From 23b420865ea6af7a1a989c0dc6501e874ae80774 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Wed, 21 Oct 2026 23:54:07 +0000 Subject: [PATCH 1/2] Start a rolling service that has nothing to roll from Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +++ SPEC.md | 2 ++ src/flow_deploy/deploy.py | 20 ++++++++++--- tests/fake_host.py | 11 ++++++-- tests/integration/test_deploys.py | 26 +++++++++++++++++ tests/test_new_service.py | 47 +++++++++++++++++++++++++++++++ 6 files changed, 103 insertions(+), 7 deletions(-) create mode 100644 tests/test_new_service.py diff --git a/README.md b/README.md index ed0d6d9..8a2f79f 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/SPEC.md b/SPEC.md index 539020b..c22c9d1 100644 --- a/SPEC.md +++ b/SPEC.md @@ -71,6 +71,8 @@ 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 =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. **On success:** the server is in detached HEAD at ``, and `.git/deploy-tag` records the tag (§2.8). Log `HEAD detached at `. diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 32c2b76..2efbd7d 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -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: @@ -574,16 +579,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. diff --git a/tests/fake_host.py b/tests/fake_host.py index b7a1ad7..43156d5 100644 --- a/tests/fake_host.py +++ b/tests/fake_host.py @@ -247,10 +247,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) diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index 32e12f0..1d821f0 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -559,3 +559,29 @@ 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")]} diff --git a/tests/test_new_service.py b/tests/test_new_service.py new file mode 100644 index 0000000..c4116ea --- /dev/null +++ b/tests/test_new_service.py @@ -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"]]} From 769ed3462296df09bf7da4510affce49683f33b1 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Wed, 21 Oct 2026 23:54:07 +0000 Subject: [PATCH 2/2] Add deploy.post-deploy hooks Co-Authored-By: Claude Opus 5.5 --- README.md | 24 ++++++++ SPEC.md | 24 ++++++-- src/flow_deploy/config.py | 3 + src/flow_deploy/deploy.py | 39 +++++++++++++ tests/fake_host.py | 3 + tests/integration/test_deploys.py | 18 ++++++ tests/test_post_deploy.py | 91 +++++++++++++++++++++++++++++++ 7 files changed, 197 insertions(+), 5 deletions(-) create mode 100644 tests/test_post_deploy.py diff --git a/README.md b/README.md index 8a2f79f..e8abdc8 100644 --- a/README.md +++ b/README.md @@ -117,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 sh -c ''`, 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 diff --git a/SPEC.md b/SPEC.md index c22c9d1..c3c9712 100644 --- a/SPEC.md +++ b/SPEC.md @@ -75,6 +75,8 @@ A rolling service with no running container (new in this release, or stopped) ha 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 ``, and `.git/deploy-tag` records the tag (§2.8). Log `HEAD detached at `. **On failure** (a failed step, a signal, or an unexpected error), the deploy reverts: @@ -243,9 +245,20 @@ Environment variable overrides exist because `x-deploy` values are committed to The GitHub Action (§7) reads these values by running ` 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 ` exec -T sh -c ''` 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 @@ -723,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 | @@ -804,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). --- @@ -820,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 ` 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. diff --git a/src/flow_deploy/config.py b/src/flow_deploy/config.py index db175c6..5059f68 100644 --- a/src/flow_deploy/config.py +++ b/src/flow_deploy/config.py @@ -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: @@ -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, ) ) diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 2efbd7d..d6d8306 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -338,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("") @@ -346,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. @@ -947,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") diff --git a/tests/fake_host.py b/tests/fake_host.py index 43156d5..12c521a 100644 --- a/tests/fake_host.py +++ b/tests/fake_host.py @@ -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] @@ -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): diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index 1d821f0..36308a6 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -585,3 +585,21 @@ def test_stopped_rolling_service_comes_back_on_the_new_tag(stack): 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"]} diff --git a/tests/test_post_deploy.py b/tests/test_post_deploy.py new file mode 100644 index 0000000..a16a585 --- /dev/null +++ b/tests/test_post_deploy.py @@ -0,0 +1,91 @@ +"""deploy.post-deploy: a command run once in a service's new container after a deploy.""" + +import signal + +import pytest + +from flow_deploy import config +from flow_deploy.deploy import deploy +from tests.fake_host import COMPOSE_CMD, FakeHost +from tests.helpers import app, chdir, record, stack + +SETUP = "python manage.py setup_pages" + + +def hooked(order=100, hook=SETUP, **kwargs): + svc = app(order, **kwargs) + svc["labels"]["deploy.post-deploy"] = hook + return svc + + +@pytest.fixture +def host(monkeypatch, tmp_path): + """web (hooked) then worker on v1.""" + chdir(monkeypatch, tmp_path) + compose = stack(web=hooked(100), worker=app(200)) + return FakeHost(compose, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + + +def test_parse_post_deploy(): + compose = stack( + web=hooked(100), worker=app(200), blank=hooked(300, hook=""), env=hooked(400, hook="$$X") + ) + hooks = {s.name: s.post_deploy for s in config.parse_services(compose)} + # $$ is how compose config prints a literal $. + assert hooks == {"web": SETUP, "worker": None, "blank": None, "env": "$X"} + + +def test_hook_runs_once_in_the_service_after_every_service_is_healthy(host, tmp_path, capsys): + host.exec_output = "Setting up CMS pages...\nDone.\n" + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + hook = f"exec -T web sh -c {SETUP}" + assert [c for c in host.commands() if "exec" in c] == [f"docker compose {hook}"] + assert host.index(hook) > host.index("--scale worker=1 worker") + assert host.envs[host.index(hook)] == {"DEPLOY_TAG": "v2"} + out = capsys.readouterr().out + assert "running: python manage.py setup_pages" in out + assert " Setting up CMS pages..." in out + assert "✓ web post-deploy done" in out + assert record(tmp_path)["tag"] == "v2" + + +def test_hooks_run_in_deploy_order(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + compose = stack(worker=hooked(200, hook="warm"), web=hooked(100, hook="seed")) + host = FakeHost(compose, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.index("exec -T web sh -c seed") < host.index("exec -T worker sh -c warm") + + +def test_failing_hook_warns_and_the_deploy_still_succeeds(host, monkeypatch, capsys): + monkeypatch.setenv("GITHUB_ACTIONS", "true") + host.fail("exec -T web") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"], "worker": ["v2"]} + captured = capsys.readouterr() + assert "::warning::web's post-deploy hook exited 1; the deploy itself succeeded" in captured.out + assert "injected failure" in captured.out + + +def test_interrupted_hook_warns_without_reverting(host, capsys): + host.before("exec -T web", lambda: signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None)) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"], "worker": ["v2"]} + assert host.sha == "v2" + assert "post-deploy hooks interrupted by signal 15" in capsys.readouterr().err + + +def test_hooks_do_not_run_when_the_deploy_fails(host): + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert not any("exec" in c for c in host.commands()) + + +def test_service_filter_runs_only_selected_services_hooks(host): + assert deploy(tag="v2", services_filter=["worker"], cmd=COMPOSE_CMD) == 0 + assert not any("exec" in c for c in host.commands()) + + +def test_dry_run_shows_the_hook(host, capsys): + assert deploy(tag="v2", dry_run=True, cmd=COMPOSE_CMD) == 0 + assert "would run: python manage.py setup_pages" in capsys.readouterr().out