Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ For each `deploy.role=app` service, in order:
4. **Cutover** — if healthy, gracefully drain the old container and scale back to 1
5. **Abort** — if unhealthy, remove the new container. Old container is untouched.

A service with no running container (new in this release, or stopped) has
nothing to roll from: it's pulled, started at one container, and must pass its
health check.

## Service Roles

| Label | Behavior |
Expand All @@ -113,6 +117,30 @@ All configuration is via Docker labels on your services:
| `deploy.healthcheck.poll` | `2` | Seconds between health polls |
| `deploy.healthcheck.skip` | `false` | Skip healthcheck validation and waiting |
| `deploy.strategy` | `rolling` | `rolling` or `drain-first` (see below) |
| `deploy.post-deploy` | — | Command to run in the service after a deploy (see below) |

### Post-deploy hooks

`deploy.post-deploy` runs a command once in the service's new container after a
successful deploy: content seeding, cache warming, notifications.

```yaml
services:
web:
labels:
deploy.role: app
deploy.post-deploy: python manage.py setup_pages
```

Hooks run with `compose exec -T <service> sh -c '<command>'`, in `deploy.order`,
once every service is up and healthy, and their output goes in the deploy log.
Write `$$` for a literal `$`, as anywhere in a compose file. A hook that fails
(or is interrupted) only warns: the deploy has already succeeded, and reverting
healthy containers wouldn't undo what the hook did. So keep them idempotent.
For several commands, chain them (`a && b`) or call a script in the image. A
failed deploy runs no hooks, and `--service` runs only the hooks of the services
it deploys. Migrations stay in the app's boot sequence: they must run before
new code serves, and a hook runs after.

### Drain-first services

Expand Down
26 changes: 21 additions & 5 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,12 @@ The snapshot is what a revert restores: the image each service was running, name
✗ Revert (below), exit 1
```

A rolling service with no running container (new in this release, or stopped) has nothing to roll from: it is pulled, started at one replica (`up -d --no-deps --scale <service>=1`) and health-checked; on failure it is removed. Scaling it to 2 would start two new containers and no old one to tell apart.

Services labelled `deploy.strategy=drain-first` are instead stopped before any rolling service and started after them; see §2.5.

After every service is up and healthy, post-deploy hooks run (§2.7).

**On success:** the server is in detached HEAD at `<tag>`, and `.git/deploy-tag` records the tag (§2.8). Log `HEAD detached at <tag>`.

**On failure** (a failed step, a signal, or an unexpected error), the deploy reverts:
Expand Down Expand Up @@ -241,9 +245,20 @@ Environment variable overrides exist because `x-deploy` values are committed to

The GitHub Action (§7) reads these values by running `<compose-command> config` in CI, which outputs the fully merged YAML with all overrides applied. It then groups services by host, applies any environment variable overrides, and SSHes to each one.

### 2.7 Pre-Deploy and Post-Deploy Hooks
### 2.7 Post-Deploy Hooks

A `deploy.post-deploy` label on an app service names a shell command to run once in that service after a successful deploy:

```yaml
web:
labels:
deploy.role: app
deploy.post-deploy: python manage.py setup_pages
```

Once every service is up and healthy, the deploy runs `<compose-command> exec -T <service> sh -c '<command>'` for each hooked service it deployed, in `deploy.order`, and logs the output. `$$` is a literal `$`, as everywhere in compose. The deploy has already succeeded by then, so a hook that fails or is interrupted logs a warning and the deploy still exits 0: reverting healthy containers wouldn't undo whatever the hook did. A failed deploy runs no hooks.

*Deferred to v2 (see §12.3).* Hook support (pre-deploy commands like migrations, post-deploy commands like cache warming) is a natural extension but not required for v1. Migrations are left to the framework's own boot sequence or manual execution via `flow-deploy exec`.
Pre-deploy hooks remain deferred (§12.3). Migrations are left to the framework's own boot sequence or manual execution via `flow-deploy exec`.

### 2.8 Versioning and Image Tags

Expand Down Expand Up @@ -721,6 +736,7 @@ The tool has zero configuration files. All behavior is controlled by `x-deploy`
| `deploy.dir` | No | `x-deploy.dir` | Project directory on remote host |
| `deploy.order` | No | `100` | Deploy order (lower first) |
| `deploy.strategy` | No | `rolling` | `rolling` or `drain-first` (§2.5) |
| `deploy.post-deploy` | No | *(none)* | Command run in the service after a deploy (§2.7) |
| `deploy.drain` | No | `30` | Seconds to wait after SIGTERM before SIGKILL |
| `deploy.healthcheck.timeout` | No | `120` | Seconds before aborting |
| `deploy.healthcheck.poll` | No | `2` | Seconds between polls |
Expand Down Expand Up @@ -802,9 +818,9 @@ If a service is already scaled to N (e.g., 3 workers), the rolling deploy should
|---|---|---|
| `deploy.scale` | `1` | Number of instances for this service |

### 12.3 Pre-Deploy and Post-Deploy Hooks
### 12.3 Pre-Deploy Hooks

Hook support for pre-deploy commands (migrations, asset compilation) and post-deploy commands (cache warming, notifications). Deferred from v1 — migrations are handled by the framework's own boot sequence or via manual `flow-deploy exec`.
Pre-deploy commands (migrations, asset compilation). Deferred: migrations are handled by the framework's own boot sequence or via manual `flow-deploy exec`. Post-deploy hooks shipped (§2.7).

---

Expand All @@ -818,6 +834,6 @@ Captured here for context on why v1 works the way it does:

3. **Traefik drain:** Graceful shutdown is the default behavior. `docker stop --time <drain>` sends SIGTERM and waits (default 30s) before SIGKILL. Configurable via `deploy.drain` label.

4. **Hook complexity:** Deferred to v2. Not needed for v1 — migrations are handled by the framework or via manual `flow-deploy exec`.
4. **Hook complexity:** Post-deploy hooks are one label per service, run in the new container, and only warn on failure (§2.7). Pre-deploy hooks stay deferred: migrations are handled by the framework or via manual `flow-deploy exec`.

5. **Fleet coordination:** The server-side tool (`flow-deploy`) is single-node by design. Multi-node coordination is handled by the GitHub Action (`flow-deploy-action`), which discovers hosts from compose labels and orchestrates via SSH. v2's two-phase deploy (`prepare` / `cutover` / `cancel`) gives the action the primitives it needs for coordinated fleet deploys.
3 changes: 3 additions & 0 deletions src/flow_deploy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class ServiceConfig:
port: int | None = None
dir: str | None = None
strategy: str = "rolling"
post_deploy: str | None = None # shell command run in the service after a deploy

@property
def is_app(self) -> bool:
Expand Down Expand Up @@ -106,6 +107,8 @@ def parse_services(compose_dict: dict) -> list[ServiceConfig]:
port=port,
dir=svc_dir,
strategy=_get_label(labels, "deploy.strategy", "rolling"),
# compose config keeps $ escaped as $$, so the output re-parses.
post_deploy=_get_label(labels, "deploy.post-deploy", "").replace("$$", "$") or None,
)
)

Expand Down
59 changes: 55 additions & 4 deletions src/flow_deploy/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,12 @@ def failed(reason: str) -> int:
# health wait, say) then rolls it back like any shipped service,
# which keeps an old container that's still running.
run.shipped.append(svc.name)
result = _deploy_service(svc, tag, compose_cmd, project=project)
if run.previous[svc.name].replicas:
result = _deploy_service(svc, tag, compose_cmd, project=project)
else:
# Nothing to roll from (just added in this release, or crashed):
# scaling to 2 would start two new containers and no old one.
result = _start_service(svc, tag, compose_cmd, project=project, pull=True)
if result == SVC_DIRTY:
dirty.append(svc.name)
if result != SVC_OK and run.previous[svc.name].replicas:
Expand Down Expand Up @@ -333,6 +338,8 @@ def failed(reason: str) -> int:
"on this host need DEPLOY_TAG set explicitly until a full deploy"
)

_post_deploy(app_services, tag, compose_cmd)

elapsed = time.time() - start_time

log.info("")
Expand All @@ -341,6 +348,39 @@ def failed(reason: str) -> int:
return EXIT_OK


def _post_deploy(services: list[config.ServiceConfig], tag: str, compose_cmd: list[str]) -> None:
"""Run each service's deploy.post-deploy command once, in its new container.

In deploy order, once every service is up and healthy. The deploy has
already succeeded, so a hook that fails (or is interrupted) only warns:
reverting healthy containers wouldn't undo whatever the hook did.
"""
try:
for svc in [s for s in services if s.post_deploy]:
log.service_start(f"{svc.name} post-deploy")
log.step(f"running: {svc.post_deploy}")
result = compose.compose_run(
["exec", "-T", svc.name, "sh", "-c", svc.post_deploy],
env={"DEPLOY_TAG": tag},
cmd=compose_cmd,
)
for line in (result.stdout + result.stderr).splitlines():
log.step(f" {line}")
if result.returncode == 0:
log.success(f"{svc.name} post-deploy done")
else:
log.warning(
f"{svc.name}'s post-deploy hook exited {result.returncode}; "
"the deploy itself succeeded"
)
log.service_end()
except Interrupted as exc:
log.service_end()
log.warning(
f"post-deploy hooks interrupted by signal {exc.signum}; the deploy itself succeeded"
)


def _warn_untagged_images(services: list[config.ServiceConfig], tag: str) -> None:
"""Warn about app images that don't follow DEPLOY_TAG.

Expand Down Expand Up @@ -574,16 +614,23 @@ def _start_service(
compose_cmd: list[str],
replicas: int = 1,
project: str = "",
pull: bool = False,
) -> int:
"""Start a drained service on the new tag at ``replicas`` and wait for health.
"""Start a service with no running containers on the new tag, at ``replicas``; wait for health.

Returns SVC_OK, or SVC_FAILED / SVC_DIRTY after removing what it started
(DIRTY when that removal itself failed).
For a drained service (already pulled by its drain), or with ``pull`` a
rolling service that had no container to roll from. Returns SVC_OK, or
SVC_FAILED / SVC_DIRTY after removing what it started (DIRTY when that
removal itself failed).
"""
log.service_start(svc.name)
svc_start = time.time()
env = {"DEPLOY_TAG": tag}

if pull and not _pull(svc, env, compose_cmd):
log.service_end()
return SVC_FAILED

def fail(msg: str, ctrs: list[dict]) -> int:
# Remove what started: an unhealthy worker may still be consuming,
# and a restore on an unchanged config would otherwise reuse it.
Expand Down Expand Up @@ -935,4 +982,8 @@ def _dry_run(tag: str, services: list[config.ServiceConfig]) -> None:
log.service_start(svc.name)
log.step(f"would start on {tag}, health check (timeout: {svc.healthcheck_timeout}s)")
log.service_end()
for svc in [s for s in services if s.post_deploy]:
log.service_start(f"{svc.name} post-deploy")
log.step(f"would run: {svc.post_deploy}")
log.service_end()
log.footer("dry-run complete")
14 changes: 11 additions & 3 deletions tests/fake_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def __init__(self, compose: dict, running: dict | None = None, project: str = "p
# Like a fail-closed script/prod: a compose call without DEPLOY_TAG fails.
self.wrapper_requires_tag = True
self.streamed: list[tuple[list[str], dict | None]] = [] # run_streaming calls
self.exec_output = "" # what compose exec prints
self.other_projects: list[str] = [] # other projects running these services here
self.foreign_services: list[tuple[str, str]] = [] # (project, service) running here
self.failures: list[list] = [] # [substring, skip, remaining or None]
Expand Down Expand Up @@ -218,6 +219,8 @@ def _compose(self, args, tag):
return ok()
if args[:1] == ["up"]:
return self._up(args, tag)
if args[:1] == ["exec"]:
return ok(self.exec_output)
raise AssertionError(f"FakeHost: unexpected compose {args}")

def _rendered(self, tag):
Expand Down Expand Up @@ -247,10 +250,15 @@ def _up(self, args, tag):
return ok()
live = self._live(service)
if "--no-recreate" not in args:
for ctr in [c for c in live if c.tag != tag]:
# Compose recreates every container whose config has changed,
# stopped ones included (which then start on the new config).
for ctr in [c for c in self.ctrs if c.service == service and c.tag != tag]:
self.ctrs.remove(ctr)
live.remove(ctr)
live.append(self.add(service, tag))
if ctr in live:
live.remove(ctr)
live.append(self.add(service, tag))
elif ctr.state == "exited":
self.add(service, tag, state="exited")
while len(live) > replicas: # compose removes the newest extras
newest = max(live, key=lambda c: c.created)
self.ctrs.remove(newest)
Expand Down
44 changes: 44 additions & 0 deletions tests/integration/test_deploys.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,3 +559,47 @@ def test_flow_deploy_never_leaves_the_wrapper_to_find_deploy_tag(stack):
ran = stack.flow(*args)
assert ran.returncode == 0, (args, ran.stderr)
assert "script/prod: set DEPLOY_TAG" not in ran.stderr


def test_first_deploy_of_a_new_rolling_service(stack):
"""Nothing to roll from: it starts on the new tag instead of failing to
tell two new containers apart (flowcanon.com 2.2.3's scheduler)."""
stack.commit("v1", standard(scheduler=None, worker=None))
stack.commit("v2", standard(scheduler=None, worker=None, api=service(150)))
stack.up("v1")

result = stack.deploy("v2")

assert result.returncode == 0, result.stdout + result.stderr
assert stack.running() == {"web": ["v2"], "api": ["v2"]}
assert stack.record()["tag"] == "v2"


def test_stopped_rolling_service_comes_back_on_the_new_tag(stack):
stack.commit("v1", standard(scheduler=None, worker=None))
stack.commit("v2", standard(scheduler=None, worker=None))
stack.up("v1")
stack.compose("stop", "web", tag="v1")

result = stack.deploy("v2")

assert result.returncode == 0, result.stdout + result.stderr
assert stack.state() == {"web": [("v2", "running")]}


def test_post_deploy_hook_runs_in_the_new_container(stack):
web = service(100)
# $$: compose would otherwise interpolate it from the host's environment.
web["labels"]["deploy.post-deploy"] = "echo hooked on $$STUB_VERSION; exit 3"
stack.commit("v1", standard(scheduler=None, worker=None))
stack.commit("v2", standard(web=web, scheduler=None, worker=None))
stack.up("v1")

result = stack.deploy("v2")

# The hook ran once, after the cutover, in the v2 container; its failure
# only warns.
assert result.returncode == 0, result.stdout + result.stderr
assert result.stdout.count("hooked on v2") == 1, result.stdout
assert "web's post-deploy hook exited 3" in result.stderr
assert stack.running() == {"web": ["v2"]}
47 changes: 47 additions & 0 deletions tests/test_new_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""A rolling service with no container to roll from (just added, or crashed)."""

from flow_deploy.deploy import deploy
from tests.fake_host import COMPOSE_CMD, FakeHost
from tests.helpers import app, chdir, record, stack

# A release that adds a scheduler beside the web already running.
ADDED = stack(web=app(100), scheduler=app(200))


def host_with(monkeypatch, tmp_path, running):
chdir(monkeypatch, tmp_path)
return FakeHost(ADDED, running=running).install(monkeypatch)


def test_new_rolling_service_starts_on_the_new_tag(monkeypatch, tmp_path):
host = host_with(monkeypatch, tmp_path, {"web": ["v1"]})
assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0
assert host.running() == {"web": ["v2"], "scheduler": ["v2"]}
assert record(tmp_path)["tag"] == "v2"
# One container, not two new ones with no old to tell apart.
assert not any("--scale scheduler=2" in c for c in host.commands())
assert host.index("pull scheduler") < host.index("--scale scheduler=1 scheduler")


def test_crashed_rolling_service_comes_back_on_the_new_tag(monkeypatch, tmp_path):
host = host_with(monkeypatch, tmp_path, {"web": ["v1"]})
host.add("scheduler", "v1", state="exited")
assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0
assert host.running() == {"web": ["v2"], "scheduler": ["v2"]}


def test_unhealthy_new_service_is_removed_and_the_rest_reverted(monkeypatch, tmp_path, capsys):
host = host_with(monkeypatch, tmp_path, {"web": ["v1"]})
host.unhealthy_services.add(("scheduler", "v2"))
assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1
assert host.running_images() == {"web": [host.images["v1"]]}
assert host.sha == "prev123abc"
assert "scheduler unhealthy; stopping and removing it" in capsys.readouterr().out


def test_unpullable_new_service_fails_before_starting(monkeypatch, tmp_path):
host = host_with(monkeypatch, tmp_path, {"web": ["v1"]})
host.fail("pull scheduler")
assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1
assert not any("--scale scheduler" in c for c in host.commands())
assert host.running_images() == {"web": [host.images["v1"]]}
Loading
Loading