Skip to content

Commit

Permalink
🌱 Refactoring of tilt's live reload system.
Browse files Browse the repository at this point in the history
  • Loading branch information
batistein committed Dec 16, 2021
1 parent b9c57c7 commit 552d6af
Show file tree
Hide file tree
Showing 18 changed files with 564 additions and 26 deletions.
35 changes: 9 additions & 26 deletions Tiltfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- mode: Python -*-
load("ext://uibutton", "cmd_button", "location")
load('ext://restart_process', 'docker_build_with_restart')

yq_cmd = "./hack/tools/bin/yq"
kustomize_cmd = "./hack/tools/bin/kustomize"
Expand All @@ -20,11 +21,10 @@ settings = {
"deploy_observability": False,
"preload_images_for_kind": True,
"kind_cluster_name": "caph",
"capi_version": "v1.0.1",
"capi_version": "v1.0.2",
"cabpt_version": "v0.5.0",
"cacppt_version": "v0.4.0-alpha.0",
"cert_manager_version": "v1.1.0",
"kubernetes_version": "v1.21.1",
"kustomize_substitutions": {
"REGION": "fsn1",
"CONTROL_PLANE_MACHINE_COUNT": "3",
Expand Down Expand Up @@ -133,26 +133,15 @@ def set_env_variables():
for key, val in arr:
os.putenv(key, val)

def deploy_hetzner_token():
def deploy_hetzner_secret():
substitutions = settings.get("kustomize_substitutions", {})
token = substitutions.get("HCLOUD_TOKEN")
local("kubectl create secret generic hetzner-token --from-literal=token=%s --dry-run=client -o yaml | kubectl apply -f -" % token)

tilt_helper_dockerfile_header = """
# Tilt image
FROM golang:1.16 as tilt-helper
# Support live reloading with Tilt
RUN wget --output-document /restart.sh --quiet https://raw.githubusercontent.com/windmilleng/rerun-process-wrapper/master/restart.sh && \
wget --output-document /start.sh --quiet https://raw.githubusercontent.com/windmilleng/rerun-process-wrapper/master/start.sh && \
chmod +x /start.sh && chmod +x /restart.sh
"""
hcloud = substitutions.get("HCLOUD_TOKEN")
local("kubectl create secret generic hetzner --from-literal=hcloud=%s --dry-run=client -o yaml | kubectl apply -f -" % hcloud)

## This should have the same versions as the Dockerfile
tilt_dockerfile_header = """
FROM gcr.io/distroless/base:debug as tilt
WORKDIR /
COPY --from=tilt-helper /start.sh .
COPY --from=tilt-helper /restart.sh .
COPY manager .
"""

Expand All @@ -178,28 +167,22 @@ def caph():
labels = ["CAPH"],
)

dockerfile_contents = "\n".join([
tilt_helper_dockerfile_header,
tilt_dockerfile_header,
])

entrypoint = ["sh", "/start.sh", "/manager"]
entrypoint = ["/manager"]
extra_args = settings.get("extra_args")
if extra_args:
entrypoint.extend(extra_args)

# Set up an image build for the provider. The live update configuration syncs the output from the local_resource
# build into the container.
docker_build(
docker_build_with_restart(
ref = "quay.io/syself/cluster-api-provider-hetzner",
context = "./.tiltbuild/",
dockerfile_contents = dockerfile_contents,
dockerfile_contents = tilt_dockerfile_header,
target = "tilt",
entrypoint = entrypoint,
only = "manager",
live_update = [
sync(".tiltbuild/manager", "/manager"),
run("sh /restart.sh"),
],
ignore = ["templates"],
)
Expand Down Expand Up @@ -296,7 +279,7 @@ deploy_capi()

set_env_variables()

deploy_hetzner_token()
deploy_hetzner_secret()

caph()

Expand Down
5 changes: 5 additions & 0 deletions tilt_modules/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
"Name": "uibutton",
"ExtensionRegistry": "https://github.com/tilt-dev/tilt-extensions",
"TimeFetched": "2021-10-27T19:41:46.910172135+02:00"
},
{
"Name": "restart_process",
"ExtensionRegistry": "https://github.com/tilt-dev/tilt-extensions",
"TimeFetched": "2021-12-08T20:30:04.816016504+01:00"
}
]
}
1 change: 1 addition & 0 deletions tilt_modules/restart_process/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
test
1 change: 1 addition & 0 deletions tilt_modules/restart_process/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tilt-restart-wrapper
19 changes: 19 additions & 0 deletions tilt_modules/restart_process/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
FROM alpine as entr-build

RUN apk update && apk add make git build-base

RUN git clone https://github.com/eradman/entr.git /entr
WORKDIR /entr
RUN git checkout c564e6bdca1dfe2177d1224363cad734158863ad
RUN cp Makefile.linux Makefile
RUN CFLAGS="-static" make install

FROM golang as go-build
WORKDIR /src
ADD ./tilt-restart-wrapper.go ./tilt-restart-wrapper.go
RUN GO111MODULE=auto go build ./tilt-restart-wrapper.go

FROM scratch

COPY --from=entr-build /usr/local/bin/entr /
COPY --from=go-build /src/tilt-restart-wrapper /
181 changes: 181 additions & 0 deletions tilt_modules/restart_process/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
# Restart Process

This extension helps create images that can restart on `live_update`:

- `docker_build_with_restart`: wraps a `docker_build` call
- `custom_build_with_restart`: wraps a `custom_build` call

At the end of a `live_update`, the container's process will rerun itself.

(Use it in place of the `restart_container()` Live Update step, which has been deprecated for Kubernetes resources.)

## When to Use
Use this extension when you have an image and you want to re-execute its entrypoint/command as part of a `live_update`.

E.g. if your app is a static binary, you'll probably need to re-execute the binary for any changes you made to take effect.

(If your app has hot reloading capabilities--i.e. it can detect and incorporate changes to its source code without needing to restart--you probably don't need this extension.)

### Unsupported Cases
This extension does NOT support process restarts for:
- Images built with `custom_build` using any of the `skips_local_docker`, `disable_push`, or `tag` parameters.
- Images run in Docker Compose resources (use the [`restart_container()`](https://docs.tilt.dev/api.html#api.restart_container) builtin instead)
- Images without a shell (e.g. `scratch`, `distroless`)
- Container commands specified as `command` in Kubernetes YAML will be overridden by this extension.
- However, the `args` field is still available; [reach out](https://tilt.dev/contact) if you need help navigating the interplay between Tilt and these YAML values
- CRDs

If this extension doesn't work for your use case, [see our docs for alternatives](https://docs.tilt.dev/live_update_reference.html#restarting-your-process).

Run into a bug? Need a use case that we don't yet support? Let us know--[open an issue](https://github.com/tilt-dev/tilt-extensions/issues) or [contact us](https://tilt.dev/contact).

## How to Use

Import this extension by putting the following at the top of your Tiltfile:
```python
load('ext://restart_process', 'docker_build_with_restart')
```

For the image that needs the process restart, replace your existing `docker_build` call:
```python
docker_build(
'foo-image',
'./foo',
arg1=val1,
arg2=val2,
live_update=[x, y, z...]
)
```
with a `docker_build_with_restart` call:
```python
docker_build_with_restart(
'foo-image',
'./foo',
entrypoint='/go/bin/foo',
arg1=val1,
arg2=val2,
live_update=[x, y, z...]
)
```
The call above looks just like the initial `docker_build` call except for one added parameter, `entrypoint` (in this example, `/go/bin/foo`). This is the command that you want to run on container start and _re-run_ on Live Update.

A custom_build call looks similar:

```python
load('ext://restart_process', 'custom_build_with_restart')

custom_build_with_restart(
'foo-image',
'docker build -t $EXPECTED_REF ./foo',
deps=['./foo'],
live_update=[sync(...)]
)
```

### Troubleshooting
#### `failed running [touch /tmp/.restart-proc']`
If you see an error of the form:
```
ERROR: Build Failed: ImageBuild: executor failed running [touch /tmp/.restart-proc']: exit code: 1
```
this often means that your Dockerfile user ([see docs](https://docs.docker.com/engine/reference/builder/#user)) doesn't have permission to write to the file we use to signal a process restart. Use the `restart_file` parameter to specify a file that your Dockerfile user definitely has write access to.

### API
```python
def docker_build_with_restart(ref: str, context: str,
entrypoint: Union[str, List[str]],
live_update: List[LiveUpdateStep],
base_suffix: str = '-base',
restart_file: str = '/.restart-proc',
trigger: Union[str, List[str]] = [],
**kwargs
):
"""Args:
ref: name for this image (e.g. 'myproj/backend' or 'myregistry/myproj/backend'); as the parameter of the same name in docker_build
context: path to use as the Docker build context; as the parameter of the same name in docker_build
entrypoint: the command to be (re-)executed when the container starts or when a live_update is run
live_update: set of steps for updating a running container; as the parameter of the same name in docker_build
base_suffix: suffix for naming the base image, applied as {ref}{base_suffix}
restart_file: file that Tilt will update during a live_update to signal the entrypoint to rerun
trigger: (optional) list of local paths. If specified, the process will ONLY be restarted when there are changes
to the given file(s); as the parameter of the same name in the LiveUpdate `run` step.
**kwargs: will be passed to the underlying `docker_build` call
"""


def custom_build_with_restart(ref: str, command: str, deps: List[str], entrypoint,

entrypoint: Union[str, List[str]],
live_update: List[LiveUpdateStep],
base_suffix: str = '-base',
restart_file: str = '/.restart-proc',
trigger: Union[str, List[str]] = [],
, **kwargs
):
"""
Args:
ref: name for this image (e.g. 'myproj/backend' or 'myregistry/myproj/backend'); as the parameter of the same name in custom_build
command: build command for building your image
deps: source dependencies of the custom build
entrypoint: the command to be (re-)executed when the container starts or when a live_update is run
live_update: set of steps for updating a running container; as the parameter of the same name in custom_build
base_suffix: suffix for naming the base image, applied as {ref}{base_suffix}
restart_file: file that Tilt will update during a live_update to signal the entrypoint to rerun
trigger: (optional) list of local paths. If specified, the process will ONLY be restarted when there are changes
to the given file(s); as the parameter of the same name in the LiveUpdate `run` step.
**kwargs: will be passed to the underlying `custom_build` call
"""
```

## What's Happening Under the Hood
*If you're a casual user/just want to get your app running, you can stop reading now. However, if you want to dig deep and know exactly what's going on, or are trying to debug weird behavior, read on.*

This extension wraps commands in `tilt-restart-wrapper`, which makes use of [`entr`](https://github.com/eradman/entr/)
to run arbitrary commands whenever a specified file changes. Specifically, we override the container's entrypoint with the following:

```
/tilt-restart-wrapper --watch_file='/.restart-proc' <entrypoint>
```

This invocation says:
- when the container starts, run <entrypoint>
- whenever the `/.restart-proc` file changes, re-execute <entrypoint>

We also set the following as the last `live_update` step:
```python
run('date > /.restart-proc')
```

Because `tilt-restart-wrapper` will re-execute the entrypoint whenever `/.restart-proc'` changes, the above `run` step will cause the entrypoint to re-run.

#### Provide `tilt-restart-wrapper`
For this all to work, the `entr` binary must be available on the Docker image. The easiest solution would be to call e.g. `apt-get install entr` in the Dockerfile, but different base images will have different package managers; rather than grapple with that, we've made a statically linked binary available on Docker image: [`tiltdev/entr`](https://hub.docker.com/repository/docker/tiltdev/entr).

To build `image-foo`, this extension will:
- build your image as normal (via `docker_build`, with all of your specified args/kwargs) but with the name `image-foo-base`
- build `image-foo` (the actual image that will be used in your resource) as a _child_ of `image-foo-base`, with the `tilt-process-wrapper` and its dependencies available

Thus, the final image produced is tagged `image-foo` and has all the properties of your original `docker_build`, plus access to the `tilt-restart-wrapper` binary.

#### Why a Wrapper?
Why bother with `tilt-restart-wrapper` rather than just calling `entr` directly?

Because in its canonical invocation, `entr` requires that the file(s) to watch be piped via stdin, i.e. it is invoked like:
```
echo "/.restart-proc" | entr -rz /bin/my-app
```

When specified as a `command` in Kubernetes or Docker Compose YAML (this is how Tilt overrides entrypoints), the above would therefore need to be executed as shell:
```
/bin/sh -c 'echo "/.restart-proc" | entr -rz /bin/my-app'
```
Any `args` specified in Kubernetes/Docker Compose are attached to the end of this call, and therefore in this case would apply TO THE `/bin/sh -c` CALL, rather than to the actual command run by `entr`; that is, any `args` specified by the user would be effectively ignored.

In order to make `entr` usable without a shell, this extension uses [a simple binary](/restart_process/tilt-restart-wrapper.go) that invokes `entr` and writes to its stdin.

Note: ideally `entr` could accept files-to-watch via flag instead of stdin, but (for a number of good reasons) this feature isn't likely to be added any time soon (see [entr#33](https://github.com/eradman/entr/issues/33)).

## For Maintainers: Releasing
If you have push access to the `tiltdev` repository on DockerHub, you can release a new version of the binaries used by this extension like so:
1. run `release.sh` (builds `tilt-restart-wrapper` from source, builds and pushes a Docker image with the new binary and a fresh binary of `entr` also installed from source)
2. update the image tag in the [Tiltfile](/restart_process/Tiltfile) with the tag you just pushed (you'll find the image referenced in the Dockerfile contents of the child image--look for "FROM tiltdev/restart-helper")

0 comments on commit 552d6af

Please sign in to comment.