From 50b42e61225c47f723685fdffc08a3f75de03ee6 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Thu, 8 Oct 2026 22:27:47 -0600 Subject: [PATCH 01/19] Add a drain-first deploy strategy for workers and schedulers Rolling deploys overlap old and new containers. For a queue worker that means old task code keeps running, through a drain of up to an hour, after the new web container has migrated the database. deploy.strategy: drain-first runs a service around the rolling phase: 1. Drain: pull the new image (so a bad tag fails before anything stops), then docker stop --time and remove the running containers. SIGTERM is Celery's warm shutdown. Nothing rolls until every drain finishes. 2. Roll: rolling services deploy as before. 3. Start: compose up on the new tag and wait for the health check. If the deploy fails before phase 3, drained services come back on the image tag their old containers ran, recorded before removal, so the rollback doesn't depend on how tags map to commits. A failed start has no rollback, since old code would run against the new schema; the service is left down and the deploy fails loudly. Unknown strategies are rejected. Rolling remains the default, so existing projects are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 38 +++++ src/flow_deploy/config.py | 19 +++ src/flow_deploy/deploy.py | 157 +++++++++++++++++++-- tests/test_drain_first.py | 283 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 489 insertions(+), 8 deletions(-) create mode 100644 tests/test_drain_first.py diff --git a/README.md b/README.md index ddb6e55..69acc23 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,44 @@ All configuration is via Docker labels on your services: | `deploy.healthcheck.timeout` | `120` | Seconds to wait for healthy | | `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) | + +### Drain-first services + +Rolling deploys briefly run old and new containers side by side. That's right +for web servers, but wrong for queue workers and schedulers. An old worker +that's still draining keeps running old code after the new web container has +migrated the database. + +Label those services `deploy.strategy: drain-first` and the deploy runs in three +phases: + +1. **Drain.** Each drain-first service, in `deploy.order`, pulls its new image + and then stops its running containers. Stopping is `docker stop --time + `: SIGTERM first, so Celery-style workers finish their current + tasks and stop taking new ones, then SIGKILL when the drain expires. Nothing + rolls until every drain has finished. +2. **Roll.** Every rolling service deploys as usual. +3. **Start.** Each drain-first service starts on the new tag and must pass its + health check. + +The service is down from the start of its drain until phase 3. Queued work +waits in the broker and the new worker picks it up. + +If the deploy fails before phase 3, drained services are restarted on the image +tag they were running before. If a drain-first service fails its own start, +there is no rollback: its old code would now run against whatever the rolling +phase changed. The deploy fails, the service is left down, and an operator +takes it from there. + +```yaml +services: + worker: + labels: + deploy.role: app + deploy.strategy: drain-first + deploy.drain: "3660" # longest job + margin +``` ## Host Discovery diff --git a/src/flow_deploy/config.py b/src/flow_deploy/config.py index 588e7c7..db175c6 100644 --- a/src/flow_deploy/config.py +++ b/src/flow_deploy/config.py @@ -2,6 +2,14 @@ from dataclasses import dataclass +# rolling: start the new container beside the old, health-check, then drain +# the old one. No downtime; old and new briefly overlap. +# drain-first: drain the old container before anything else in the deploy +# rolls, and start the new one after everything else has. No overlap with +# new code (or new migrations); the service is down for the deploy. For +# queue workers and schedulers. +STRATEGIES = ("rolling", "drain-first") + @dataclass class ServiceConfig: @@ -19,11 +27,16 @@ class ServiceConfig: user: str | None = None port: int | None = None dir: str | None = None + strategy: str = "rolling" @property def is_app(self) -> bool: return self.role == "app" + @property + def drains_first(self) -> bool: + return self.strategy == "drain-first" + def _get_label(labels: dict, key: str, default=None): """Get a label value, with optional default.""" @@ -92,6 +105,7 @@ def parse_services(compose_dict: dict) -> list[ServiceConfig]: user=user, port=port, dir=svc_dir, + strategy=_get_label(labels, "deploy.strategy", "rolling"), ) ) @@ -107,3 +121,8 @@ def validate_healthchecks(services: list[ServiceConfig]) -> list[str]: return [ s.name for s in services if s.is_app and not s.has_healthcheck and not s.healthcheck_skip ] + + +def validate_strategies(services: list[ServiceConfig]) -> list[str]: + """Return ``name=strategy`` for each service with an unknown deploy.strategy.""" + return [f"{s.name}={s.strategy}" for s in services if s.strategy not in STRATEGIES] diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index f1b1490..95d172c 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -84,14 +84,45 @@ def _cleanup_handler(signum, frame): project = compose_dict.get("name", "") start_time = time.time() - for svc in app_services: + drain_first = [s for s in app_services if s.drains_first] + rolling = [s for s in app_services if not s.drains_first] + + # Phase 1: drain-first services stop before anything rolls, so none of + # their old code runs beside new code or after new migrations. Each + # one's previous image tag is kept to bring it back if the deploy fails. + drained: list[tuple[config.ServiceConfig, str | None]] = [] + for svc in drain_first: + result, old_tag = _drain_service(svc, tag, compose_cmd, project=project) + if result != 0: + log.info("") + keep_lock = not git.restore(previous_sha) + _restore_drained(drained, compose_cmd) + log.footer("FAILED (deploy aborted)") + return 1 + drained.append((svc, old_tag)) + + # Phase 2: rolling services, as before. + for svc in rolling: result = _deploy_service(svc, tag, compose_cmd, project=project) if result != 0: log.info("") keep_lock = not git.restore(previous_sha) + _restore_drained(drained, compose_cmd) log.footer("FAILED (deploy aborted)") return 1 + # Phase 3: drain-first services start on the new tag. There's no + # rollback past this point: the old code would now run against + # whatever the rolling phase changed, so a failure leaves the service + # down for an operator. + for svc in drain_first: + result = _start_service(svc, tag, compose_cmd, project=project) + if result != 0: + log.info("") + keep_lock = not git.restore(previous_sha) + log.footer(f"FAILED ({svc.name} is down; rolling services deployed)") + return 1 + elapsed = time.time() - start_time log.info("") @@ -130,9 +161,112 @@ def _resolve_app_services( log.error(f"Services missing healthcheck: {', '.join(missing)}") return None + unknown = config.validate_strategies(app_services) + if unknown: + log.error( + f"Unknown deploy.strategy: {', '.join(unknown)} " + f"(expected one of: {', '.join(config.STRATEGIES)})" + ) + return None + return app_services +def _pull(svc: config.ServiceConfig, env: dict, compose_cmd: list[str]) -> bool: + image_name = (svc.image or svc.name).rsplit(":", 1)[0] + log.step(f"pulling {image_name}:{env['DEPLOY_TAG']}...") + pull_start = time.time() + result = compose.compose_run(["pull", svc.name], env=env, cmd=compose_cmd) + if result.returncode != 0: + log.failure(f"pull failed: {result.stderr.strip()}") + return False + log.step(f"pulled ({time.time() - pull_start:.1f}s)") + return True + + +def _image_tag(image: str) -> str | None: + """The tag of ``registry/name:tag``, or None when the image has no tag.""" + last = image.rsplit("/", 1)[-1] + return last.rsplit(":", 1)[1] if ":" in last else None + + +def _drain_service( + svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" +) -> tuple[int, str | None]: + """Pull the new image, then stop and remove the running containers. + + Pulls first so an unpullable tag fails before anything stops. Returns + (exit code, the old containers' image tag or None if none were running). + """ + log.service_start(svc.name) + svc_start = time.time() + env = {"DEPLOY_TAG": tag} + + if not _pull(svc, env, compose_cmd): + log.service_end() + return 1, None + + ctrs = containers.get_containers_for_service(svc.name, project=project) + old_tag = _image_tag(ctrs[0].get("Image", "")) if ctrs else None + if not ctrs: + log.step("not running; nothing to drain") + for ctr in ctrs: + ctr_id = ctr["ID"] + log.step(f"draining {ctr_id[:7]} ({svc.drain}s timeout)...") + containers.stop_container(ctr_id, timeout=svc.drain) + containers.remove_container(ctr_id) + + log.success(f"{svc.name} drained ({time.time() - svc_start:.1f}s)") + log.service_end() + return 0, old_tag + + +def _start_service( + svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" +) -> int: + """Start a drained service on the new tag and wait for it to be healthy.""" + log.service_start(svc.name) + svc_start = time.time() + env = {"DEPLOY_TAG": tag} + + log.step("starting new container...") + result = compose.compose_run(["up", "-d", "--no-deps", svc.name], env=env, cmd=compose_cmd) + ctrs = containers.get_containers_for_service(svc.name, project=project) + if result.returncode != 0 or len(ctrs) != 1: + log.failure(f"start failed: {result.stderr.strip() or f'{len(ctrs)} containers'}") + log.service_end() + return 1 + + if svc.healthcheck_skip: + log.step("healthcheck skipped (deploy.healthcheck.skip=true)") + else: + log.step(f"waiting for health check (timeout: {svc.healthcheck_timeout}s)...") + if not _wait_for_healthy(ctrs[0]["ID"], svc.healthcheck_timeout, svc.healthcheck_poll): + log.failure(f"{svc.name} unhealthy; left running for inspection") + log.service_end() + return 1 + + log.success(f"{svc.name} started ({time.time() - svc_start:.1f}s)") + log.service_end() + return 0 + + +def _restore_drained( + drained: list[tuple[config.ServiceConfig, str | None]], compose_cmd: list[str] +) -> None: + """Best-effort: bring drained services back on the tag they were running.""" + for svc, old_tag in drained: + if old_tag is None: + log.step(f"{svc.name} was not running before the deploy; leaving it stopped") + continue + log.step(f"restoring {svc.name} on {old_tag}...") + result = compose.compose_run( + ["up", "-d", "--no-deps", svc.name], env={"DEPLOY_TAG": old_tag}, cmd=compose_cmd + ) + if result.returncode != 0: + log.failure(f"could not restore {svc.name}: {result.stderr.strip()}") + + def _deploy_service( svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" ) -> int: @@ -143,15 +277,9 @@ def _deploy_service( env = {"DEPLOY_TAG": tag} # 1. Pull - image_name = (svc.image or svc.name).rsplit(":", 1)[0] - log.step(f"pulling {image_name}:{tag}...") - pull_start = time.time() - result = compose.compose_run(["pull", svc.name], env=env, cmd=compose_cmd) - if result.returncode != 0: - log.failure(f"pull failed: {result.stderr.strip()}") + if not _pull(svc, env, compose_cmd): log.service_end() return 1 - log.step(f"pulled ({time.time() - pull_start:.1f}s)") # 2. Scale to 2 log.step("starting new container...") @@ -251,7 +379,16 @@ def _dry_run(tag: str, services: list[config.ServiceConfig]) -> None: log.info(f"tag: {tag}") log.info(f"services: {', '.join(s.name for s in services)}") log.info("") + drain_first = [s for s in services if s.drains_first] + for svc in drain_first: + log.service_start(svc.name) + image_name = (svc.image or svc.name).rsplit(":", 1)[0] + log.step(f"would pull {image_name}:{tag}") + log.step(f"would drain running containers first ({svc.drain}s timeout)") + log.service_end() for svc in services: + if svc.drains_first: + continue log.service_start(svc.name) image_name = (svc.image or svc.name).rsplit(":", 1)[0] log.step(f"would pull {image_name}:{tag}") @@ -259,4 +396,8 @@ def _dry_run(tag: str, services: list[config.ServiceConfig]) -> None: log.step(f"would drain old container ({svc.drain}s timeout)") log.step("would scale back to 1") log.service_end() + for svc in drain_first: + log.service_start(svc.name) + log.step(f"would start on {tag}, health check (timeout: {svc.healthcheck_timeout}s)") + log.service_end() log.footer("dry-run complete") diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py new file mode 100644 index 0000000..0272164 --- /dev/null +++ b/tests/test_drain_first.py @@ -0,0 +1,283 @@ +"""Tests for deploy.strategy=drain-first: drain before rolling, start after.""" + +import json + +from flow_deploy import config +from flow_deploy.deploy import _image_tag, deploy +from tests.test_deploy import ( + COMPOSE_CMD, + WEB_CONTAINER_NEW, + WEB_CONTAINER_OLD, + _chdir, + _err, + _git_preflight, + _ok, +) + +COMPOSE_CONFIG_YAML = """\ +services: + web: + image: ghcr.io/myorg/myapp:latest + labels: + deploy.role: app + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/health"] + worker: + image: ghcr.io/myorg/myapp:latest + labels: + deploy.role: app + deploy.strategy: drain-first + deploy.drain: "3660" + healthcheck: + test: ["CMD", "celery", "inspect", "ping"] +""" + +WORKER_OLD = json.dumps({"ID": "old_wrk_333", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) +WORKER_NEW = json.dumps({"ID": "new_wrk_444", "Image": "ghcr.io/myorg/myapp:abc123"}) + +WEB_ROLL = [ + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: docker ps + _ok("healthy\n"), # web: health + _ok(), # web: docker stop old + _ok(), # web: docker rm old + _ok(), # web: scale back to 1 +] +WORKER_DRAIN = [ + _ok(), # worker: pull + _ok(WORKER_OLD + "\n"), # worker: docker ps + _ok(), # worker: docker stop old + _ok(), # worker: docker rm old +] + + +def _commands(mock_process): + return [" ".join(args) for _, args, _, _ in mock_process.calls] + + +def _index(commands, *needles): + return next(i for i, c in enumerate(commands) if all(n in c for n in needles)) + + +def test_drain_first_runs_drain_then_rolling_then_start(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + *WORKER_DRAIN, + *WEB_ROLL, + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: docker ps + _ok("healthy\n"), # worker: health + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 + + cmds = _commands(mock_process) + drain = _index(cmds, "docker stop", "--time 3660", "old_wrk_333") + roll = _index(cmds, "--scale web=2") + start = _index(cmds, "up -d --no-deps worker") + assert drain < roll < start + # The worker never scales to 2: no overlap of old and new. + assert not any("--scale worker=2" in c for c in cmds) + + +def test_drain_first_service_not_running_is_started_after(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # worker: pull + _ok(""), # worker: docker ps (none running) + *WEB_ROLL, + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: docker ps + _ok("healthy\n"), # worker: health + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 + + +def test_rolling_failure_restores_drained_service_on_its_old_tag( + mock_process, monkeypatch, tmp_path +): + _chdir(monkeypatch, tmp_path) + monkeypatch.setattr("flow_deploy.deploy._wait_for_healthy", lambda *a, **kw: False) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + *WORKER_DRAIN, + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps + _ok(), # web: stop new (abort) + _ok(), # web: rm new + _ok(), # web: scale back to 1 + _ok(), # git restore + _ok(), # worker: compose up on the old tag + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + + restore = mock_process.calls[-1] + assert "up -d --no-deps worker" in " ".join(restore[1]) + assert restore[2] == {"DEPLOY_TAG": "v1.2.0"} + + +def test_drain_pull_failure_stops_nothing(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _err("manifest unknown"), # worker: pull + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert not any("docker stop" in c for c in _commands(mock_process)) + + +def test_second_drain_failure_restores_the_first(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + two_drainers = COMPOSE_CONFIG_YAML.replace(" web:", " scheduler:", 1).replace( + ' deploy.role: app\n healthcheck:\n test: ["CMD", "curl"', + " deploy.role: app\n deploy.strategy: drain-first\n" + ' deploy.order: "300"\n healthcheck:\n test: ["CMD", "curl"', + 1, + ) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(two_drainers), + *WORKER_DRAIN, # worker drains first (order 100) + _err("pull failed"), # scheduler: pull + _ok(), # git restore + _err("no such image"), # worker: restore fails, logged + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + + +def test_drained_service_that_was_not_running_stays_stopped_on_failure( + mock_process, monkeypatch, tmp_path +): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # worker: pull + _ok(""), # worker: docker ps (none running) + _err("pull failed"), # web: pull + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert not any("up -d --no-deps worker" in c for c in _commands(mock_process)) + + +def test_start_failure_leaves_service_down(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + # Web comes up healthy; the new worker never does. + monkeypatch.setattr( + "flow_deploy.deploy._wait_for_healthy", lambda ctr_id, *a: ctr_id != "new_wrk_444" + ) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + *WORKER_DRAIN, + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps + _ok(), # web: docker stop old + _ok(), # web: docker rm old + _ok(), # web: scale back to 1 + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: docker ps + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + out = capsys.readouterr().out + assert "worker is down" in out + # No rollback to the old tag once the rolling services shipped. + assert not any("v1.2.0" in str(call[2]) for call in mock_process.calls) + + +def test_start_compose_failure(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + *WORKER_DRAIN, + *WEB_ROLL, + _err("port in use"), # worker: compose up + _ok(""), # worker: docker ps + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + + +def test_start_healthcheck_skip(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + skip = COMPOSE_CONFIG_YAML.replace( + "deploy.strategy: drain-first", + 'deploy.strategy: drain-first\n deploy.healthcheck.skip: "true"', + ) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(skip), + *WORKER_DRAIN, + *WEB_ROLL, + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: docker ps + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 + + +def test_unknown_strategy_is_rejected(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML.replace("drain-first", "blue-green")), + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert "Unknown deploy.strategy: worker=blue-green" in capsys.readouterr().err + + +def test_dry_run_shows_the_three_phases(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + mock_process.responses.append(_ok(COMPOSE_CONFIG_YAML)) + assert deploy(tag="abc123", dry_run=True, cmd=COMPOSE_CMD) == 0 + out = capsys.readouterr().out + first = out.index("would drain running containers first (3660s timeout)") + rolling = out.index("would scale to 2") + last = out.index("would start on abc123") + assert first < rolling < last + + +def test_parse_strategy_defaults_to_rolling(): + services = config.parse_services({"services": {"web": {"labels": {"deploy.role": "app"}}}}) + assert services[0].strategy == "rolling" + assert not services[0].drains_first + + +def test_image_tag(): + assert _image_tag("ghcr.io/org/app:v1.2.0") == "v1.2.0" + assert _image_tag("localhost:5000/app:abc") == "abc" + assert _image_tag("localhost:5000/app") is None + assert _image_tag("app") is None From 74e01e41681ad5b94dcfefea35987a38893cbc20 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Thu, 8 Oct 2026 22:36:16 -0600 Subject: [PATCH 02/19] Harden drain-first failure paths from review - A docker stop or rm failure during the drain now aborts before anything rolls, restoring what was drained, instead of marking the service drained while old code may still run. - Drain records keep the replica count and image; restore brings services back at that scale with --scale, and mixed old images are flagged. - Phase 3 starts every drain-first service even if one fails. A failed start is restored on its previous tag when no rolling service deployed (e.g. --service worker); otherwise it stays down. - A failed restore is reported and sets the retained-lock message, as a failed git restore does. - --service that rolls services while leaving drain-first ones out warns that they keep running old code. - _image_tag ignores a digest suffix: repo@sha256:... has no tag (it returned the digest hex as one), and name:tag@sha256:... keeps the tag. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 18 +++- src/flow_deploy/deploy.py | 160 ++++++++++++++++++++---------- tests/test_drain_first.py | 199 +++++++++++++++++++++++++++++++++++++- 3 files changed, 321 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 69acc23..59e712c 100644 --- a/README.md +++ b/README.md @@ -114,10 +114,20 @@ The service is down from the start of its drain until phase 3. Queued work waits in the broker and the new worker picks it up. If the deploy fails before phase 3, drained services are restarted on the image -tag they were running before. If a drain-first service fails its own start, -there is no rollback: its old code would now run against whatever the rolling -phase changed. The deploy fails, the service is left down, and an operator -takes it from there. +tag they were running before, at the same replica count. This includes a +container that won't stop or be removed, which aborts the deploy before +anything rolls. + +Every drain-first service is started in phase 3, even if an earlier one fails. +If one fails its start: + +- When no rolling service deployed (e.g. `--service worker`), it's restored on + its previous tag. +- Otherwise it's left down. Its old code would run against whatever the rolling + phase changed, so an operator takes it from there. + +Deploying rolling services with `--service` while leaving drain-first services +out prints a warning, since those keep running old code. ```yaml services: diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 95d172c..c528730 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -2,6 +2,7 @@ import signal import time +from dataclasses import dataclass from flow_deploy import compose, config, containers, git, lock, log @@ -53,6 +54,7 @@ def _cleanup_handler(signum, frame): signal.signal(signal.SIGINT, _cleanup_handler) keep_lock = False + lock_reason = "git restore failed" try: # Git pre-flight: dirty check, fetch, checkout detached. # Protected by the lock so concurrent deploys can't race on checkout. @@ -87,41 +89,53 @@ def _cleanup_handler(signum, frame): drain_first = [s for s in app_services if s.drains_first] rolling = [s for s in app_services if not s.drains_first] + def abort(drained, footer="FAILED (deploy aborted)"): + """Restore the repo, then drained services on their old tags.""" + nonlocal keep_lock, lock_reason + log.info("") + if not git.restore(previous_sha): + keep_lock, lock_reason = True, "git restore failed" + if not _restore_drained(drained, compose_cmd): + keep_lock, lock_reason = True, "drained services could not be restored" + log.footer(footer) + return 1 + # Phase 1: drain-first services stop before anything rolls, so none of - # their old code runs beside new code or after new migrations. Each - # one's previous image tag is kept to bring it back if the deploy fails. - drained: list[tuple[config.ServiceConfig, str | None]] = [] + # their old code runs beside new code or after new migrations. What + # each one was running is kept to bring it back if the deploy fails. + drained: list[Drained] = [] for svc in drain_first: - result, old_tag = _drain_service(svc, tag, compose_cmd, project=project) + result, record = _drain_service(svc, tag, compose_cmd, project=project) + if record is not None: + drained.append(record) if result != 0: - log.info("") - keep_lock = not git.restore(previous_sha) - _restore_drained(drained, compose_cmd) - log.footer("FAILED (deploy aborted)") - return 1 - drained.append((svc, old_tag)) + return abort(drained) # Phase 2: rolling services, as before. for svc in rolling: result = _deploy_service(svc, tag, compose_cmd, project=project) if result != 0: - log.info("") - keep_lock = not git.restore(previous_sha) - _restore_drained(drained, compose_cmd) - log.footer("FAILED (deploy aborted)") - return 1 - - # Phase 3: drain-first services start on the new tag. There's no - # rollback past this point: the old code would now run against - # whatever the rolling phase changed, so a failure leaves the service - # down for an operator. - for svc in drain_first: - result = _start_service(svc, tag, compose_cmd, project=project) - if result != 0: - log.info("") - keep_lock = not git.restore(previous_sha) - log.footer(f"FAILED ({svc.name} is down; rolling services deployed)") - return 1 + return abort(drained) + + # Phase 3: drain-first services start on the new tag. Every one is + # attempted, so one failure doesn't strand the rest. + failed = [ + record + for record in drained + if _start_service(record.svc, tag, compose_cmd, project=project) != 0 + ] + if failed: + names = ", ".join(r.svc.name for r in failed) + if not rolling: + # Nothing else changed, so the old tags are still safe to run. + return abort(failed, footer=f"FAILED ({names} restored on previous tag)") + # Rolling services shipped: old code would now run against + # whatever they changed, so the failed services stay down. + log.info("") + if not git.restore(previous_sha): + keep_lock, lock_reason = True, "git restore failed" + log.footer(f"FAILED ({names} down; rolling services deployed)") + return 1 elapsed = time.time() - start_time @@ -131,8 +145,8 @@ def _cleanup_handler(signum, frame): finally: if keep_lock: log.error( - "Lock retained — git restore failed, manual intervention required. " - "Run: git checkout --detach && rm .git/deploy-lock" + f"Lock retained — {lock_reason}, manual intervention required. " + "Fix the repo checkout and service state, then: rm .git/deploy-lock" ) else: lock.release() @@ -150,7 +164,14 @@ def _resolve_app_services( app_services = [s for s in all_services if s.is_app] if services_filter: - app_services = [s for s in app_services if s.name in services_filter] + selected = [s for s in app_services if s.name in services_filter] + skipped = [s.name for s in app_services if s.drains_first and s not in selected] + if skipped and any(not s.drains_first for s in selected): + log.error( + f"--service leaves drain-first {', '.join(skipped)} running old code " + "beside the new rolling services; include them unless that's intended" + ) + app_services = selected if not app_services: log.error("No app services to deploy") @@ -185,18 +206,30 @@ def _pull(svc: config.ServiceConfig, env: dict, compose_cmd: list[str]) -> bool: def _image_tag(image: str) -> str | None: - """The tag of ``registry/name:tag``, or None when the image has no tag.""" - last = image.rsplit("/", 1)[-1] - return last.rsplit(":", 1)[1] if ":" in last else None + """The tag of ``registry/name:tag[@digest]``, or None when there's no tag.""" + name = image.rsplit("/", 1)[-1].split("@", 1)[0] + return name.rsplit(":", 1)[1] if ":" in name else None + + +@dataclass +class Drained: + """What a drain-first service was running before its drain.""" + + svc: config.ServiceConfig + replicas: int = 0 + old_tag: str | None = None + old_image: str = "" def _drain_service( svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" -) -> tuple[int, str | None]: +) -> tuple[int, Drained | None]: """Pull the new image, then stop and remove the running containers. - Pulls first so an unpullable tag fails before anything stops. Returns - (exit code, the old containers' image tag or None if none were running). + Pulls first so an unpullable tag fails before anything stops, returning + (1, None). Otherwise returns the record of what was running, with exit + code 1 if any container failed to stop or be removed: the caller must not + roll anything while old code may still be running. """ log.service_start(svc.name) svc_start = time.time() @@ -207,18 +240,34 @@ def _drain_service( return 1, None ctrs = containers.get_containers_for_service(svc.name, project=project) - old_tag = _image_tag(ctrs[0].get("Image", "")) if ctrs else None + images = list(dict.fromkeys(c.get("Image", "") for c in ctrs)) + record = Drained(svc, replicas=len(ctrs)) + if images: + record.old_image = images[0] + record.old_tag = _image_tag(images[0]) + if len(images) > 1: + log.error( + f"{svc.name} was running mixed images ({', '.join(images)}); " + f"a rollback restores {images[0]}" + ) if not ctrs: log.step("not running; nothing to drain") + for ctr in ctrs: ctr_id = ctr["ID"] log.step(f"draining {ctr_id[:7]} ({svc.drain}s timeout)...") - containers.stop_container(ctr_id, timeout=svc.drain) - containers.remove_container(ctr_id) + if not containers.stop_container(ctr_id, timeout=svc.drain): + log.failure(f"could not stop {ctr_id[:7]}; it may still be running") + log.service_end() + return 1, record + if not containers.remove_container(ctr_id): + log.failure(f"could not remove {ctr_id[:7]}") + log.service_end() + return 1, record log.success(f"{svc.name} drained ({time.time() - svc_start:.1f}s)") log.service_end() - return 0, old_tag + return 0, record def _start_service( @@ -251,20 +300,31 @@ def _start_service( return 0 -def _restore_drained( - drained: list[tuple[config.ServiceConfig, str | None]], compose_cmd: list[str] -) -> None: - """Best-effort: bring drained services back on the tag they were running.""" - for svc, old_tag in drained: - if old_tag is None: - log.step(f"{svc.name} was not running before the deploy; leaving it stopped") +def _restore_drained(drained: list[Drained], compose_cmd: list[str]) -> bool: + """Bring drained services back as they were. Returns False if any couldn't be.""" + ok = True + for record in drained: + name = record.svc.name + if not record.replicas: + log.step(f"{name} was not running before the deploy; leaving it stopped") + continue + if record.old_tag is None: + log.failure( + f"cannot restore {name}: no tag in its previous image " + f"({record.old_image or 'unknown'}); start it manually" + ) + ok = False continue - log.step(f"restoring {svc.name} on {old_tag}...") + log.step(f"restoring {name} on {record.old_tag} ({record.replicas} replica(s))...") result = compose.compose_run( - ["up", "-d", "--no-deps", svc.name], env={"DEPLOY_TAG": old_tag}, cmd=compose_cmd + ["up", "-d", "--no-deps", "--scale", f"{name}={record.replicas}", name], + env={"DEPLOY_TAG": record.old_tag}, + cmd=compose_cmd, ) if result.returncode != 0: - log.failure(f"could not restore {svc.name}: {result.stderr.strip()}") + log.failure(f"could not restore {name}: {result.stderr.strip()}") + ok = False + return ok def _deploy_service( diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 0272164..924a690 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -124,7 +124,7 @@ def test_rolling_failure_restores_drained_service_on_its_old_tag( assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 restore = mock_process.calls[-1] - assert "up -d --no-deps worker" in " ".join(restore[1]) + assert "up -d --no-deps --scale worker=1 worker" in " ".join(restore[1]) assert restore[2] == {"DEPLOY_TAG": "v1.2.0"} @@ -206,7 +206,7 @@ def test_start_failure_leaves_service_down(mock_process, monkeypatch, tmp_path, ) assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 out = capsys.readouterr().out - assert "worker is down" in out + assert "worker down; rolling services deployed" in out # No rollback to the old tag once the rolling services shipped. assert not any("v1.2.0" in str(call[2]) for call in mock_process.calls) @@ -270,6 +270,199 @@ def test_dry_run_shows_the_three_phases(mock_process, monkeypatch, tmp_path, cap assert first < rolling < last +def test_drain_stop_failure_aborts_before_rolling(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # worker: pull + _ok(WORKER_OLD + "\n"), # worker: docker ps + _err("daemon unreachable"), # worker: docker stop fails + _ok(), # git restore + _ok(), # worker: restore on old tag + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + cmds = _commands(mock_process) + assert not any("--scale web=2" in c for c in cmds) + assert "--scale worker=1 worker" in cmds[-1] + + +def test_drain_remove_failure_aborts_before_rolling(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # worker: pull + _ok(WORKER_OLD + "\n"), # worker: docker ps + _ok(), # worker: docker stop + _err("removal in progress"), # worker: docker rm fails + _ok(), # git restore + _ok(), # worker: restore on old tag + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert not any("--scale web=2" in c for c in _commands(mock_process)) + + +def test_restore_brings_back_every_replica(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + second = json.dumps({"ID": "old_wrk_555", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # worker: pull + _ok(WORKER_OLD + "\n" + second + "\n"), # worker: docker ps (2 replicas) + _ok(), # stop 1 + _ok(), # rm 1 + _ok(), # stop 2 + _ok(), # rm 2 + _err("pull failed"), # web: pull + _ok(), # git restore + _ok(), # worker: restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert "--scale worker=2 worker" in _commands(mock_process)[-1] + + +def test_mixed_old_images_are_flagged(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + other = json.dumps({"ID": "old_wrk_555", "Image": "ghcr.io/myorg/myapp:v1.1.9"}) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # worker: pull + _ok(WORKER_OLD + "\n" + other + "\n"), # worker: docker ps + _ok(), # stop 1 + _ok(), # rm 1 + _ok(), # stop 2 + _ok(), # rm 2 + _err("pull failed"), # web: pull + _ok(), # git restore + _ok(), # worker: restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert "was running mixed images" in capsys.readouterr().err + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + + +def test_failed_restore_is_reported_and_retains_the_lock( + mock_process, monkeypatch, tmp_path, capsys +): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + *WORKER_DRAIN, + _err("pull failed"), # web: pull + _ok(), # git restore + _err("no such image"), # worker: restore fails + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert "drained services could not be restored" in capsys.readouterr().err + assert (tmp_path / ".git" / "deploy-lock").exists() + + +def test_untagged_old_image_cannot_be_restored(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + digest = json.dumps({"ID": "old_wrk_333", "Image": "ghcr.io/myorg/myapp@sha256:abc"}) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # worker: pull + _ok(digest + "\n"), # worker: docker ps + _ok(), # stop + _ok(), # rm + _err("pull failed"), # web: pull + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + captured = capsys.readouterr() + output = captured.out + captured.err + assert "cannot restore worker: no tag in its previous image" in output + assert "ghcr.io/myorg/myapp@sha256:abc" in output + + +def test_service_filter_skipping_drain_first_warns(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend([*_git_preflight(), _ok(COMPOSE_CONFIG_YAML), *WEB_ROLL]) + assert deploy(tag="abc123", services_filter=["web"], cmd=COMPOSE_CMD) == 0 + assert "leaves drain-first worker running old code" in capsys.readouterr().err + + +def test_start_failure_with_nothing_rolled_restores_old_tag( + mock_process, monkeypatch, tmp_path, capsys +): + _chdir(monkeypatch, tmp_path) + monkeypatch.setattr("flow_deploy.deploy._wait_for_healthy", lambda *a, **kw: False) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + *WORKER_DRAIN, + _ok(), # worker: compose up (new tag) + _ok(WORKER_NEW + "\n"), # worker: docker ps + _ok(), # git restore + _ok(), # worker: restore on old tag + ] + ) + assert deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) == 1 + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + assert "worker restored on previous tag" in capsys.readouterr().out + + +def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + two = COMPOSE_CONFIG_YAML + ( + " scheduler:\n" + " image: ghcr.io/myorg/myapp:latest\n" + " labels:\n" + " deploy.role: app\n" + " deploy.strategy: drain-first\n" + " healthcheck:\n" + ' test: ["CMD", "true"]\n' + ) + sched_old = json.dumps({"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) + sched_new = json.dumps({"ID": "new_sch_777", "Image": "ghcr.io/myorg/myapp:abc123"}) + monkeypatch.setattr( + "flow_deploy.deploy._wait_for_healthy", lambda ctr_id, *a: ctr_id != "new_wrk_444" + ) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(two), + *WORKER_DRAIN, + _ok(), # scheduler: pull + _ok(sched_old + "\n"), # scheduler: ps + _ok(), # scheduler: stop + _ok(), # scheduler: rm + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps + _ok(), # web: stop old + _ok(), # web: rm old + _ok(), # web: scale back + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: ps (then unhealthy) + _ok(), # scheduler: compose up + _ok(sched_new + "\n"), # scheduler: ps (healthy) + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert any("up -d --no-deps scheduler" in c for c in _commands(mock_process)) + + def test_parse_strategy_defaults_to_rolling(): services = config.parse_services({"services": {"web": {"labels": {"deploy.role": "app"}}}}) assert services[0].strategy == "rolling" @@ -281,3 +474,5 @@ def test_image_tag(): assert _image_tag("localhost:5000/app:abc") == "abc" assert _image_tag("localhost:5000/app") is None assert _image_tag("app") is None + assert _image_tag("ghcr.io/org/app@sha256:abc") is None + assert _image_tag("ghcr.io/org/app:v1.2.0@sha256:abc") == "v1.2.0" From b81c865bcf99b74f440936519e9bd3ed535f16be Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Thu, 8 Oct 2026 22:40:42 -0600 Subject: [PATCH 03/19] Never restore old drain-first code after a rolling service ships From the second review: - A rolling-phase failure restored drained services even when an earlier rolling service had already deployed, putting the old worker back beside the new web. Every abort now follows one rule: restore drained services on their old tags only while nothing has shipped; after that, leave them down with a message naming what shipped. - A failed start left its unhealthy container running, so the service wasn't actually down, and a restore on an unchanged config could reuse it. It's now stopped (with the service's drain) and removed. - abort() builds the FAILED footer from a reason, so suffixes read "FAILED (worker failed to start; worker down)". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 23 +++++++------- src/flow_deploy/deploy.py | 51 ++++++++++++++++++++----------- tests/test_drain_first.py | 64 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 107 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 59e712c..f10b6b7 100644 --- a/README.md +++ b/README.md @@ -113,18 +113,17 @@ phases: The service is down from the start of its drain until phase 3. Queued work waits in the broker and the new worker picks it up. -If the deploy fails before phase 3, drained services are restarted on the image -tag they were running before, at the same replica count. This includes a -container that won't stop or be removed, which aborts the deploy before -anything rolls. - -Every drain-first service is started in phase 3, even if an earlier one fails. -If one fails its start: - -- When no rolling service deployed (e.g. `--service worker`), it's restored on - its previous tag. -- Otherwise it's left down. Its old code would run against whatever the rolling - phase changed, so an operator takes it from there. +On failure, one rule decides what happens to drained services. Phase 3 still +starts every drain-first service even if an earlier one fails, and a failed +start's container is stopped and removed. + +- **No rolling service has deployed yet.** This covers a drain that fails, + including a container that won't stop or be removed, and a failure at the + first rolling service. It also covers `--service worker`. Drained services + come back on the image tag they were running, at the same replica count. +- **A rolling service has deployed.** Drained services, and any that failed to + start, are left down. Their old code would run beside the new services and + against any migration they ran, so an operator starts them on a fixed tag. Deploying rolling services with `--service` while leaving drain-first services out prints a warning, since those keep running old code. diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index c528730..9325326 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -89,33 +89,49 @@ def _cleanup_handler(signum, frame): drain_first = [s for s in app_services if s.drains_first] rolling = [s for s in app_services if not s.drains_first] - def abort(drained, footer="FAILED (deploy aborted)"): - """Restore the repo, then drained services on their old tags.""" + shipped = [] # rolling services that deployed in this run + + def abort(down, reason): + """Restore the repo; bring ``down`` back on their old tags if safe. + + Safe only while no rolling service has shipped. Once one has, old + drain-first code would run beside it (and against any migration + it ran), so those services stay down for an operator. + """ nonlocal keep_lock, lock_reason log.info("") if not git.restore(previous_sha): keep_lock, lock_reason = True, "git restore failed" - if not _restore_drained(drained, compose_cmd): + names = ", ".join(r.svc.name for r in down if r.replicas or r in failed) + if shipped and names: + log.failure( + f"{names} left down: {', '.join(shipped)} already deployed, so their " + "old code can't run safely; start them on a fixed tag" + ) + reason = f"{reason}; {names} down" + elif not _restore_drained(down, compose_cmd): keep_lock, lock_reason = True, "drained services could not be restored" - log.footer(footer) + log.footer(f"FAILED ({reason})") return 1 # Phase 1: drain-first services stop before anything rolls, so none of # their old code runs beside new code or after new migrations. What # each one was running is kept to bring it back if the deploy fails. drained: list[Drained] = [] + failed: list[Drained] = [] for svc in drain_first: result, record = _drain_service(svc, tag, compose_cmd, project=project) if record is not None: drained.append(record) if result != 0: - return abort(drained) + return abort(drained, "deploy aborted") # Phase 2: rolling services, as before. for svc in rolling: result = _deploy_service(svc, tag, compose_cmd, project=project) if result != 0: - return abort(drained) + return abort(drained, "deploy aborted") + shipped.append(svc.name) # Phase 3: drain-first services start on the new tag. Every one is # attempted, so one failure doesn't strand the rest. @@ -126,16 +142,7 @@ def abort(drained, footer="FAILED (deploy aborted)"): ] if failed: names = ", ".join(r.svc.name for r in failed) - if not rolling: - # Nothing else changed, so the old tags are still safe to run. - return abort(failed, footer=f"FAILED ({names} restored on previous tag)") - # Rolling services shipped: old code would now run against - # whatever they changed, so the failed services stay down. - log.info("") - if not git.restore(previous_sha): - keep_lock, lock_reason = True, "git restore failed" - log.footer(f"FAILED ({names} down; rolling services deployed)") - return 1 + return abort(failed, f"{names} failed to start") elapsed = time.time() - start_time @@ -283,6 +290,7 @@ def _start_service( ctrs = containers.get_containers_for_service(svc.name, project=project) if result.returncode != 0 or len(ctrs) != 1: log.failure(f"start failed: {result.stderr.strip() or f'{len(ctrs)} containers'}") + _remove_all(ctrs, timeout=svc.drain) log.service_end() return 1 @@ -291,7 +299,10 @@ def _start_service( else: log.step(f"waiting for health check (timeout: {svc.healthcheck_timeout}s)...") if not _wait_for_healthy(ctrs[0]["ID"], svc.healthcheck_timeout, svc.healthcheck_poll): - log.failure(f"{svc.name} unhealthy; left running for inspection") + # Remove it: an unhealthy worker may still be consuming, and a + # restore on an unchanged config would otherwise reuse it. + log.failure(f"{svc.name} unhealthy; stopping and removing it") + _remove_all(ctrs, timeout=svc.drain) log.service_end() return 1 @@ -300,6 +311,12 @@ def _start_service( return 0 +def _remove_all(ctrs: list[dict], timeout: int) -> None: + for ctr in ctrs: + containers.stop_container(ctr["ID"], timeout=timeout) + containers.remove_container(ctr["ID"]) + + def _restore_drained(drained: list[Drained], compose_cmd: list[str]) -> bool: """Bring drained services back as they were. Returns False if any couldn't be.""" ok = True diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 924a690..204c57e 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -201,12 +201,18 @@ def test_start_failure_leaves_service_down(mock_process, monkeypatch, tmp_path, _ok(), # web: scale back to 1 _ok(), # worker: compose up _ok(WORKER_NEW + "\n"), # worker: docker ps + _ok(), # worker: stop unhealthy new + _ok(), # worker: rm unhealthy new _ok(), # git restore ] ) assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 out = capsys.readouterr().out - assert "worker down; rolling services deployed" in out + assert "worker failed to start; worker down" in out + # The unhealthy container is gone, not left consuming. + cmds = _commands(mock_process) + assert any("docker stop --time 3660 new_wrk_444" in c for c in cmds) + assert any("docker rm new_wrk_444" in c for c in cmds) # No rollback to the old tag once the rolling services shipped. assert not any("v1.2.0" in str(call[2]) for call in mock_process.calls) @@ -412,13 +418,17 @@ def test_start_failure_with_nothing_rolled_restores_old_tag( *WORKER_DRAIN, _ok(), # worker: compose up (new tag) _ok(WORKER_NEW + "\n"), # worker: docker ps + _ok(), # worker: stop unhealthy new + _ok(), # worker: rm unhealthy new _ok(), # git restore _ok(), # worker: restore on old tag ] ) assert deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) == 1 assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - assert "worker restored on previous tag" in capsys.readouterr().out + out = capsys.readouterr().out + assert "restoring worker on v1.2.0" in out + assert "worker failed to start" in out def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, tmp_path): @@ -454,6 +464,8 @@ def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, _ok(), # web: scale back _ok(), # worker: compose up _ok(WORKER_NEW + "\n"), # worker: ps (then unhealthy) + _ok(), # worker: stop unhealthy new + _ok(), # worker: rm unhealthy new _ok(), # scheduler: compose up _ok(sched_new + "\n"), # scheduler: ps (healthy) _ok(), # git restore @@ -463,6 +475,54 @@ def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, assert any("up -d --no-deps scheduler" in c for c in _commands(mock_process)) +def test_rolling_failure_after_another_shipped_leaves_drained_down( + mock_process, monkeypatch, tmp_path, capsys +): + _chdir(monkeypatch, tmp_path) + with_api = COMPOSE_CONFIG_YAML + ( + " api:\n" + " image: ghcr.io/myorg/myapp:latest\n" + " labels:\n" + " deploy.role: app\n" + " healthcheck:\n" + ' test: ["CMD", "true"]\n' + ) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(with_api), + *WORKER_DRAIN, + *WEB_ROLL, # web ships + _err("pull failed"), # api: pull + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + captured = capsys.readouterr() + assert "worker left down: web already deployed" in captured.out + captured.err + # The old worker must not come back beside the new web. + assert not any("v1.2.0" in str(call[2]) for call in mock_process.calls) + + +def test_start_compose_failure_removes_partial_containers(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + *WORKER_DRAIN, + *WEB_ROLL, + _err("partial"), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: docker ps (one started anyway) + _ok(), # worker: stop + _ok(), # worker: rm + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert any("docker rm new_wrk_444" in c for c in _commands(mock_process)) + + def test_parse_strategy_defaults_to_rolling(): services = config.parse_services({"services": {"web": {"labels": {"deploy.role": "app"}}}}) assert services[0].strategy == "rolling" From 4e0464726db83da00ca5dfbc5c187f7899f0467b Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Thu, 8 Oct 2026 22:50:23 -0600 Subject: [PATCH 04/19] Revert every failed deploy cleanly; drain in reverse order A failed deploy should leave no trace and need no manual cleanup: - Drained services are always restored on the image tag and replica count they ran, whatever failed, including after a rolling service shipped and when a drain-first service fails its own start. The "leave it down" rule is gone: expand-then-contract migrations, which rolling deploys already rely on, keep old code compatible with the new schema. - The lock is always released. Retaining it was never a guard anyway: acquire() breaks any lock whose PID is gone. - New exit code 3 when something can't be put back (git restore failed, a restore's compose up failed, or the old image had no tag), so CI can tell "failed and reverted" (1) from "needs a person" (3). Ordering follows dependencies: drain-first services drain in reverse deploy.order, rolling services roll in deploy.order, and drain-first services start (and restore) in deploy.order. So with web 100, api 200, worker 300, the worker drains first and starts last. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 56 ++++++++++++-------- SPEC.md | 3 +- src/flow_deploy/deploy.py | 109 ++++++++++++++++++++------------------ tests/test_deploy.py | 18 +++---- tests/test_drain_first.py | 105 ++++++++++++++++++++++++++++-------- 5 files changed, 180 insertions(+), 111 deletions(-) diff --git a/README.md b/README.md index f10b6b7..c30cc70 100644 --- a/README.md +++ b/README.md @@ -101,29 +101,39 @@ migrated the database. Label those services `deploy.strategy: drain-first` and the deploy runs in three phases: -1. **Drain.** Each drain-first service, in `deploy.order`, pulls its new image - and then stops its running containers. Stopping is `docker stop --time - `: SIGTERM first, so Celery-style workers finish their current - tasks and stop taking new ones, then SIGKILL when the drain expires. Nothing - rolls until every drain has finished. -2. **Roll.** Every rolling service deploys as usual. -3. **Start.** Each drain-first service starts on the new tag and must pass its - health check. - -The service is down from the start of its drain until phase 3. Queued work -waits in the broker and the new worker picks it up. - -On failure, one rule decides what happens to drained services. Phase 3 still -starts every drain-first service even if an earlier one fails, and a failed -start's container is stopped and removed. - -- **No rolling service has deployed yet.** This covers a drain that fails, - including a container that won't stop or be removed, and a failure at the - first rolling service. It also covers `--service worker`. Drained services - come back on the image tag they were running, at the same replica count. -- **A rolling service has deployed.** Drained services, and any that failed to - start, are left down. Their old code would run beside the new services and - against any migration they ran, so an operator starts them on a fixed tag. +1. **Drain.** Drain-first services stop in *reverse* `deploy.order`. Each one + pulls its new image, then stops its running containers. Stopping is + `docker stop --time `: SIGTERM first, so Celery-style workers + finish their current tasks and stop taking new ones, then SIGKILL when the + drain expires. Nothing rolls until every drain has finished. +2. **Roll.** Rolling services deploy in `deploy.order`, as usual. +3. **Start.** Drain-first services start in `deploy.order` on the new tag, and + each must pass its health check. + +So with `web` (100), `api` (200) and `worker` (300), the worker drains first, +then web and api roll, then the worker starts last, after the services it +depends on. The worker is down from the start of its drain until phase 3. +Queued work waits in the broker and the new worker picks it up. + +**A failed deploy leaves no trace.** It doesn't need manual cleanup: + +- A rolling service that fails is reverted as always: the old container keeps + serving and the new one is removed. +- Every drained service comes back on the image tag it was running, at the same + replica count, in `deploy.order`. That holds whatever failed, including a + container that wouldn't stop and a drain-first service that failed its own + start. Phase 3 attempts every start, removes any that fail, and restores only + those. This relies on the same expand-then-contract migration discipline as + rolling deploys: old code keeps working against the new schema. +- The repo goes back to the previous commit, and the lock is released. + +Rolling services that already shipped earlier in the run stay deployed (see +Deploy Ordering in SPEC.md). + +The deploy exits `1` when it failed and everything was put back. It exits `3` +only when something couldn't be: the git restore failed, a restore's +`compose up` failed, or the old image had no tag to restore. Even then the lock +is released. Exit `3` is the signal that someone needs to look. Deploying rolling services with `--service` while leaving drain-first services out prints a warning, since those keep running old code. diff --git a/SPEC.md b/SPEC.md index 639515a..22842cb 100644 --- a/SPEC.md +++ b/SPEC.md @@ -296,8 +296,9 @@ flow-deploy deploy [--tag TAG] [--service SERVICE] [--dry-run] Exit codes: - `0` — all services deployed successfully -- `1` — deploy failed (dirty tree, git error, unhealthy service, etc.) +- `1` — deploy failed (dirty tree, git error, unhealthy service, etc.) and everything it touched was put back - `2` — deploy lock held by another process +- `3` — deploy failed and could not be fully reverted (git restore or a service restore failed); the lock is still released To deploy a previous version, run `flow-deploy deploy --tag `. The SHA is always a git commit — find it in your CI history or via `git log` on the server. diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 9325326..210a252 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -6,6 +6,11 @@ from flow_deploy import compose, config, containers, git, lock, log +EXIT_OK = 0 +EXIT_FAILED = 1 # failed; everything it touched was put back +EXIT_LOCKED = 2 +EXIT_DEGRADED = 3 # failed, and something couldn't be put back + def deploy( tag: str | None = None, @@ -13,7 +18,8 @@ def deploy( dry_run: bool = False, cmd: list[str] | None = None, ) -> int: - """Perform a rolling deploy. Returns exit code (0=success, 1=failure, 2=locked).""" + """Perform a deploy. Returns an EXIT_* code: 0 ok, 1 failed and reverted, + 2 locked, 3 failed and not fully reverted.""" compose_cmd = cmd or compose.resolve_command() # Determine tag: if not provided, deploy whatever is currently checked out @@ -39,7 +45,7 @@ def deploy( lock_info = lock.read_lock() pid = lock_info["pid"] if lock_info else "unknown" log.error(f"Deploy lock held by PID {pid}") - return 2 + return EXIT_LOCKED # Register signal handlers for cleanup _original_sigterm = signal.getsignal(signal.SIGTERM) @@ -53,8 +59,6 @@ def _cleanup_handler(signum, frame): signal.signal(signal.SIGTERM, _cleanup_handler) signal.signal(signal.SIGINT, _cleanup_handler) - keep_lock = False - lock_reason = "git restore failed" try: # Git pre-flight: dirty check, fetch, checkout detached. # Protected by the lock so concurrent deploys can't race on checkout. @@ -62,20 +66,18 @@ def _cleanup_handler(signum, frame): # from the target commit, not whatever is currently checked out. git_code, previous_sha = git.preflight_and_checkout(tag if tag_provided else None) if git_code != 0: - return 1 + return EXIT_FAILED # Parse compose config (now reading from the target commit) try: compose_dict = compose.compose_config(cmd=compose_cmd) except RuntimeError as e: log.error(str(e)) - keep_lock = not git.restore(previous_sha) - return 1 + return EXIT_FAILED if git.restore(previous_sha) else _degraded("git restore failed") app_services = _resolve_app_services(compose_dict, services_filter) if app_services is None: - keep_lock = not git.restore(previous_sha) - return 1 + return EXIT_FAILED if git.restore(previous_sha) else _degraded("git restore failed") service_names = ", ".join(s.name for s in app_services) log.header("deploy") @@ -86,59 +88,53 @@ def _cleanup_handler(signum, frame): project = compose_dict.get("name", "") start_time = time.time() + # app_services is in deploy.order. Services start in that order and + # stop in reverse, so a worker comes up after the web and API it + # depends on, and drains before them. drain_first = [s for s in app_services if s.drains_first] rolling = [s for s in app_services if not s.drains_first] - shipped = [] # rolling services that deployed in this run - - def abort(down, reason): - """Restore the repo; bring ``down`` back on their old tags if safe. + def abort(down: list[Drained], reason: str) -> int: + """Put things back as they were before the deploy. - Safe only while no rolling service has shipped. Once one has, old - drain-first code would run beside it (and against any migration - it ran), so those services stay down for an operator. + Restores the repo and brings ``down`` back on the tags they ran. + Expand-then-contract migrations keep old code compatible with the + new schema, as rolling deploys already assume. Exits 3 only when + something can't be put back. """ - nonlocal keep_lock, lock_reason log.info("") + problems = [] if not git.restore(previous_sha): - keep_lock, lock_reason = True, "git restore failed" - names = ", ".join(r.svc.name for r in down if r.replicas or r in failed) - if shipped and names: - log.failure( - f"{names} left down: {', '.join(shipped)} already deployed, so their " - "old code can't run safely; start them on a fixed tag" - ) - reason = f"{reason}; {names} down" - elif not _restore_drained(down, compose_cmd): - keep_lock, lock_reason = True, "drained services could not be restored" + problems.append("git restore failed") + if not _restore_drained(down, compose_cmd): + problems.append("drained services could not be restored") log.footer(f"FAILED ({reason})") - return 1 + return _degraded(", ".join(problems)) if problems else EXIT_FAILED - # Phase 1: drain-first services stop before anything rolls, so none of - # their old code runs beside new code or after new migrations. What - # each one was running is kept to bring it back if the deploy fails. + # Phase 1: drain-first services stop, in reverse deploy order, before + # anything rolls, so none of their old code runs beside new code. + # What each one was running is kept to bring it back on failure. drained: list[Drained] = [] - failed: list[Drained] = [] - for svc in drain_first: + for svc in reversed(drain_first): result, record = _drain_service(svc, tag, compose_cmd, project=project) if record is not None: drained.append(record) if result != 0: return abort(drained, "deploy aborted") - # Phase 2: rolling services, as before. + # Phase 2: rolling services, in deploy order, as before. for svc in rolling: - result = _deploy_service(svc, tag, compose_cmd, project=project) - if result != 0: + if _deploy_service(svc, tag, compose_cmd, project=project) != 0: return abort(drained, "deploy aborted") - shipped.append(svc.name) - # Phase 3: drain-first services start on the new tag. Every one is - # attempted, so one failure doesn't strand the rest. + # Phase 3: drain-first services start in deploy order. Every one is + # attempted, so one failure doesn't strand the rest; a failed one goes + # back to what it ran before. + by_name = {record.svc.name: record for record in drained} failed = [ - record - for record in drained - if _start_service(record.svc, tag, compose_cmd, project=project) != 0 + by_name[svc.name] + for svc in drain_first + if _start_service(svc, tag, compose_cmd, project=project) != 0 ] if failed: names = ", ".join(r.svc.name for r in failed) @@ -150,17 +146,21 @@ def abort(down, reason): log.info(f"HEAD detached at {tag}") log.footer(f"complete ({elapsed:.1f}s)") finally: - if keep_lock: - log.error( - f"Lock retained — {lock_reason}, manual intervention required. " - "Fix the repo checkout and service state, then: rm .git/deploy-lock" - ) - else: - lock.release() + # Always released: a failed deploy puts things back rather than + # leaving state for someone to clean up by hand. + lock.release() signal.signal(signal.SIGTERM, _original_sigterm) signal.signal(signal.SIGINT, _original_sigint) - return 0 + return EXIT_OK + + +def _degraded(problem: str) -> int: + log.error( + f"Deploy failed and could not be fully reverted ({problem}). " + "Check the repo checkout and service state on this host." + ) + return EXIT_DEGRADED def _resolve_app_services( @@ -318,9 +318,12 @@ def _remove_all(ctrs: list[dict], timeout: int) -> None: def _restore_drained(drained: list[Drained], compose_cmd: list[str]) -> bool: - """Bring drained services back as they were. Returns False if any couldn't be.""" + """Bring drained services back as they were, in deploy (start) order. + + Returns False if any couldn't be. + """ ok = True - for record in drained: + for record in sorted(drained, key=lambda r: (r.svc.order, r.svc.file_order)): name = record.svc.name if not record.replicas: log.step(f"{name} was not running before the deploy; leaving it stopped") @@ -457,7 +460,7 @@ def _dry_run(tag: str, services: list[config.ServiceConfig]) -> None: log.info(f"services: {', '.join(s.name for s in services)}") log.info("") drain_first = [s for s in services if s.drains_first] - for svc in drain_first: + for svc in reversed(drain_first): log.service_start(svc.name) image_name = (svc.image or svc.name).rsplit(":", 1)[0] log.step(f"would pull {image_name}:{tag}") diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 229721b..c5da3ea 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -319,8 +319,10 @@ def test_deploy_order(mock_process, monkeypatch, tmp_path, capsys): assert web_pos < worker_pos -def test_deploy_restore_failure_retains_lock(mock_process, monkeypatch, tmp_path, capsys): - """If git restore fails after a deploy failure, the lock should be retained.""" +def test_deploy_restore_failure_exits_degraded_and_releases_lock( + mock_process, monkeypatch, tmp_path, capsys +): + """A failed git restore exits 3 but still releases the lock: no manual cleanup.""" _chdir(monkeypatch, tmp_path) mock_process.responses.extend( [ @@ -333,15 +335,9 @@ def test_deploy_restore_failure_retains_lock(mock_process, monkeypatch, tmp_path ] ) result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - # Lock should still be held - from flow_deploy import lock - - assert not lock.acquire(), "Lock should still be held after restore failure" - err = capsys.readouterr().err - assert "Lock retained" in err - # Clean up for other tests - lock.release() + assert result == 3 + assert not (tmp_path / ".git" / "deploy-lock").exists() + assert "could not be fully reverted (git restore failed)" in capsys.readouterr().err def test_deploy_dirty_tree_fails(mock_process, monkeypatch, tmp_path, capsys): diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 204c57e..83d21a3 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -150,18 +150,24 @@ def test_second_drain_failure_restores_the_first(mock_process, monkeypatch, tmp_ ' deploy.order: "300"\n healthcheck:\n test: ["CMD", "curl"', 1, ) + sched_old = json.dumps({"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.1.0"}) mock_process.responses.extend( [ *_git_preflight(), _ok(two_drainers), - *WORKER_DRAIN, # worker drains first (order 100) - _err("pull failed"), # scheduler: pull + # Drains run in reverse deploy order: scheduler (300) before worker (100). + _ok(), # scheduler: pull + _ok(sched_old + "\n"), # scheduler: ps + _ok(), # scheduler: stop + _ok(), # scheduler: rm + _err("pull failed"), # worker: pull _ok(), # git restore - _err("no such image"), # worker: restore fails, logged + _err("no such image"), # scheduler: restore fails ] ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 3 + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.1.0"} + assert not (tmp_path / ".git" / "deploy-lock").exists() def test_drained_service_that_was_not_running_stays_stopped_on_failure( @@ -182,7 +188,7 @@ def test_drained_service_that_was_not_running_stays_stopped_on_failure( assert not any("up -d --no-deps worker" in c for c in _commands(mock_process)) -def test_start_failure_leaves_service_down(mock_process, monkeypatch, tmp_path, capsys): +def test_start_failure_restores_previous_container(mock_process, monkeypatch, tmp_path, capsys): _chdir(monkeypatch, tmp_path) # Web comes up healthy; the new worker never does. monkeypatch.setattr( @@ -204,17 +210,18 @@ def test_start_failure_leaves_service_down(mock_process, monkeypatch, tmp_path, _ok(), # worker: stop unhealthy new _ok(), # worker: rm unhealthy new _ok(), # git restore + _ok(), # worker: restore on old tag ] ) assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - out = capsys.readouterr().out - assert "worker failed to start; worker down" in out - # The unhealthy container is gone, not left consuming. + assert "worker failed to start" in capsys.readouterr().out + # The unhealthy container is gone, not left consuming... cmds = _commands(mock_process) assert any("docker stop --time 3660 new_wrk_444" in c for c in cmds) assert any("docker rm new_wrk_444" in c for c in cmds) - # No rollback to the old tag once the rolling services shipped. - assert not any("v1.2.0" in str(call[2]) for call in mock_process.calls) + # ...and the previous one is back, even though web shipped. + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + assert not (tmp_path / ".git" / "deploy-lock").exists() def test_start_compose_failure(mock_process, monkeypatch, tmp_path): @@ -358,7 +365,7 @@ def test_mixed_old_images_are_flagged(mock_process, monkeypatch, tmp_path, capsy assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} -def test_failed_restore_is_reported_and_retains_the_lock( +def test_failed_restore_exits_degraded_and_releases_the_lock( mock_process, monkeypatch, tmp_path, capsys ): _chdir(monkeypatch, tmp_path) @@ -372,9 +379,9 @@ def test_failed_restore_is_reported_and_retains_the_lock( _err("no such image"), # worker: restore fails ] ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 3 assert "drained services could not be restored" in capsys.readouterr().err - assert (tmp_path / ".git" / "deploy-lock").exists() + assert not (tmp_path / ".git" / "deploy-lock").exists() def test_untagged_old_image_cannot_be_restored(mock_process, monkeypatch, tmp_path, capsys): @@ -392,7 +399,7 @@ def test_untagged_old_image_cannot_be_restored(mock_process, monkeypatch, tmp_pa _ok(), # git restore ] ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 3 captured = capsys.readouterr() output = captured.out + captured.err assert "cannot restore worker: no tag in its previous image" in output @@ -431,6 +438,51 @@ def test_start_failure_with_nothing_rolled_restores_old_tag( assert "worker failed to start" in out +def test_drains_in_reverse_order_and_starts_in_order(mock_process, monkeypatch, tmp_path): + """worker (100) then scheduler (300) in deploy order: drain scheduler first, + start worker first, roll web in between.""" + _chdir(monkeypatch, tmp_path) + ordered = COMPOSE_CONFIG_YAML + ( + " scheduler:\n" + " image: ghcr.io/myorg/myapp:latest\n" + " labels:\n" + " deploy.role: app\n" + " deploy.strategy: drain-first\n" + ' deploy.order: "300"\n' + " healthcheck:\n" + ' test: ["CMD", "true"]\n' + ) + sched_old = json.dumps({"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) + sched_new = json.dumps({"ID": "new_sch_777", "Image": "ghcr.io/myorg/myapp:abc123"}) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(ordered), + _ok(), # scheduler: pull + _ok(sched_old + "\n"), # scheduler: ps + _ok(), # scheduler: stop + _ok(), # scheduler: rm + *WORKER_DRAIN, + *WEB_ROLL, + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: ps + _ok("healthy\n"), # worker: health + _ok(), # scheduler: compose up + _ok(sched_new + "\n"), # scheduler: ps + _ok("healthy\n"), # scheduler: health + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 + cmds = _commands(mock_process) + assert ( + _index(cmds, "docker stop", "old_sch_666") + < _index(cmds, "docker stop", "old_wrk_333") + < _index(cmds, "--scale web=2") + < _index(cmds, "up -d --no-deps worker") + < _index(cmds, "up -d --no-deps scheduler") + ) + + def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, tmp_path): _chdir(monkeypatch, tmp_path) two = COMPOSE_CONFIG_YAML + ( @@ -451,11 +503,12 @@ def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, [ *_git_preflight(), _ok(two), - *WORKER_DRAIN, + # Same order, so file order breaks the tie: scheduler drains first. _ok(), # scheduler: pull _ok(sched_old + "\n"), # scheduler: ps _ok(), # scheduler: stop _ok(), # scheduler: rm + *WORKER_DRAIN, _ok(), # web: pull _ok(), # web: scale to 2 _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps @@ -469,14 +522,19 @@ def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, _ok(), # scheduler: compose up _ok(sched_new + "\n"), # scheduler: ps (healthy) _ok(), # git restore + _ok(), # worker: restore on old tag ] ) assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert any("up -d --no-deps scheduler" in c for c in _commands(mock_process)) + cmds = _commands(mock_process) + assert any("up -d --no-deps scheduler" in c for c in cmds) + # Only the failed worker goes back; the healthy new scheduler stays. + assert "--scale worker=1 worker" in cmds[-1] + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} -def test_rolling_failure_after_another_shipped_leaves_drained_down( - mock_process, monkeypatch, tmp_path, capsys +def test_rolling_failure_after_another_shipped_still_restores_drained( + mock_process, monkeypatch, tmp_path ): _chdir(monkeypatch, tmp_path) with_api = COMPOSE_CONFIG_YAML + ( @@ -495,13 +553,14 @@ def test_rolling_failure_after_another_shipped_leaves_drained_down( *WEB_ROLL, # web ships _err("pull failed"), # api: pull _ok(), # git restore + _ok(), # worker: restore on old tag ] ) + # Expand-then-contract keeps the old worker compatible with whatever web + # migrated, so it comes back rather than leaving the queue unworked. assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - captured = capsys.readouterr() - assert "worker left down: web already deployed" in captured.out + captured.err - # The old worker must not come back beside the new web. - assert not any("v1.2.0" in str(call[2]) for call in mock_process.calls) + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + assert not (tmp_path / ".git" / "deploy-lock").exists() def test_start_compose_failure_removes_partial_containers(mock_process, monkeypatch, tmp_path): From 1d5f27aed0368665248543b76d1a840a380c1435 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Thu, 8 Oct 2026 23:04:39 -0600 Subject: [PATCH 05/19] Revert on signals and crashes; report cleanup failures; 100% coverage From the third review: - A signal (cancelled CI job, Ctrl-C) or unexpected exception now reverts like any other failure instead of exiting with drained services down. The handler raises Interrupted; deploy() wraps the run, ignores further signals while reverting, and still releases the lock. Drain-first services already healthy on the new tag stay. - Cleanup failures are reported. _deploy_service and _start_service return OK / FAILED / DIRTY; a stop, rm, or scale-back that fails during a rolling abort, a cutover, or a failed start makes the deploy exit 3 instead of claiming a clean revert. - Phase 3 starts drain-first services at their drained replica count and health-checks every replica. - _image_tag treats a bare image ID (sha256:...) as untagged. - README states the DEPLOY_TAG contract that restores rely on. Coverage is now required at 100% (pyproject fail_under), with tests for the previously uncovered CLI status command, version fallback, lock, log, process, and container paths, plus a test module for deploy failure paths. The __main__ guard is excluded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 12 ++ pyproject.toml | 6 +- src/flow_deploy/deploy.py | 394 +++++++++++++++++++++------------- tests/test_cli.py | 43 ++++ tests/test_containers.py | 21 ++ tests/test_deploy_failures.py | 298 +++++++++++++++++++++++++ tests/test_drain_first.py | 10 +- tests/test_init.py | 18 ++ tests/test_lock.py | 6 + tests/test_log.py | 10 + tests/test_process.py | 5 + 11 files changed, 668 insertions(+), 155 deletions(-) create mode 100644 tests/test_deploy_failures.py create mode 100644 tests/test_init.py diff --git a/README.md b/README.md index c30cc70..86126e7 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,18 @@ Queued work waits in the broker and the new worker picks it up. Rolling services that already shipped earlier in the run stay deployed (see Deploy Ordering in SPEC.md). +Restoring relies on the same contract as every deploy: each app service's image +is tagged by `DEPLOY_TAG`, for example `image: ghcr.io/org/app:${DEPLOY_TAG}` +directly or through an env var that expands to it. A restore runs `compose up` +with the previous tag in `DEPLOY_TAG`. A service whose image ignores it comes +back on whatever the compose file names. + +A signal (a cancelled CI job, Ctrl-C) or an unexpected error reverts the same +way. Further signals are ignored until the revert finishes. Drain-first services +already healthy on the new tag stay. Cleanup that fails along the way (a new +container that won't stop or be removed, a scale-back that fails) also makes the +deploy exit `3`. + The deploy exits `1` when it failed and everything was put back. It exits `3` only when something couldn't be: the git restore failed, a restore's `compose up` failed, or the old image had no tag to restore. Even then the lock diff --git a/pyproject.toml b/pyproject.toml index 4bf753f..ecd2c35 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,5 +47,9 @@ addopts = "-v --tb=short --cov=flow_deploy --cov-report=term-missing" source = ["flow_deploy"] [tool.coverage.report] -fail_under = 90 +fail_under = 100 show_missing = true +exclude_lines = [ + "pragma: no cover", + "if __name__ == .__main__.:", +] diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 210a252..33e140b 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -2,7 +2,7 @@ import signal import time -from dataclasses import dataclass +from dataclasses import dataclass, field from flow_deploy import compose, config, containers, git, lock, log @@ -11,6 +11,62 @@ EXIT_LOCKED = 2 EXIT_DEGRADED = 3 # failed, and something couldn't be put back +# Per-service outcomes from _deploy_service and _start_service. +SVC_OK = 0 +SVC_FAILED = 1 # failed, and its own cleanup succeeded +SVC_DIRTY = 2 # failed, and its own cleanup failed too + + +class Interrupted(BaseException): + """Raised by the signal handler so the deploy reverts before exiting. + + A BaseException, so no ``except Exception`` along the way swallows it. + """ + + def __init__(self, signum: int): + super().__init__(signum) + self.signum = signum + + +@dataclass +class Drained: + """What a drain-first service was running before its drain.""" + + svc: config.ServiceConfig + replicas: int = 0 + old_tag: str | None = None + old_image: str = "" + + +@dataclass +class _Run: + """What a deploy has changed so far, so any failure can put it back.""" + + compose_cmd: list[str] + previous_sha: str | None = None + drained: list[Drained] = field(default_factory=list) + started: set[str] = field(default_factory=set) # drain-first, healthy on the new tag + + def revert(self, reason: str, down: list[Drained] | None = None) -> int: + """Put things back as they were before the deploy. + + Restores the repo and brings ``down`` (by default every drained + service not yet healthy on the new tag) back on the tags they ran. + Expand-then-contract migrations keep old code compatible with the new + schema, as rolling deploys already assume. Exits 3 only when + something can't be put back. + """ + if down is None: + down = [r for r in self.drained if r.svc.name not in self.started] + log.info("") + problems = [] + if self.previous_sha is not None and not git.restore(self.previous_sha): + problems.append("git restore failed") + if not _restore_drained(down, self.compose_cmd): + problems.append("drained services could not be restored") + log.footer(f"FAILED ({reason})") + return _degraded(", ".join(problems)) if problems else EXIT_FAILED + def deploy( tag: str | None = None, @@ -47,104 +103,29 @@ def deploy( log.error(f"Deploy lock held by PID {pid}") return EXIT_LOCKED - # Register signal handlers for cleanup + # A signal (a cancelled CI job, Ctrl-C) reverts like any other failure. _original_sigterm = signal.getsignal(signal.SIGTERM) _original_sigint = signal.getsignal(signal.SIGINT) - def _cleanup_handler(signum, frame): - log.error(f"Received signal {signum}, cleaning up...") - lock.release() - raise SystemExit(1) + def _interrupt(signum, frame): + raise Interrupted(signum) - signal.signal(signal.SIGTERM, _cleanup_handler) - signal.signal(signal.SIGINT, _cleanup_handler) + signal.signal(signal.SIGTERM, _interrupt) + signal.signal(signal.SIGINT, _interrupt) + run = _Run(compose_cmd) try: - # Git pre-flight: dirty check, fetch, checkout detached. - # Protected by the lock so concurrent deploys can't race on checkout. - # Must happen before config parsing so we read the compose file - # from the target commit, not whatever is currently checked out. - git_code, previous_sha = git.preflight_and_checkout(tag if tag_provided else None) - if git_code != 0: - return EXIT_FAILED - - # Parse compose config (now reading from the target commit) - try: - compose_dict = compose.compose_config(cmd=compose_cmd) - except RuntimeError as e: - log.error(str(e)) - return EXIT_FAILED if git.restore(previous_sha) else _degraded("git restore failed") - - app_services = _resolve_app_services(compose_dict, services_filter) - if app_services is None: - return EXIT_FAILED if git.restore(previous_sha) else _degraded("git restore failed") - - service_names = ", ".join(s.name for s in app_services) - log.header("deploy") - log.info(f"tag: {tag}") - log.info(f"services: {service_names}") - log.info("") - - project = compose_dict.get("name", "") - start_time = time.time() - - # app_services is in deploy.order. Services start in that order and - # stop in reverse, so a worker comes up after the web and API it - # depends on, and drains before them. - drain_first = [s for s in app_services if s.drains_first] - rolling = [s for s in app_services if not s.drains_first] - - def abort(down: list[Drained], reason: str) -> int: - """Put things back as they were before the deploy. - - Restores the repo and brings ``down`` back on the tags they ran. - Expand-then-contract migrations keep old code compatible with the - new schema, as rolling deploys already assume. Exits 3 only when - something can't be put back. - """ - log.info("") - problems = [] - if not git.restore(previous_sha): - problems.append("git restore failed") - if not _restore_drained(down, compose_cmd): - problems.append("drained services could not be restored") - log.footer(f"FAILED ({reason})") - return _degraded(", ".join(problems)) if problems else EXIT_FAILED - - # Phase 1: drain-first services stop, in reverse deploy order, before - # anything rolls, so none of their old code runs beside new code. - # What each one was running is kept to bring it back on failure. - drained: list[Drained] = [] - for svc in reversed(drain_first): - result, record = _drain_service(svc, tag, compose_cmd, project=project) - if record is not None: - drained.append(record) - if result != 0: - return abort(drained, "deploy aborted") - - # Phase 2: rolling services, in deploy order, as before. - for svc in rolling: - if _deploy_service(svc, tag, compose_cmd, project=project) != 0: - return abort(drained, "deploy aborted") - - # Phase 3: drain-first services start in deploy order. Every one is - # attempted, so one failure doesn't strand the rest; a failed one goes - # back to what it ran before. - by_name = {record.svc.name: record for record in drained} - failed = [ - by_name[svc.name] - for svc in drain_first - if _start_service(svc, tag, compose_cmd, project=project) != 0 - ] - if failed: - names = ", ".join(r.svc.name for r in failed) - return abort(failed, f"{names} failed to start") - - elapsed = time.time() - start_time - - log.info("") - log.info(f"HEAD detached at {tag}") - log.footer(f"complete ({elapsed:.1f}s)") + return _deploy_locked(run, tag, tag_provided, services_filter) + except (Exception, Interrupted) as exc: + # Don't let a second signal cut the revert short. + signal.signal(signal.SIGTERM, signal.SIG_IGN) + signal.signal(signal.SIGINT, signal.SIG_IGN) + if isinstance(exc, Interrupted): + reason = f"interrupted by signal {exc.signum}" + else: + reason = f"unexpected error: {exc!r}" + log.error(f"{reason}; reverting") + return run.revert(reason) finally: # Always released: a failed deploy puts things back rather than # leaving state for someone to clean up by hand. @@ -152,6 +133,94 @@ def abort(down: list[Drained], reason: str) -> int: signal.signal(signal.SIGTERM, _original_sigterm) signal.signal(signal.SIGINT, _original_sigint) + +def _deploy_locked( + run: _Run, tag: str, tag_provided: bool, services_filter: list[str] | None +) -> int: + """The deploy proper, under the lock. Records what it changes on ``run``.""" + # Git pre-flight: dirty check, fetch, checkout detached. + # Protected by the lock so concurrent deploys can't race on checkout. + # Must happen before config parsing so we read the compose file + # from the target commit, not whatever is currently checked out. + git_code, run.previous_sha = git.preflight_and_checkout(tag if tag_provided else None) + if git_code != 0: + return EXIT_FAILED + + # Parse compose config (now reading from the target commit) + try: + compose_dict = compose.compose_config(cmd=run.compose_cmd) + except RuntimeError as e: + log.error(str(e)) + return EXIT_FAILED if git.restore(run.previous_sha) else _degraded("git restore failed") + + app_services = _resolve_app_services(compose_dict, services_filter) + if app_services is None: + return EXIT_FAILED if git.restore(run.previous_sha) else _degraded("git restore failed") + + service_names = ", ".join(s.name for s in app_services) + log.header("deploy") + log.info(f"tag: {tag}") + log.info(f"services: {service_names}") + log.info("") + + project = compose_dict.get("name", "") + compose_cmd = run.compose_cmd + start_time = time.time() + + # app_services is in deploy.order. Services start in that order and stop + # in reverse, so a worker comes up after the web and API it depends on, + # and drains before them. + drain_first = [s for s in app_services if s.drains_first] + rolling = [s for s in app_services if not s.drains_first] + dirty = [] # services whose own failure cleanup also failed + + def failed(reason: str, down: list[Drained] | None = None) -> int: + code = run.revert(reason, down) + if dirty and code == EXIT_FAILED: + return _degraded(f"cleanup failed for {', '.join(dirty)}") + return code + + # Phase 1: drain-first services stop, in reverse deploy order, before + # anything rolls, so none of their old code runs beside new code. What + # each one was running is kept to bring it back on failure. + for svc in reversed(drain_first): + result, record = _drain_service(svc, tag, compose_cmd, project=project) + if record is not None: + run.drained.append(record) + if result != 0: + return failed("deploy aborted") + + # Phase 2: rolling services, in deploy order, as before. + for svc in rolling: + result = _deploy_service(svc, tag, compose_cmd, project=project) + if result == SVC_DIRTY: + dirty.append(svc.name) + if result != SVC_OK: + return failed("deploy aborted") + + # Phase 3: drain-first services start in deploy order, at the replica + # count they ran. Every one is attempted, so one failure doesn't strand + # the rest; a failed one goes back to what it ran before. + by_name = {record.svc.name: record for record in run.drained} + failures = [] + for svc in drain_first: + record = by_name[svc.name] + result = _start_service(svc, tag, compose_cmd, max(record.replicas, 1), project=project) + if result == SVC_OK: + run.started.add(svc.name) + continue + if result == SVC_DIRTY: + dirty.append(svc.name) + failures.append(record) + if failures: + names = ", ".join(r.svc.name for r in failures) + return failed(f"{names} failed to start", failures) + + elapsed = time.time() - start_time + + log.info("") + log.info(f"HEAD detached at {tag}") + log.footer(f"complete ({elapsed:.1f}s)") return EXIT_OK @@ -213,21 +282,16 @@ def _pull(svc: config.ServiceConfig, env: dict, compose_cmd: list[str]) -> bool: def _image_tag(image: str) -> str | None: - """The tag of ``registry/name:tag[@digest]``, or None when there's no tag.""" + """The tag of ``registry/name:tag[@digest]``, or None when there's no tag. + + A bare image ID (``sha256:...``) has no tag. + """ + if image.startswith("sha256:"): + return None name = image.rsplit("/", 1)[-1].split("@", 1)[0] return name.rsplit(":", 1)[1] if ":" in name else None -@dataclass -class Drained: - """What a drain-first service was running before its drain.""" - - svc: config.ServiceConfig - replicas: int = 0 - old_tag: str | None = None - old_image: str = "" - - def _drain_service( svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" ) -> tuple[int, Drained | None]: @@ -278,43 +342,64 @@ def _drain_service( def _start_service( - svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" + svc: config.ServiceConfig, + tag: str, + compose_cmd: list[str], + replicas: int = 1, + project: str = "", ) -> int: - """Start a drained service on the new tag and wait for it to be healthy.""" + """Start a drained service on the new tag at ``replicas`` and wait for health. + + 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} - log.step("starting new container...") - result = compose.compose_run(["up", "-d", "--no-deps", svc.name], env=env, cmd=compose_cmd) - ctrs = containers.get_containers_for_service(svc.name, project=project) - if result.returncode != 0 or len(ctrs) != 1: - log.failure(f"start failed: {result.stderr.strip() or f'{len(ctrs)} containers'}") - _remove_all(ctrs, timeout=svc.drain) + 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. + log.failure(msg) + clean = _remove_all(ctrs, timeout=svc.drain) log.service_end() - return 1 + return SVC_FAILED if clean else SVC_DIRTY + + log.step(f"starting {replicas} new container(s)...") + result = compose.compose_run( + ["up", "-d", "--no-deps", "--scale", f"{svc.name}={replicas}", svc.name], + env=env, + cmd=compose_cmd, + ) + ctrs = containers.get_containers_for_service(svc.name, project=project) + if result.returncode != 0 or len(ctrs) != replicas: + detail = result.stderr.strip() or f"{len(ctrs)} of {replicas} containers running" + return fail(f"start failed: {detail}", ctrs) if svc.healthcheck_skip: log.step("healthcheck skipped (deploy.healthcheck.skip=true)") else: log.step(f"waiting for health check (timeout: {svc.healthcheck_timeout}s)...") - if not _wait_for_healthy(ctrs[0]["ID"], svc.healthcheck_timeout, svc.healthcheck_poll): - # Remove it: an unhealthy worker may still be consuming, and a - # restore on an unchanged config would otherwise reuse it. - log.failure(f"{svc.name} unhealthy; stopping and removing it") - _remove_all(ctrs, timeout=svc.drain) - log.service_end() - return 1 + for ctr in ctrs: + if not _wait_for_healthy(ctr["ID"], svc.healthcheck_timeout, svc.healthcheck_poll): + return fail(f"{svc.name} unhealthy; stopping and removing it", ctrs) log.success(f"{svc.name} started ({time.time() - svc_start:.1f}s)") log.service_end() - return 0 + return SVC_OK -def _remove_all(ctrs: list[dict], timeout: int) -> None: +def _remove_all(ctrs: list[dict], timeout: int) -> bool: + """Stop and remove ``ctrs``. Returns False if any couldn't be.""" + ok = True for ctr in ctrs: - containers.stop_container(ctr["ID"], timeout=timeout) - containers.remove_container(ctr["ID"]) + if not containers.stop_container(ctr["ID"], timeout=timeout): + log.failure(f"could not stop {ctr['ID'][:7]}") + ok = False + if not containers.remove_container(ctr["ID"]): + log.failure(f"could not remove {ctr['ID'][:7]}") + ok = False + return ok def _restore_drained(drained: list[Drained], compose_cmd: list[str]) -> bool: @@ -350,16 +435,23 @@ def _restore_drained(drained: list[Drained], compose_cmd: list[str]) -> bool: def _deploy_service( svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" ) -> int: - """Deploy a single service. Returns 0 on success, 1 on failure.""" + """Deploy a single service with a rolling cutover. + + Returns SVC_OK, SVC_FAILED (old container still serving, nothing left + behind), or SVC_DIRTY (failed, and cleaning up after itself failed too). + """ log.service_start(svc.name) svc_start = time.time() env = {"DEPLOY_TAG": tag} + def end(code: int) -> int: + log.service_end() + return code + # 1. Pull if not _pull(svc, env, compose_cmd): - log.service_end() - return 1 + return end(SVC_FAILED) # 2. Scale to 2 log.step("starting new container...") @@ -370,8 +462,7 @@ def _deploy_service( ) if result.returncode != 0: log.failure(f"scale up failed: {result.stderr.strip()}") - log.service_end() - return 1 + return end(SVC_FAILED if _scale_back(svc.name, env, compose_cmd) else SVC_DIRTY) # 3. Get containers, identify old vs new ctrs = containers.get_containers_for_service(svc.name, project=project) @@ -382,16 +473,12 @@ def _deploy_service( f"Run `docker ps --filter label=com.docker.compose.service={svc.name}` " "to inspect running containers, then remove extras and retry." ) - _scale_back(svc.name, env, compose_cmd) - log.service_end() - return 1 + return end(SVC_FAILED if _scale_back(svc.name, env, compose_cmd) else SVC_DIRTY) old, new = containers.identify_old_new(ctrs, tag) if old is None or new is None: log.failure("Could not identify old/new containers") - _scale_back(svc.name, env, compose_cmd) - log.service_end() - return 1 + return end(SVC_FAILED if _scale_back(svc.name, env, compose_cmd) else SVC_DIRTY) new_id = new["ID"] old_id = old["ID"] @@ -411,24 +498,29 @@ def _deploy_service( # 5a. Cutover: stop old, remove old, scale back log.step(f"draining old container ({old_id[:7]}, {svc.drain}s timeout)...") - containers.stop_container(old_id, timeout=svc.drain) - containers.remove_container(old_id) - _scale_back(svc.name, env, compose_cmd) + clean = containers.stop_container(old_id, timeout=svc.drain) + clean = containers.remove_container(old_id) and clean + clean = _scale_back(svc.name, env, compose_cmd) and clean + if not clean: + # The new container is serving, but the old one may be too. + log.failure(f"{svc.name} cutover incomplete: old container {old_id[:7]} remains") + return end(SVC_DIRTY) elapsed = time.time() - svc_start log.success(f"{svc.name} deployed ({elapsed:.1f}s)") - log.service_end() - return 0 + return end(SVC_OK) else: # 5b. Abort: stop new, remove new, scale back log.step(f"aborting: stopping new container ({new_id[:7]})...") - containers.stop_container(new_id) - containers.remove_container(new_id) - _scale_back(svc.name, env, compose_cmd) - log.step("aborted, old container still serving") + clean = containers.stop_container(new_id) + clean = containers.remove_container(new_id) and clean + clean = _scale_back(svc.name, env, compose_cmd) and clean + if clean: + log.step("aborted, old container still serving") + else: + log.step(f"abort incomplete: new container {new_id[:7]} may still be running") log.failure(f"{svc.name} FAILED") - log.service_end() - return 1 + return end(SVC_FAILED if clean else SVC_DIRTY) def _wait_for_healthy(container_id: str, timeout: int, poll_interval: int) -> bool: @@ -444,13 +536,17 @@ def _wait_for_healthy(container_id: str, timeout: int, poll_interval: int) -> bo return False -def _scale_back(service_name: str, env: dict, compose_cmd: list[str]) -> None: - """Scale service back to 1.""" - compose.compose_run( +def _scale_back(service_name: str, env: dict, compose_cmd: list[str]) -> bool: + """Scale service back to 1. Returns False if compose failed.""" + result = compose.compose_run( ["up", "-d", "--no-deps", "--scale", f"{service_name}=1", service_name], env=env, cmd=compose_cmd, ) + if result.returncode != 0: + log.failure(f"scale back failed: {result.stderr.strip()}") + return False + return True def _dry_run(tag: str, services: list[config.ServiceConfig]) -> None: diff --git a/tests/test_cli.py b/tests/test_cli.py index b1c496c..3f8c3e1 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -148,6 +148,49 @@ def test_config_with_command(mock_config, mock_env, mock_discover): mock_config.assert_called_once_with(cmd=["docker", "compose"]) +STATUS_COMPOSE = { + "services": { + "web": {"labels": {"deploy.role": "app"}}, + "postgres": {"labels": {"deploy.role": "accessory"}}, + } +} + + +@patch("flow_deploy.containers.get_container_health") +@patch("flow_deploy.containers.get_containers_for_service") +@patch("flow_deploy.git.current_sha") +@patch("flow_deploy.compose.compose_config") +def test_status_lists_each_service(mock_config, mock_sha, mock_ctrs, mock_health, capsys): + mock_config.return_value = STATUS_COMPOSE + mock_sha.return_value = "abc1234def" + mock_ctrs.side_effect = lambda name: ( + [{"ID": "0123456789abcdef", "Image": "app:v1", "State": "running"}] if name == "web" else [] + ) + mock_health.return_value = None + result = CliRunner().invoke(main, ["status"]) + assert result.exit_code == 0 + out = capsys.readouterr().out + result.output + assert "Current SHA: abc1234" in out + assert "web (app) 0123456789ab app:v1 running/none" in out + assert "postgres (accessory) no containers" in out + + +@patch("flow_deploy.git.current_sha") +@patch("flow_deploy.compose.compose_config") +def test_status_without_a_sha(mock_config, mock_sha, capsys): + mock_config.return_value = {"services": {}} + mock_sha.return_value = "" + result = CliRunner().invoke(main, ["status"]) + assert result.exit_code == 0 + assert "Current SHA: (none)" in capsys.readouterr().out + result.output + + +@patch("flow_deploy.compose.compose_config") +def test_status_compose_failure(mock_config): + mock_config.side_effect = RuntimeError("compose config failed: bad") + assert CliRunner().invoke(main, ["status"]).exit_code == 1 + + def test_help(): runner = CliRunner() result = runner.invoke(main, ["--help"]) diff --git a/tests/test_containers.py b/tests/test_containers.py index a7340d0..fd139b7 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -61,6 +61,27 @@ def test_identify_old_new_same_tag(): assert n["ID"] == "new1" +def test_get_containers_filters_by_project(mock_process): + mock_process.responses.append(process.Result(0, "", "")) + get_containers_for_service("web", project="myapp") + _, args, _, _ = mock_process.calls[0] + assert "com.docker.compose.project=myapp" in " ".join(args) + + +def test_identify_old_new_same_tag_newer_listed_first(): + new = {"ID": "new1", "Image": "app:latest", "CreatedAt": "2024-01-02 00:00:00"} + old = {"ID": "old1", "Image": "app:latest", "CreatedAt": "2024-01-01 00:00:00"} + o, n = identify_old_new([new, old], "latest") + assert o["ID"] == "old1" + assert n["ID"] == "new1" + + +def test_identify_old_new_indistinguishable(): + a = {"ID": "a", "Image": "app:latest", "CreatedAt": "2024-01-01 00:00:00"} + b = {"ID": "b", "Image": "app:latest", "CreatedAt": "2024-01-01 00:00:00"} + assert identify_old_new([a, b], "latest") == (None, None) + + def test_identify_wrong_count(): assert identify_old_new([], "v1") == (None, None) c = {"ID": "a", "Image": "app:v1", "CreatedAt": "2024-01-01"} diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py new file mode 100644 index 0000000..02bcebc --- /dev/null +++ b/tests/test_deploy_failures.py @@ -0,0 +1,298 @@ +"""Failure paths: signals, crashes, cleanup failures, and their exit codes.""" + +import signal + +import pytest + +from flow_deploy import deploy as deploy_mod +from flow_deploy.deploy import EXIT_DEGRADED, EXIT_FAILED, _image_tag, _wait_for_healthy, deploy +from tests.test_deploy import ( + COMPOSE_CMD, + COMPOSE_CONFIG_YAML, + WEB_CONTAINER_NEW, + WEB_CONTAINER_OLD, + _chdir, + _err, + _git_preflight, + _ok, +) +from tests.test_drain_first import COMPOSE_CONFIG_YAML as DRAIN_CONFIG +from tests.test_drain_first import WORKER_DRAIN, WORKER_NEW, _commands + +WEB_ONLY = ["web"] + + +def _lock_released(tmp_path): + return not (tmp_path / ".git" / "deploy-lock").exists() + + +# --------------------------------------------------------------------------- +# Signals and unexpected exceptions revert like any other failure +# --------------------------------------------------------------------------- + + +def test_sigterm_mid_deploy_restores_drained_and_releases(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + original = signal.getsignal(signal.SIGTERM) + + def cancelled(*args, **kwargs): + # What a cancelled CI job delivers while web is rolling. + signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) + + monkeypatch.setattr(deploy_mod, "_deploy_service", cancelled) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + *WORKER_DRAIN, + _ok(), # git restore + _ok(), # worker: restore on old tag + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + assert _lock_released(tmp_path) + assert signal.getsignal(signal.SIGTERM) is original + + +def test_unexpected_exception_reverts(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + + def boom(*args, **kwargs): + raise KeyError("Image") + + monkeypatch.setattr(deploy_mod, "_deploy_service", boom) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + *WORKER_DRAIN, + _ok(), # git restore + _ok(), # worker: restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert "unexpected error: KeyError('Image'); reverting" in capsys.readouterr().err + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + assert _lock_released(tmp_path) + + +def test_exception_before_checkout_skips_git_restore(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + + def broken(_tag): + raise OSError("git not found") + + monkeypatch.setattr(deploy_mod.git, "preflight_and_checkout", broken) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert mock_process.calls == [] # nothing to restore + assert _lock_released(tmp_path) + + +def test_interrupt_during_start_keeps_already_started_services(mock_process, monkeypatch, tmp_path): + """Services healthy on the new tag stay; only unstarted ones are restored.""" + _chdir(monkeypatch, tmp_path) + two = DRAIN_CONFIG + ( + " scheduler:\n" + " image: ghcr.io/myorg/myapp:latest\n" + " labels:\n" + " deploy.role: app\n" + " deploy.strategy: drain-first\n" + ' deploy.order: "300"\n' + " healthcheck:\n" + ' test: ["CMD", "true"]\n' + ) + real_start = deploy_mod._start_service + + def start(svc, *args, **kwargs): + if svc.name == "scheduler": + signal.getsignal(signal.SIGINT)(signal.SIGINT, None) + return real_start(svc, *args, **kwargs) + + monkeypatch.setattr(deploy_mod, "_start_service", start) + monkeypatch.setattr(deploy_mod, "_deploy_service", lambda *a, **kw: 0) + sched_old = '{"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.1.0"}' + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(two), + _ok(), # scheduler: pull + _ok(sched_old + "\n"), # scheduler: ps + _ok(), # scheduler: stop + _ok(), # scheduler: rm + *WORKER_DRAIN, + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: ps + _ok("healthy\n"), # worker: health + _ok(), # git restore + _ok(), # scheduler: restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + restores = [c for c in mock_process.calls if c[2] and c[2]["DEPLOY_TAG"] != "abc123"] + assert [c[2]["DEPLOY_TAG"] for c in restores] == ["v1.1.0"] # scheduler only + + +# --------------------------------------------------------------------------- +# Cleanup failures turn a clean failure (1) into a degraded one (3) +# --------------------------------------------------------------------------- + + +def test_rolling_abort_cleanup_failure_is_degraded(mock_process, monkeypatch, tmp_path, capsys): + _chdir(monkeypatch, tmp_path) + monkeypatch.setattr(deploy_mod, "_wait_for_healthy", lambda *a, **kw: False) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps + _err("stop failed"), # web: stop new + _ok(), # web: rm new + _ok(), # web: scale back + _ok(), # git restore + ] + ) + result = deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) + assert result == EXIT_DEGRADED + captured = capsys.readouterr() + assert "abort incomplete: new container new_web" in captured.out + assert "cleanup failed for web" in captured.err + + +def test_rolling_cutover_cleanup_failure_is_degraded(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps + _ok("healthy\n"), # web: health + _err("stop failed"), # web: stop old + _ok(), # web: rm old + _ok(), # web: scale back + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == EXIT_DEGRADED + + +@pytest.mark.parametrize(("scale_back", "expected"), [(_ok(), 1), (_err("busy"), 3)]) +def test_rolling_scale_up_failure(mock_process, monkeypatch, tmp_path, scale_back, expected): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # web: pull + _err("port in use"), # web: scale to 2 + scale_back, # web: scale back + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == expected + + +def test_rolling_unidentifiable_containers_scale_back(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + twin = '{"ID": "%s", "Image": "ghcr.io/myorg/myapp:abc123", "CreatedAt": "2024-01-01"}' + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(COMPOSE_CONFIG_YAML), + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(twin % "a1" + "\n" + twin % "b2" + "\n"), # web: ps (same tag, same time) + _ok(), # web: scale back + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == EXIT_FAILED + + +@pytest.mark.parametrize( + ("stop", "rm"), [(_err("stuck"), _ok()), (_ok(), _err("in use"))], ids=["stop", "rm"] +) +def test_failed_start_that_cannot_be_removed_is_degraded( + mock_process, monkeypatch, tmp_path, stop, rm +): + _chdir(monkeypatch, tmp_path) + monkeypatch.setattr(deploy_mod, "_wait_for_healthy", lambda *a, **kw: False) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + *WORKER_DRAIN, + _ok(), # worker: compose up + _ok(WORKER_NEW + "\n"), # worker: ps + stop, # worker: stop unhealthy new + rm, # worker: rm unhealthy new + _ok(), # git restore + _ok(), # worker: restore + ] + ) + result = deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) + assert result == EXIT_DEGRADED + + +def test_start_scales_to_the_drained_replica_count(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + old2 = '{"ID": "old_wrk_555", "Image": "ghcr.io/myorg/myapp:v1.2.0"}' + new2 = '{"ID": "new_wrk_888", "Image": "ghcr.io/myorg/myapp:abc123"}' + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + _ok(), # worker: pull + _ok(WORKER_DRAIN[1].stdout.strip() + "\n" + old2 + "\n"), # worker: ps (2) + _ok(), # stop 1 + _ok(), # rm 1 + _ok(), # stop 2 + _ok(), # rm 2 + _ok(), # worker: compose up --scale worker=2 + _ok(WORKER_NEW + "\n" + new2 + "\n"), # worker: ps (2) + _ok("healthy\n"), # worker 1: health + _ok("healthy\n"), # worker 2: health + ] + ) + assert deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) == 0 + assert any("--scale worker=2 worker" in c for c in _commands(mock_process)) + + +# --------------------------------------------------------------------------- +# Dry run and helpers +# --------------------------------------------------------------------------- + + +def test_dry_run_compose_failure(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.append(_err("bad compose file")) + assert deploy(tag="abc123", dry_run=True, cmd=COMPOSE_CMD) == 1 + + +def test_dry_run_unknown_service(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.append(_ok(COMPOSE_CONFIG_YAML)) + assert deploy(tag="abc123", dry_run=True, services_filter=["nope"], cmd=COMPOSE_CMD) == 1 + + +def test_image_tag_bare_id_has_no_tag(): + assert _image_tag("sha256:0123abcd") is None + + +def test_wait_for_healthy_returns_false_when_unhealthy(monkeypatch): + statuses = iter(["starting", "unhealthy"]) + monkeypatch.setattr(deploy_mod.containers, "get_container_health", lambda _: next(statuses)) + monkeypatch.setattr(deploy_mod.time, "sleep", lambda _: None) + assert _wait_for_healthy("abc", timeout=60, poll_interval=1) is False + + +def test_wait_for_healthy_times_out(monkeypatch): + clock = iter([0, 0, 61]) + monkeypatch.setattr(deploy_mod.time, "time", lambda: next(clock)) + monkeypatch.setattr(deploy_mod.containers, "get_container_health", lambda _: "starting") + monkeypatch.setattr(deploy_mod.time, "sleep", lambda _: None) + assert _wait_for_healthy("abc", timeout=60, poll_interval=1) is False diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 83d21a3..4ad8a17 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -78,7 +78,7 @@ def test_drain_first_runs_drain_then_rolling_then_start(mock_process, monkeypatc cmds = _commands(mock_process) drain = _index(cmds, "docker stop", "--time 3660", "old_wrk_333") roll = _index(cmds, "--scale web=2") - start = _index(cmds, "up -d --no-deps worker") + start = _index(cmds, "--scale worker=1 worker") assert drain < roll < start # The worker never scales to 2: no overlap of old and new. assert not any("--scale worker=2" in c for c in cmds) @@ -185,7 +185,7 @@ def test_drained_service_that_was_not_running_stays_stopped_on_failure( ] ) assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert not any("up -d --no-deps worker" in c for c in _commands(mock_process)) + assert not any("--scale worker=1 worker" in c for c in _commands(mock_process)) def test_start_failure_restores_previous_container(mock_process, monkeypatch, tmp_path, capsys): @@ -478,8 +478,8 @@ def test_drains_in_reverse_order_and_starts_in_order(mock_process, monkeypatch, _index(cmds, "docker stop", "old_sch_666") < _index(cmds, "docker stop", "old_wrk_333") < _index(cmds, "--scale web=2") - < _index(cmds, "up -d --no-deps worker") - < _index(cmds, "up -d --no-deps scheduler") + < _index(cmds, "--scale worker=1 worker") + < _index(cmds, "--scale scheduler=1 scheduler") ) @@ -527,7 +527,7 @@ def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, ) assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 cmds = _commands(mock_process) - assert any("up -d --no-deps scheduler" in c for c in cmds) + assert any("--scale scheduler=1 scheduler" in c for c in cmds) # Only the failed worker goes back; the healthy new scheduler stays. assert "--scale worker=1 worker" in cmds[-1] assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..8bb12c6 --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,18 @@ +"""Tests for flow_deploy/__init__.py — version resolution.""" + +import importlib +import importlib.metadata + +import flow_deploy + + +def test_version_falls_back_when_package_metadata_is_missing(monkeypatch): + def missing(name): + raise importlib.metadata.PackageNotFoundError(name) + + monkeypatch.setattr(importlib.metadata, "version", missing) + try: + assert importlib.reload(flow_deploy).__version__ == "0.0.0" + finally: + monkeypatch.undo() + importlib.reload(flow_deploy) diff --git a/tests/test_lock.py b/tests/test_lock.py index 83143ef..3c008a7 100644 --- a/tests/test_lock.py +++ b/tests/test_lock.py @@ -53,3 +53,9 @@ def test_release_no_file(): def test_read_lock_no_file(): assert read_lock() is None + + +def test_read_lock_corrupt_returns_none(): + with open(".git/deploy-lock", "w") as f: + f.write("{not json") + assert read_lock() is None diff --git a/tests/test_log.py b/tests/test_log.py index 3e1b32b..e458fc9 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -111,3 +111,13 @@ def test_error(capsys): error("something broke") err = capsys.readouterr().err assert "ERROR: something broke" in err + + +def test_error_github_actions_annotates(capsys, monkeypatch): + monkeypatch.setenv("GITHUB_ACTIONS", "true") + from flow_deploy.log import error + + error("boom") + captured = capsys.readouterr() + assert "::error::boom" in captured.out + assert "ERROR: boom" in captured.err diff --git a/tests/test_process.py b/tests/test_process.py index b45063b..3ba0668 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -40,3 +40,8 @@ def test_run_streaming_returns_exit_code(): def test_run_streaming_nonzero(): code = run_streaming(["false"]) assert code != 0 + + +def test_run_streaming_with_env(): + code = run_streaming(["sh", "-c", 'test "$TEST_VAR" = works'], env={"TEST_VAR": "works"}) + assert code == 0 From e2a6479ff50abcca35e745dd39659b75998c4678 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Thu, 8 Oct 2026 23:06:26 -0600 Subject: [PATCH 06/19] Survive a cancel mid-drain and a dropped ssh session From self-review: - _drain_service records what's running before stopping anything, so a signal during a long drain (up to the longest task) still restores the service instead of leaving it down. - SIGHUP reverts too. deploy-action runs flow-deploy over ssh; a cancelled CI job kills the ssh client and the remote process gets SIGHUP, which previously killed it with no revert. - Logging never raises: once the ssh session is gone, stdout/stderr writes fail with OSError, which would have crashed the revert. - Signals are ignored inside _Run.revert itself, so a second signal during a normal failure's revert can't cut it short or start another. - Dry run returns EXIT_* constants. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 7 ++-- src/flow_deploy/deploy.py | 62 ++++++++++++++++++-------------- src/flow_deploy/log.py | 28 ++++++++++----- tests/test_deploy_failures.py | 66 +++++++++++++++++++++++++++++++++++ tests/test_log.py | 28 +++++++++++++++ 5 files changed, 154 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 86126e7..ae4b84b 100644 --- a/README.md +++ b/README.md @@ -136,8 +136,11 @@ directly or through an env var that expands to it. A restore runs `compose up` with the previous tag in `DEPLOY_TAG`. A service whose image ignores it comes back on whatever the compose file names. -A signal (a cancelled CI job, Ctrl-C) or an unexpected error reverts the same -way. Further signals are ignored until the revert finishes. Drain-first services +A signal reverts the same way, and so does an unexpected error. The signals are +SIGTERM, Ctrl-C (SIGINT), and SIGHUP. SIGHUP is what a remote deploy receives +when the CI job driving it over ssh is cancelled. Further signals are ignored +until the revert finishes, and logging keeps going even if the session's output +has gone away. Drain-first services already healthy on the new tag stay. Cleanup that fails along the way (a new container that won't stop or be removed, a scale-back that fails) also makes the deploy exit `3`. diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 33e140b..b4b22fe 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -11,6 +11,10 @@ EXIT_LOCKED = 2 EXIT_DEGRADED = 3 # failed, and something couldn't be put back +# Signals that revert the deploy. SIGHUP is what a remote deploy gets when its +# ssh session dies, e.g. when the CI job driving it is cancelled. +HANDLED_SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP) + # Per-service outcomes from _deploy_service and _start_service. SVC_OK = 0 SVC_FAILED = 1 # failed, and its own cleanup succeeded @@ -56,6 +60,9 @@ def revert(self, reason: str, down: list[Drained] | None = None) -> int: schema, as rolling deploys already assume. Exits 3 only when something can't be put back. """ + # Don't let a further signal cut the revert short (or start a second one). + for signum in HANDLED_SIGNALS: + signal.signal(signum, signal.SIG_IGN) if down is None: down = [r for r in self.drained if r.svc.name not in self.started] log.info("") @@ -89,12 +96,12 @@ def deploy( compose_dict = compose.compose_config(cmd=compose_cmd) except RuntimeError as e: log.error(str(e)) - return 1 + return EXIT_FAILED app_services = _resolve_app_services(compose_dict, services_filter) if app_services is None: - return 1 + return EXIT_FAILED _dry_run(tag, app_services) - return 0 + return EXIT_OK # Acquire lock before any mutations (git checkout, container changes) if not lock.acquire(): @@ -103,23 +110,20 @@ def deploy( log.error(f"Deploy lock held by PID {pid}") return EXIT_LOCKED - # A signal (a cancelled CI job, Ctrl-C) reverts like any other failure. - _original_sigterm = signal.getsignal(signal.SIGTERM) - _original_sigint = signal.getsignal(signal.SIGINT) + # A signal (a cancelled CI job, Ctrl-C, a dropped ssh session) reverts + # like any other failure. + originals = {signum: signal.getsignal(signum) for signum in HANDLED_SIGNALS} def _interrupt(signum, frame): raise Interrupted(signum) - signal.signal(signal.SIGTERM, _interrupt) - signal.signal(signal.SIGINT, _interrupt) + for signum in HANDLED_SIGNALS: + signal.signal(signum, _interrupt) run = _Run(compose_cmd) try: return _deploy_locked(run, tag, tag_provided, services_filter) except (Exception, Interrupted) as exc: - # Don't let a second signal cut the revert short. - signal.signal(signal.SIGTERM, signal.SIG_IGN) - signal.signal(signal.SIGINT, signal.SIG_IGN) if isinstance(exc, Interrupted): reason = f"interrupted by signal {exc.signum}" else: @@ -130,8 +134,8 @@ def _interrupt(signum, frame): # Always released: a failed deploy puts things back rather than # leaving state for someone to clean up by hand. lock.release() - signal.signal(signal.SIGTERM, _original_sigterm) - signal.signal(signal.SIGINT, _original_sigint) + for signum, handler in originals.items(): + signal.signal(signum, handler) def _deploy_locked( @@ -184,10 +188,7 @@ def failed(reason: str, down: list[Drained] | None = None) -> int: # anything rolls, so none of their old code runs beside new code. What # each one was running is kept to bring it back on failure. for svc in reversed(drain_first): - result, record = _drain_service(svc, tag, compose_cmd, project=project) - if record is not None: - run.drained.append(record) - if result != 0: + if _drain_service(svc, tag, compose_cmd, run.drained, project=project) != 0: return failed("deploy aborted") # Phase 2: rolling services, in deploy order, as before. @@ -293,14 +294,20 @@ def _image_tag(image: str) -> str | None: def _drain_service( - svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" -) -> tuple[int, Drained | None]: + svc: config.ServiceConfig, + tag: str, + compose_cmd: list[str], + drained: list[Drained], + project: str = "", +) -> int: """Pull the new image, then stop and remove the running containers. - Pulls first so an unpullable tag fails before anything stops, returning - (1, None). Otherwise returns the record of what was running, with exit - code 1 if any container failed to stop or be removed: the caller must not - roll anything while old code may still be running. + Pulls first so an unpullable tag fails before anything stops. Records + what was running on ``drained`` *before* stopping anything, so a signal + mid-drain (a drain can take as long as the service's longest task) still + knows what to restore. Returns 1 if the pull failed or any container + failed to stop or be removed: the caller must not roll anything while old + code may still be running. """ log.service_start(svc.name) svc_start = time.time() @@ -308,7 +315,7 @@ def _drain_service( if not _pull(svc, env, compose_cmd): log.service_end() - return 1, None + return 1 ctrs = containers.get_containers_for_service(svc.name, project=project) images = list(dict.fromkeys(c.get("Image", "") for c in ctrs)) @@ -316,6 +323,7 @@ def _drain_service( if images: record.old_image = images[0] record.old_tag = _image_tag(images[0]) + drained.append(record) if len(images) > 1: log.error( f"{svc.name} was running mixed images ({', '.join(images)}); " @@ -330,15 +338,15 @@ def _drain_service( if not containers.stop_container(ctr_id, timeout=svc.drain): log.failure(f"could not stop {ctr_id[:7]}; it may still be running") log.service_end() - return 1, record + return 1 if not containers.remove_container(ctr_id): log.failure(f"could not remove {ctr_id[:7]}") log.service_end() - return 1, record + return 1 log.success(f"{svc.name} drained ({time.time() - svc_start:.1f}s)") log.service_end() - return 0, record + return 0 def _start_service( diff --git a/src/flow_deploy/log.py b/src/flow_deploy/log.py index be464c5..8ce67f6 100644 --- a/src/flow_deploy/log.py +++ b/src/flow_deploy/log.py @@ -13,14 +13,26 @@ def _is_github_actions() -> bool: return os.environ.get("GITHUB_ACTIONS") == "true" +def _write(text: str, stream=None) -> None: + """Print, but never raise. + + When a remote deploy's ssh session drops, its stdout and stderr go with + it. Logging must not then crash the revert that's putting things back. + """ + try: + print(text, file=stream or sys.stdout, flush=True) + except (OSError, ValueError): + pass + + def info(msg: str) -> None: - print(f"[{_timestamp()}] {msg}", flush=True) + _write(f"[{_timestamp()}] {msg}") def header(title: str) -> None: line = f"── {title} " + "─" * max(0, 45 - len(title)) if _is_github_actions(): - print(f"::group::{title}", flush=True) + _write(f"::group::{title}") info(line) @@ -28,18 +40,18 @@ def footer(title: str) -> None: line = f"── {title} " + "─" * max(0, 45 - len(title)) info(line) if _is_github_actions(): - print("::endgroup::", flush=True) + _write("::endgroup::") def service_start(name: str) -> None: if _is_github_actions(): - print(f"::group::{name}", flush=True) + _write(f"::group::{name}") info(f"▸ {name}") def service_end() -> None: if _is_github_actions(): - print("::endgroup::", flush=True) + _write("::endgroup::") def step(msg: str) -> None: @@ -52,11 +64,11 @@ def success(msg: str) -> None: def failure(msg: str) -> None: if _is_github_actions(): - print(f"::error::{msg}", flush=True) + _write(f"::error::{msg}") info(f" ✗ {msg}") def error(msg: str) -> None: if _is_github_actions(): - print(f"::error::{msg}", flush=True) - print(f"[{_timestamp()}] ERROR: {msg}", file=sys.stderr, flush=True) + _write(f"::error::{msg}") + _write(f"[{_timestamp()}] ERROR: {msg}", stream=sys.stderr) diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py index 02bcebc..f5b1ad6 100644 --- a/tests/test_deploy_failures.py +++ b/tests/test_deploy_failures.py @@ -55,6 +55,72 @@ def cancelled(*args, **kwargs): assert signal.getsignal(signal.SIGTERM) is original +def test_sighup_from_a_dropped_ssh_session_reverts(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + + def hung_up(*args, **kwargs): + signal.getsignal(signal.SIGHUP)(signal.SIGHUP, None) + + monkeypatch.setattr(deploy_mod, "_deploy_service", hung_up) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + *WORKER_DRAIN, + _ok(), # git restore + _ok(), # worker: restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + + +def test_signal_while_a_drain_is_stopping_still_restores(mock_process, monkeypatch, tmp_path): + """A drain can take an hour: a cancel mid-stop must still know what to restore.""" + _chdir(monkeypatch, tmp_path) + + def stop_interrupted(container_id, timeout=30): + signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) + + monkeypatch.setattr(deploy_mod.containers, "stop_container", stop_interrupted) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + _ok(), # worker: pull + WORKER_DRAIN[1], # worker: docker ps + _ok(), # git restore + _ok(), # worker: restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert "--scale worker=1 worker" in _commands(mock_process)[-1] + assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + + +def test_signals_are_ignored_while_reverting(mock_process, monkeypatch, tmp_path): + """A second signal mid-revert neither cuts it short nor starts another.""" + _chdir(monkeypatch, tmp_path) + seen = [] + + def restore(drained, compose_cmd): + seen.append(signal.getsignal(signal.SIGTERM)) + return True + + monkeypatch.setattr(deploy_mod, "_restore_drained", restore) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + *WORKER_DRAIN, + _err("pull failed"), # web: pull + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert seen == [signal.SIG_IGN] + + def test_unexpected_exception_reverts(mock_process, monkeypatch, tmp_path, capsys): _chdir(monkeypatch, tmp_path) diff --git a/tests/test_log.py b/tests/test_log.py index e458fc9..1fa1736 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -113,6 +113,34 @@ def test_error(capsys): assert "ERROR: something broke" in err +def test_logging_survives_a_closed_stream(monkeypatch): + """A dropped ssh session closes stdout/stderr; logging must not raise.""" + import io + + from flow_deploy import log + + closed = io.StringIO() + closed.close() + monkeypatch.setattr("sys.stdout", closed) + monkeypatch.setattr("sys.stderr", closed) + log.info("still here") + log.error("still here") + + +def test_logging_survives_an_io_error(monkeypatch): + from flow_deploy import log + + class Hungup: + def write(self, _text): + raise OSError(5, "Input/output error") + + def flush(self): + pass + + monkeypatch.setattr("sys.stdout", Hungup()) + log.step("still here") + + def test_error_github_actions_annotates(capsys, monkeypatch): monkeypatch.setenv("GITHUB_ACTIONS", "true") from flow_deploy.log import error From 016c4a531b5a3c870656d4b8474100f5c2935a1d Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Thu, 8 Oct 2026 23:10:25 -0600 Subject: [PATCH 07/19] Close signal windows around the lock and in cleanup From the fourth review: - Signal handlers are installed before the lock is taken, and the lock is acquired inside the guarded block, so a signal can't land between the two and skip cleanup. The finally only releases a lock this process actually holds. - The finally ignores signals before releasing the lock and restoring the original handlers, so a signal there can't skip the rest. - Phase 3 starting a drain-first service that wasn't running at one replica is deliberate (newly added or crashed services come up with the deploy); the comment and test now say so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- src/flow_deploy/deploy.py | 30 +++++++++++++++--------- tests/test_deploy_failures.py | 44 +++++++++++++++++++++++++++++++++++ tests/test_drain_first.py | 7 +++++- 3 files changed, 69 insertions(+), 12 deletions(-) diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index b4b22fe..282f834 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -103,15 +103,9 @@ def deploy( _dry_run(tag, app_services) return EXIT_OK - # Acquire lock before any mutations (git checkout, container changes) - if not lock.acquire(): - lock_info = lock.read_lock() - pid = lock_info["pid"] if lock_info else "unknown" - log.error(f"Deploy lock held by PID {pid}") - return EXIT_LOCKED - # A signal (a cancelled CI job, Ctrl-C, a dropped ssh session) reverts - # like any other failure. + # like any other failure. Handlers go in before the lock is taken, so no + # signal can land between the two and skip cleanup. originals = {signum: signal.getsignal(signum) for signum in HANDLED_SIGNALS} def _interrupt(signum, frame): @@ -121,7 +115,15 @@ def _interrupt(signum, frame): signal.signal(signum, _interrupt) run = _Run(compose_cmd) + locked = False try: + # Acquire lock before any mutations (git checkout, container changes) + locked = lock.acquire() + if not locked: + lock_info = lock.read_lock() + pid = lock_info["pid"] if lock_info else "unknown" + log.error(f"Deploy lock held by PID {pid}") + return EXIT_LOCKED return _deploy_locked(run, tag, tag_provided, services_filter) except (Exception, Interrupted) as exc: if isinstance(exc, Interrupted): @@ -131,9 +133,13 @@ def _interrupt(signum, frame): log.error(f"{reason}; reverting") return run.revert(reason) finally: + # Ignore signals first, so one landing here can't skip the rest. + for signum in HANDLED_SIGNALS: + signal.signal(signum, signal.SIG_IGN) # Always released: a failed deploy puts things back rather than # leaving state for someone to clean up by hand. - lock.release() + if locked: + lock.release() for signum, handler in originals.items(): signal.signal(signum, handler) @@ -200,8 +206,10 @@ def failed(reason: str, down: list[Drained] | None = None) -> int: return failed("deploy aborted") # Phase 3: drain-first services start in deploy order, at the replica - # count they ran. Every one is attempted, so one failure doesn't strand - # the rest; a failed one goes back to what it ran before. + # count they ran. One that wasn't running (just added in this release, + # or crashed) starts at 1: a deploy brings its services up. Every one is + # attempted, so one failure doesn't strand the rest; a failed one goes + # back to what it ran before. by_name = {record.svc.name: record for record in run.drained} failures = [] for svc in drain_first: diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py index f5b1ad6..0d94835 100644 --- a/tests/test_deploy_failures.py +++ b/tests/test_deploy_failures.py @@ -121,6 +121,50 @@ def restore(drained, compose_cmd): assert seen == [signal.SIG_IGN] +def test_signal_while_taking_the_lock_changes_nothing(mock_process, monkeypatch, tmp_path): + """Handlers are installed before the lock, so even this signal is handled.""" + _chdir(monkeypatch, tmp_path) + released = [] + + def acquire_interrupted(): + signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) + + monkeypatch.setattr(deploy_mod.lock, "acquire", acquire_interrupted) + monkeypatch.setattr(deploy_mod.lock, "release", lambda: released.append(True)) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert mock_process.calls == [] + assert released == [] # never held, so never released + + +def test_finally_ignores_signals_while_releasing(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + original = signal.getsignal(signal.SIGHUP) + during_release = [] + real_release = deploy_mod.lock.release + + def release(): + during_release.append(signal.getsignal(signal.SIGHUP)) + real_release() + + monkeypatch.setattr(deploy_mod.lock, "release", release) + mock_process.responses.extend([*_git_preflight(), _ok(COMPOSE_CONFIG_YAML), *_web_roll()]) + assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == 0 + assert during_release == [signal.SIG_IGN] + assert signal.getsignal(signal.SIGHUP) is original + + +def _web_roll(): + return [ + _ok(), # web: pull + _ok(), # web: scale to 2 + _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps + _ok("healthy\n"), # web: health + _ok(), # web: stop old + _ok(), # web: rm old + _ok(), # web: scale back + ] + + def test_unexpected_exception_reverts(mock_process, monkeypatch, tmp_path, capsys): _chdir(monkeypatch, tmp_path) diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 4ad8a17..7c3c7e0 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -84,7 +84,11 @@ def test_drain_first_runs_drain_then_rolling_then_start(mock_process, monkeypatc assert not any("--scale worker=2" in c for c in cmds) -def test_drain_first_service_not_running_is_started_after(mock_process, monkeypatch, tmp_path): +def test_drain_first_service_not_running_is_started_at_one_replica( + mock_process, monkeypatch, tmp_path +): + """Deliberate: a service with no containers (newly added, or crashed) comes + up with the deploy rather than staying at zero.""" _chdir(monkeypatch, tmp_path) mock_process.responses.extend( [ @@ -99,6 +103,7 @@ def test_drain_first_service_not_running_is_started_after(mock_process, monkeypa ] ) assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 + assert any("--scale worker=1 worker" in c for c in _commands(mock_process)) def test_rolling_failure_restores_drained_service_on_its_old_tag( From 97cd5c871061b511426ba8b72b1322745bd679f5 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sat, 10 Oct 2026 11:52:50 -0600 Subject: [PATCH 08/19] Keep rolling deploys identical to master; pin it with a parity test Reliability review: a project that doesn't use drain-first must see exactly master's behavior. - Scale-up failure no longer issues a scale-back; as on master it fails without further compose commands. - A successful cutover whose old-container stop/rm/scale-back fails succeeds again with a warning, as on master. The usual cause is the old container having exited on its own; failing would revert the repo underneath a healthy new container. - tests/test_rolling_parity.py replays nine rolling scenarios (success, health abort, pull/scale-up/compose-config failures, container-count mismatch, cutover cleanup failure, dirty tree, restore failure) against fixtures/rolling_master.json, recorded by running them on master 0.3.0: every docker/compose command, its env, the exit code, and the lock. All match; the one agreed departure (failed git restore exits 3 and releases the lock) is listed in DELIBERATE_CHANGES. Drain-first: - A docker ps failure during a drain aborts before anything rolls instead of reading as "nothing running" (new containers.list_containers_for_service returns None on failure; the rolling helper is unchanged). Restarting containers are drained too. - --service skipping drain-first services is a plain warning line, not an ::error:: annotation on a deploy that succeeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 23 +- src/flow_deploy/containers.py | 17 +- src/flow_deploy/deploy.py | 30 +- tests/fixtures/rolling_master.json | 965 +++++++++++++++++++++++++++++ tests/test_deploy_failures.py | 62 +- tests/test_drain_first.py | 7 +- tests/test_rolling_parity.py | 102 +++ 7 files changed, 1177 insertions(+), 29 deletions(-) create mode 100644 tests/fixtures/rolling_master.json create mode 100644 tests/test_rolling_parity.py diff --git a/README.md b/README.md index ae4b84b..9f667e8 100644 --- a/README.md +++ b/README.md @@ -140,15 +140,24 @@ A signal reverts the same way, and so does an unexpected error. The signals are SIGTERM, Ctrl-C (SIGINT), and SIGHUP. SIGHUP is what a remote deploy receives when the CI job driving it over ssh is cancelled. Further signals are ignored until the revert finishes, and logging keeps going even if the session's output -has gone away. Drain-first services -already healthy on the new tag stay. Cleanup that fails along the way (a new -container that won't stop or be removed, a scale-back that fails) also makes the -deploy exit `3`. +has gone away. Drain-first services already healthy on the new tag stay. The deploy exits `1` when it failed and everything was put back. It exits `3` -only when something couldn't be: the git restore failed, a restore's -`compose up` failed, or the old image had no tag to restore. Even then the lock -is released. Exit `3` is the signal that someone needs to look. +only when something couldn't be put back: + +- the git restore failed +- a restore's `compose up` failed +- the old image had no tag to restore +- a *failed* service's own cleanup failed, such as an aborted new container + that won't stop or be removed + +Even then the lock is released. Exit `3` is the signal that someone needs to +look. + +Rolling deploys otherwise behave exactly as before; `tests/test_rolling_parity.py` +replays them against a recording of the previous release. As before, a +successful cutover whose old-container cleanup fails still succeeds, with a +warning: the new container is healthy and serving. Deploying rolling services with `--service` while leaving drain-first services out prints a warning, since those keep running old code. diff --git a/src/flow_deploy/containers.py b/src/flow_deploy/containers.py index 5f305dc..ee2bd67 100644 --- a/src/flow_deploy/containers.py +++ b/src/flow_deploy/containers.py @@ -9,15 +9,28 @@ def get_containers_for_service(service: str, project: str = "") -> list[dict]: """Get running containers for a service via docker ps. Returns list of dicts with keys: ID, Image, CreatedAt, State, Health. + An empty list if docker ps fails. + """ + return list_containers_for_service(service, project) or [] + + +def list_containers_for_service( + service: str, project: str = "", statuses: tuple[str, ...] = ("running",) +) -> list[dict] | None: + """Like get_containers_for_service, but None when docker ps fails. + + For callers that must not mistake "couldn't list" for "nothing running". + ``statuses`` are OR'd docker ps status filters. """ filters = ["--filter", f"label=com.docker.compose.service={service}"] if project: filters += ["--filter", f"label=com.docker.compose.project={project}"] - filters += ["--filter", "status=running"] + for status in statuses: + filters += ["--filter", f"status={status}"] result = process.run(["docker", "ps"] + filters + ["--format", "{{json .}}"]) if result.returncode != 0: - return [] + return None containers = [] for line in result.stdout.strip().splitlines(): diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 282f834..fa2ef57 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -252,9 +252,11 @@ def _resolve_app_services( selected = [s for s in app_services if s.name in services_filter] skipped = [s.name for s in app_services if s.drains_first and s not in selected] if skipped and any(not s.drains_first for s in selected): - log.error( - f"--service leaves drain-first {', '.join(skipped)} running old code " - "beside the new rolling services; include them unless that's intended" + # A warning, not an error: the deploy proceeds and can succeed. + log.info( + f"warning: --service leaves drain-first {', '.join(skipped)} running " + "old code beside the new rolling services; include them unless " + "that's intended" ) app_services = selected @@ -325,7 +327,16 @@ def _drain_service( log.service_end() return 1 - ctrs = containers.get_containers_for_service(svc.name, project=project) + # Restarting containers too: a crash-looping worker would otherwise come + # back on old code mid-deploy. + ctrs = containers.list_containers_for_service( + svc.name, project=project, statuses=("running", "restarting") + ) + if ctrs is None: + # Not knowing what's running is not the same as nothing running. + log.failure(f"could not list {svc.name} containers; not draining blind") + log.service_end() + return 1 images = list(dict.fromkeys(c.get("Image", "") for c in ctrs)) record = Drained(svc, replicas=len(ctrs)) if images: @@ -477,8 +488,9 @@ def end(code: int) -> int: cmd=compose_cmd, ) if result.returncode != 0: + # As on master: fail without issuing further compose commands. log.failure(f"scale up failed: {result.stderr.strip()}") - return end(SVC_FAILED if _scale_back(svc.name, env, compose_cmd) else SVC_DIRTY) + return end(SVC_FAILED) # 3. Get containers, identify old vs new ctrs = containers.get_containers_for_service(svc.name, project=project) @@ -518,9 +530,11 @@ def end(code: int) -> int: clean = containers.remove_container(old_id) and clean clean = _scale_back(svc.name, env, compose_cmd) and clean if not clean: - # The new container is serving, but the old one may be too. - log.failure(f"{svc.name} cutover incomplete: old container {old_id[:7]} remains") - return end(SVC_DIRTY) + # The new container is healthy and serving, so the deploy + # succeeded, as on master. A stop/rm failure here is usually the + # old container having already exited; failing would revert the + # repo underneath a healthy new container. + log.step(f"warning: cleanup of old container {old_id[:7]} did not complete") elapsed = time.time() - svc_start log.success(f"{svc.name} deployed ({elapsed:.1f}s)") diff --git a/tests/fixtures/rolling_master.json b/tests/fixtures/rolling_master.json new file mode 100644 index 0000000..c3e52b1 --- /dev/null +++ b/tests/fixtures/rolling_master.json @@ -0,0 +1,965 @@ +{ + "happy": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "rm", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "rm", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ] + ], + "lock_left": false + }, + "health_abort": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "rm", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": false + }, + "pull_fail": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": false + }, + "scale_up_fail": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": false + }, + "count_mismatch": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": false + }, + "restore_fail": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": true + }, + "cutover_stop_fail": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "rm", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "rm", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ] + ], + "lock_left": false + }, + "dirty_tree": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ] + ], + "lock_left": false + }, + "compose_config_fail": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": false + } +} diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py index 0d94835..98f40a3 100644 --- a/tests/test_deploy_failures.py +++ b/tests/test_deploy_failures.py @@ -271,7 +271,14 @@ def test_rolling_abort_cleanup_failure_is_degraded(mock_process, monkeypatch, tm assert "cleanup failed for web" in captured.err -def test_rolling_cutover_cleanup_failure_is_degraded(mock_process, monkeypatch, tmp_path): +def test_rolling_cutover_cleanup_failure_still_succeeds( + mock_process, monkeypatch, tmp_path, capsys +): + """As on master: the new container is healthy and serving, so it's a success. + + The usual cause is the old container having exited on its own; failing + here would revert the repo underneath a healthy new container. + """ _chdir(monkeypatch, tmp_path) mock_process.responses.extend( [ @@ -281,17 +288,19 @@ def test_rolling_cutover_cleanup_failure_is_degraded(mock_process, monkeypatch, _ok(), # web: scale to 2 _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps _ok("healthy\n"), # web: health - _err("stop failed"), # web: stop old + _err("No such container"), # web: stop old _ok(), # web: rm old _ok(), # web: scale back - _ok(), # git restore ] ) - assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == EXIT_DEGRADED + assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == 0 + captured = capsys.readouterr() + assert "warning: cleanup of old container old_web" in captured.out + assert "::error::" not in captured.out -@pytest.mark.parametrize(("scale_back", "expected"), [(_ok(), 1), (_err("busy"), 3)]) -def test_rolling_scale_up_failure(mock_process, monkeypatch, tmp_path, scale_back, expected): +def test_rolling_scale_up_failure_issues_no_further_commands(mock_process, monkeypatch, tmp_path): + """As on master: no scale-back after a failed scale-up.""" _chdir(monkeypatch, tmp_path) mock_process.responses.extend( [ @@ -299,14 +308,17 @@ def test_rolling_scale_up_failure(mock_process, monkeypatch, tmp_path, scale_bac _ok(COMPOSE_CONFIG_YAML), _ok(), # web: pull _err("port in use"), # web: scale to 2 - scale_back, # web: scale back _ok(), # git restore ] ) - assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == expected + assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == EXIT_FAILED + assert not any("--scale web=1" in c for c in _commands(mock_process)) -def test_rolling_unidentifiable_containers_scale_back(mock_process, monkeypatch, tmp_path): +@pytest.mark.parametrize(("scale_back", "expected"), [(_ok(), 1), (_err("busy"), 3)]) +def test_rolling_unidentifiable_containers_scale_back( + mock_process, monkeypatch, tmp_path, scale_back, expected +): _chdir(monkeypatch, tmp_path) twin = '{"ID": "%s", "Image": "ghcr.io/myorg/myapp:abc123", "CreatedAt": "2024-01-01"}' mock_process.responses.extend( @@ -316,11 +328,39 @@ def test_rolling_unidentifiable_containers_scale_back(mock_process, monkeypatch, _ok(), # web: pull _ok(), # web: scale to 2 _ok(twin % "a1" + "\n" + twin % "b2" + "\n"), # web: ps (same tag, same time) - _ok(), # web: scale back + scale_back, # web: scale back _ok(), # git restore ] ) - assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == EXIT_FAILED + assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == expected + + +def test_drain_aborts_when_docker_ps_fails(mock_process, monkeypatch, tmp_path, capsys): + """Couldn't list != nothing running: never roll past an unknown drain.""" + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + _ok(), # worker: pull + _err("Cannot connect to the Docker daemon"), # worker: docker ps + _ok(), # git restore + ] + ) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + cmds = _commands(mock_process) + assert not any("--scale web=2" in c for c in cmds) + assert "not draining blind" in capsys.readouterr().out + + +def test_drain_lists_restarting_containers_too(mock_process, monkeypatch, tmp_path): + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [*_git_preflight(), _ok(DRAIN_CONFIG), _ok(), _err("stop here"), _ok()] + ) + deploy(tag="abc123", cmd=COMPOSE_CMD) + ps = next(c for c in _commands(mock_process) if c.startswith("docker ps")) + assert "--filter status=running --filter status=restarting" in ps @pytest.mark.parametrize( diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 7c3c7e0..77880fc 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -414,8 +414,13 @@ def test_untagged_old_image_cannot_be_restored(mock_process, monkeypatch, tmp_pa def test_service_filter_skipping_drain_first_warns(mock_process, monkeypatch, tmp_path, capsys): _chdir(monkeypatch, tmp_path) mock_process.responses.extend([*_git_preflight(), _ok(COMPOSE_CONFIG_YAML), *WEB_ROLL]) + monkeypatch.setenv("GITHUB_ACTIONS", "true") assert deploy(tag="abc123", services_filter=["web"], cmd=COMPOSE_CMD) == 0 - assert "leaves drain-first worker running old code" in capsys.readouterr().err + captured = capsys.readouterr() + assert "warning: --service leaves drain-first worker running old code" in captured.out + # A warning on a deploy that succeeds: no error annotation. + assert "::error::" not in captured.out + assert captured.err == "" def test_start_failure_with_nothing_rolled_restores_old_tag( diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py new file mode 100644 index 0000000..5cef78a --- /dev/null +++ b/tests/test_rolling_parity.py @@ -0,0 +1,102 @@ +"""Rolling deploys behave exactly as on master (0.3.0). + +fixtures/rolling_master.json was recorded by running these scenarios against +master's flow_deploy: every docker/compose command, its env, the exit code, and +whether the lock was left behind. A project that doesn't use drain-first must +see the same commands in the same order. The one intentional difference is +noted in DELIBERATE_CHANGES. +""" + +import json +from pathlib import Path + +import pytest + +from flow_deploy import process +from flow_deploy.deploy import deploy +from tests.test_deploy import _chdir + +MASTER = json.loads((Path(__file__).parent / "fixtures" / "rolling_master.json").read_text()) + +CONFIG = """\ +services: + web: + image: ghcr.io/myorg/myapp:latest + labels: + deploy.role: app + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/health"] + worker: + image: ghcr.io/myorg/myapp:latest + labels: + deploy.role: app + deploy.order: "200" + healthcheck: + test: ["CMD", "celery", "inspect", "ping"] + postgres: + image: postgres:16 + labels: + deploy.role: accessory +""" + + +def _ctr(cid, tag, created): + return json.dumps({"ID": cid, "Image": f"ghcr.io/myorg/myapp:{tag}", "CreatedAt": created}) + + +WEB = _ctr("old_web_111", "old", "2024-01-01") + "\n" + _ctr("new_web_222", "abc123", "2024-01-02") +WRK = _ctr("old_wrk_333", "old", "2024-01-01") + "\n" + _ctr("new_wrk_444", "abc123", "2024-01-02") + + +def ok(out=""): + return process.Result(0, out, "") + + +def err(msg="error"): + return process.Result(1, "", msg) + + +GIT = [ok(""), ok(), ok("prev123\n"), ok()] + + +def roll(ps, health="healthy\n", stop=None): + return [ok(), ok(), ok(ps), ok(health), stop or ok(), ok(), ok()] + + +SCENARIOS = { + "happy": GIT + [ok(CONFIG)] + roll(WEB) + roll(WRK), + "health_abort": GIT + + [ok(CONFIG), ok(), ok(), ok(WEB), ok("unhealthy\n"), ok(), ok(), ok(), ok()], + "pull_fail": GIT + [ok(CONFIG), err("pull"), ok()], + "scale_up_fail": GIT + [ok(CONFIG), ok(), err("port"), ok()], + "count_mismatch": GIT + [ok(CONFIG), ok(), ok(), ok(WEB.split("\n")[0]), ok(), ok()], + "restore_fail": GIT + [ok(CONFIG), err("pull"), err("checkout")], + "cutover_stop_fail": GIT + [ok(CONFIG)] + roll(WEB, stop=err("No such container")) + roll(WRK), + "dirty_tree": [ok(" M file")], + "compose_config_fail": GIT + [err("bad yaml"), ok()], +} + +# Agreed departures from master, by scenario: what changed and why. +DELIBERATE_CHANGES = { + # A failed git restore exits 3 ("needs a person") instead of 1, and the + # lock is released: master's retained lock was broken by the next deploy + # anyway, since acquire() clears locks whose PID has exited. + "restore_fail": {"code": 3, "lock_left": False}, +} + + +@pytest.mark.parametrize("name", sorted(SCENARIOS)) +def test_rolling_deploy_matches_master(name, mock_process, monkeypatch, tmp_path): + assert set(SCENARIOS) == set(MASTER), "scenarios and fixture out of sync" + _chdir(monkeypatch, tmp_path) + monkeypatch.setattr("flow_deploy.deploy.time.sleep", lambda _s: None) + mock_process.responses.extend(SCENARIOS[name]) + + code = deploy(tag="abc123", cmd=["docker", "compose"]) + + calls = [[args, env] for _, args, env, _ in mock_process.calls] + assert calls == MASTER[name]["calls"], f"{name}: docker/compose commands differ from master" + expected = {"code": MASTER[name]["code"], "lock_left": MASTER[name]["lock_left"]} + expected.update(DELIBERATE_CHANGES.get(name, {})) + assert code == expected["code"] + assert (tmp_path / ".git" / "deploy-lock").exists() == expected["lock_left"] From 586027e840102855a7e9485b08dae64c0f42a876 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sat, 10 Oct 2026 11:58:00 -0600 Subject: [PATCH 09/19] Check phase-3 container listing; widen the master parity recording From the confirmation review: - _start_service lists containers with the failure-aware helper (running and restarting). If docker ps fails after compose up, it can't see or remove what started, so it reports SVC_DIRTY (exit 3) instead of treating "couldn't list" as "nothing to clean up" and restoring old workers beside new ones. - The parity scenarios move to tests/rolling_scenarios.py, shared by the test and a recorder that runs them against a master checkout. fixtures/rolling_master.json is re-recorded from master 0.3.0 with 15 scenarios, adding: second-service health abort, unidentifiable containers, same-tag redeploy, healthcheck.skip, --service, and deploy without --tag. All match master. - The signal change for rolling-only projects (restore git, then exit 1) is now documented as deliberate and pinned by a rolling-only test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 15 +- src/flow_deploy/deploy.py | 10 +- tests/fixtures/rolling_master.json | 1091 ++++++++++++++++++++++++++++ tests/rolling_scenarios.py | 157 ++++ tests/test_deploy_failures.py | 35 + tests/test_rolling_parity.py | 100 +-- 6 files changed, 1327 insertions(+), 81 deletions(-) create mode 100644 tests/rolling_scenarios.py diff --git a/README.md b/README.md index 9f667e8..93fb065 100644 --- a/README.md +++ b/README.md @@ -154,10 +154,17 @@ only when something couldn't be put back: Even then the lock is released. Exit `3` is the signal that someone needs to look. -Rolling deploys otherwise behave exactly as before; `tests/test_rolling_parity.py` -replays them against a recording of the previous release. As before, a -successful cutover whose old-container cleanup fails still succeeds, with a -warning: the new container is healthy and serving. +Rolling deploys otherwise behave exactly as before. `tests/test_rolling_parity.py` +replays 15 rolling scenarios against a recording of the previous release: every +command, its environment, the exit code, and the lock. As before, a successful +cutover whose old-container cleanup fails still succeeds, with a warning: the +new container is healthy and serving. + +The two deliberate changes for rolling-only projects: + +- A failed git restore exits `3` and releases the lock. +- A signal restores the repo before exiting `1`. Previously it released the + lock and exited without restoring. Deploying rolling services with `--service` while leaving drain-first services out prints a warning, since those keep running old code. diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index fa2ef57..4547d94 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -398,7 +398,15 @@ def fail(msg: str, ctrs: list[dict]) -> int: env=env, cmd=compose_cmd, ) - ctrs = containers.get_containers_for_service(svc.name, project=project) + # Restarting containers count too, so a crash-looping one gets removed. + ctrs = containers.list_containers_for_service( + svc.name, project=project, statuses=("running", "restarting") + ) + if ctrs is None: + # Can't see what started, so can't remove it: not a clean failure. + log.failure(f"could not list {svc.name} containers after starting them") + log.service_end() + return SVC_DIRTY if result.returncode != 0 or len(ctrs) != replicas: detail = result.stderr.strip() or f"{len(ctrs)} of {replicas} containers running" return fail(f"start failed: {detail}", ctrs) diff --git a/tests/fixtures/rolling_master.json b/tests/fixtures/rolling_master.json index c3e52b1..40ef70b 100644 --- a/tests/fixtures/rolling_master.json +++ b/tests/fixtures/rolling_master.json @@ -351,6 +351,228 @@ ], "lock_left": false }, + "second_service_health_abort": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "rm", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "rm", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": false + }, "pull_fail": { "code": 1, "calls": [ @@ -612,6 +834,875 @@ ], "lock_left": false }, + "unidentifiable": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123" + ], + null + ] + ], + "lock_left": false + }, + "same_tag_redeploy": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "rm", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "rm", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ] + ], + "lock_left": false + }, + "healthcheck_skip": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "rm", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "rm", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ] + ], + "lock_left": false + }, + "service_filter": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "abc123" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "rm", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "abc123" + } + ] + ], + "lock_left": false + }, + "no_tag_current_head": { + "code": 0, + "calls": [ + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "head456" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "head456" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_web_222" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "rm", + "old_web_111" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "head456" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "head456" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "head456" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "new_wrk_444" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "rm", + "old_wrk_333" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "head456" + } + ] + ], + "lock_left": false + }, "restore_fail": { "code": 1, "calls": [ diff --git a/tests/rolling_scenarios.py b/tests/rolling_scenarios.py new file mode 100644 index 0000000..079be0f --- /dev/null +++ b/tests/rolling_scenarios.py @@ -0,0 +1,157 @@ +"""Rolling-only deploy scenarios, shared by the parity test and its recorder. + +Responses are plain (returncode, stdout, stderr) tuples so the recorder can run +them against another checkout's flow_deploy (master) without importing this +branch's code. To re-record fixtures/rolling_master.json from a master +checkout: + + git worktree add /tmp/deploy-master master + poetry run python tests/rolling_scenarios.py /tmp/deploy-master \ + > tests/fixtures/rolling_master.json +""" + +import json + +CONFIG = """\ +services: + web: + image: ghcr.io/myorg/myapp:latest + labels: + deploy.role: app + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:8000/health"] + worker: + image: ghcr.io/myorg/myapp:latest + labels: + deploy.role: app + deploy.order: "200" + healthcheck: + test: ["CMD", "celery", "inspect", "ping"] + postgres: + image: postgres:16 + labels: + deploy.role: accessory +""" + +SKIP_CONFIG = CONFIG.replace( + ' deploy.order: "200"\n', + ' deploy.order: "200"\n deploy.healthcheck.skip: "true"\n', +) + + +def _ctr(cid, tag, created): + return json.dumps({"ID": cid, "Image": f"ghcr.io/myorg/myapp:{tag}", "CreatedAt": created}) + + +WEB = _ctr("old_web_111", "old", "2024-01-01") + "\n" + _ctr("new_web_222", "abc123", "2024-01-02") +WRK = _ctr("old_wrk_333", "old", "2024-01-01") + "\n" + _ctr("new_wrk_444", "abc123", "2024-01-02") +# Same tag on both: old/new told apart by CreatedAt. +WEB_SAME_TAG = ( + _ctr("old_web_111", "abc123", "2024-01-01") + "\n" + _ctr("new_web_222", "abc123", "2024-01-02") +) +# Same tag and same CreatedAt: can't tell them apart. +WEB_TWINS = _ctr("a1", "abc123", "2024-01-01") + "\n" + _ctr("b2", "abc123", "2024-01-01") + + +def ok(out=""): + return (0, out, "") + + +def err(msg="error"): + return (1, "", msg) + + +GIT = [ok(""), ok(), ok("prev123\n"), ok()] +GIT_NO_TAG = [ok("head456\n"), ok(""), ok(), ok("head456\n")] # rev-parse, status, fetch, rev-parse + + +def roll(ps, health="healthy\n", stop=None): + return [ok(), ok(), ok(ps), ok(health), stop or ok(), ok(), ok()] + + +def roll_skip(ps): + return [ok(), ok(), ok(ps), ok(), ok(), ok()] + + +# name -> (responses, deploy kwargs) +SCENARIOS = { + "happy": (GIT + [ok(CONFIG)] + roll(WEB) + roll(WRK), {}), + "health_abort": ( + GIT + [ok(CONFIG), ok(), ok(), ok(WEB), ok("unhealthy\n"), ok(), ok(), ok(), ok()], + {}, + ), + "second_service_health_abort": ( + GIT + + [ok(CONFIG)] + + roll(WEB) + + [ok(), ok(), ok(WRK), ok("unhealthy\n")] + + [ok(), ok(), ok(), ok()], + {}, + ), + "pull_fail": (GIT + [ok(CONFIG), err("pull"), ok()], {}), + "scale_up_fail": (GIT + [ok(CONFIG), ok(), err("port"), ok()], {}), + "count_mismatch": ( + GIT + [ok(CONFIG), ok(), ok(), ok(WEB.split("\n")[0]), ok(), ok()], + {}, + ), + "unidentifiable": (GIT + [ok(CONFIG), ok(), ok(), ok(WEB_TWINS), ok(), ok()], {}), + "same_tag_redeploy": (GIT + [ok(CONFIG)] + roll(WEB_SAME_TAG) + roll(WRK), {}), + "healthcheck_skip": (GIT + [ok(SKIP_CONFIG)] + roll(WEB) + roll_skip(WRK), {}), + "service_filter": (GIT + [ok(CONFIG)] + roll(WRK), {"services_filter": ["worker"]}), + "no_tag_current_head": (GIT_NO_TAG + [ok(CONFIG)] + roll(WEB) + roll(WRK), {"tag": None}), + "restore_fail": (GIT + [ok(CONFIG), err("pull"), err("checkout")], {}), + "cutover_stop_fail": ( + GIT + [ok(CONFIG)] + roll(WEB, stop=err("No such container")) + roll(WRK), + {}, + ), + "dirty_tree": ([ok(" M file")], {}), + "compose_config_fail": (GIT + [err("bad yaml"), ok()], {}), +} + + +def record(deploy_module, process_module, name, workdir): + """Run one scenario against the given flow_deploy modules; return the observation.""" + import os + + responses, kwargs = SCENARIOS[name] + queue = [process_module.Result(*r) for r in responses] + calls = [] + + def fake_run(args, env=None, cwd=None): + calls.append([args, env]) + return queue.pop(0) if queue else process_module.Result(0, "", "") + + process_module.run = fake_run + process_module.run_streaming = lambda *a, **k: 0 + deploy_module.time.sleep = lambda _s: None + os.makedirs(os.path.join(workdir, ".git"), exist_ok=True) + os.chdir(workdir) + kwargs = {"tag": "abc123", **kwargs} + code = deploy_module.deploy(cmd=["docker", "compose"], **kwargs) + return { + "code": code, + "calls": calls, + "lock_left": os.path.exists(".git/deploy-lock"), + } + + +if __name__ == "__main__": + import os + import sys + import tempfile + + sys.path.insert(0, os.path.join(sys.argv[1], "src")) + from flow_deploy import deploy as deploy_mod + from flow_deploy import process + + results = {} + devnull = open(os.devnull, "w") + for name in SCENARIOS: + out, errs = sys.stdout, sys.stderr + sys.stdout = sys.stderr = devnull + try: + with tempfile.TemporaryDirectory() as d: + results[name] = record(deploy_mod, process, name, d) + finally: + sys.stdout, sys.stderr = out, errs + print(json.dumps(results, indent=1)) diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py index 98f40a3..d45828e 100644 --- a/tests/test_deploy_failures.py +++ b/tests/test_deploy_failures.py @@ -335,6 +335,41 @@ def test_rolling_unidentifiable_containers_scale_back( assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == expected +def test_start_cannot_list_containers_is_degraded(mock_process, monkeypatch, tmp_path): + """Couldn't see what started, so couldn't remove it: exit 3, not a clean revert.""" + _chdir(monkeypatch, tmp_path) + mock_process.responses.extend( + [ + *_git_preflight(), + _ok(DRAIN_CONFIG), + *WORKER_DRAIN, + _ok(), # worker: compose up + _err("Cannot connect to the Docker daemon"), # worker: docker ps + _ok(), # git restore + _ok(), # worker: restore + ] + ) + result = deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) + assert result == EXIT_DEGRADED + start_ps = [c for c in _commands(mock_process) if c.startswith("docker ps")][-1] + assert "--filter status=running --filter status=restarting" in start_ps + + +def test_signal_during_rolling_only_deploy_restores_git(mock_process, monkeypatch, tmp_path): + """Deliberate change from master (which released the lock and exited 1 + without restoring): a signal now also puts the repo back.""" + _chdir(monkeypatch, tmp_path) + + def cancelled(*args, **kwargs): + signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) + + monkeypatch.setattr(deploy_mod, "_deploy_service", cancelled) + mock_process.responses.extend([*_git_preflight(), _ok(COMPOSE_CONFIG_YAML), _ok()]) + assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert _commands(mock_process)[-1] == "git checkout --detach prev123abc" + assert _lock_released(tmp_path) + + def test_drain_aborts_when_docker_ps_fails(mock_process, monkeypatch, tmp_path, capsys): """Couldn't list != nothing running: never roll past an unknown drain.""" _chdir(monkeypatch, tmp_path) diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py index 5cef78a..497cdc4 100644 --- a/tests/test_rolling_parity.py +++ b/tests/test_rolling_parity.py @@ -1,10 +1,12 @@ """Rolling deploys behave exactly as on master (0.3.0). -fixtures/rolling_master.json was recorded by running these scenarios against -master's flow_deploy: every docker/compose command, its env, the exit code, and -whether the lock was left behind. A project that doesn't use drain-first must -see the same commands in the same order. The one intentional difference is -noted in DELIBERATE_CHANGES. +fixtures/rolling_master.json was recorded by running tests/rolling_scenarios.py +against master's flow_deploy: every docker/compose/git command, its env, the +exit code, and whether the lock was left behind. A project that doesn't use +drain-first must see the same commands in the same order. Agreed departures +are listed in DELIBERATE_CHANGES; signals are covered separately in +test_deploy_failures.py (master exited without restoring git; this branch +restores it). """ import json @@ -12,71 +14,13 @@ import pytest +from flow_deploy import deploy as deploy_mod from flow_deploy import process -from flow_deploy.deploy import deploy -from tests.test_deploy import _chdir +from tests.rolling_scenarios import SCENARIOS, record MASTER = json.loads((Path(__file__).parent / "fixtures" / "rolling_master.json").read_text()) -CONFIG = """\ -services: - web: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/health"] - worker: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - deploy.order: "200" - healthcheck: - test: ["CMD", "celery", "inspect", "ping"] - postgres: - image: postgres:16 - labels: - deploy.role: accessory -""" - - -def _ctr(cid, tag, created): - return json.dumps({"ID": cid, "Image": f"ghcr.io/myorg/myapp:{tag}", "CreatedAt": created}) - - -WEB = _ctr("old_web_111", "old", "2024-01-01") + "\n" + _ctr("new_web_222", "abc123", "2024-01-02") -WRK = _ctr("old_wrk_333", "old", "2024-01-01") + "\n" + _ctr("new_wrk_444", "abc123", "2024-01-02") - - -def ok(out=""): - return process.Result(0, out, "") - - -def err(msg="error"): - return process.Result(1, "", msg) - - -GIT = [ok(""), ok(), ok("prev123\n"), ok()] - - -def roll(ps, health="healthy\n", stop=None): - return [ok(), ok(), ok(ps), ok(health), stop or ok(), ok(), ok()] - - -SCENARIOS = { - "happy": GIT + [ok(CONFIG)] + roll(WEB) + roll(WRK), - "health_abort": GIT - + [ok(CONFIG), ok(), ok(), ok(WEB), ok("unhealthy\n"), ok(), ok(), ok(), ok()], - "pull_fail": GIT + [ok(CONFIG), err("pull"), ok()], - "scale_up_fail": GIT + [ok(CONFIG), ok(), err("port"), ok()], - "count_mismatch": GIT + [ok(CONFIG), ok(), ok(), ok(WEB.split("\n")[0]), ok(), ok()], - "restore_fail": GIT + [ok(CONFIG), err("pull"), err("checkout")], - "cutover_stop_fail": GIT + [ok(CONFIG)] + roll(WEB, stop=err("No such container")) + roll(WRK), - "dirty_tree": [ok(" M file")], - "compose_config_fail": GIT + [err("bad yaml"), ok()], -} - -# Agreed departures from master, by scenario: what changed and why. +# Agreed departures from master, by scenario. DELIBERATE_CHANGES = { # A failed git restore exits 3 ("needs a person") instead of 1, and the # lock is released: master's retained lock was broken by the next deploy @@ -85,18 +29,22 @@ def roll(ps, health="healthy\n", stop=None): } +def test_scenarios_and_fixture_agree(): + assert set(SCENARIOS) == set(MASTER) + + @pytest.mark.parametrize("name", sorted(SCENARIOS)) -def test_rolling_deploy_matches_master(name, mock_process, monkeypatch, tmp_path): - assert set(SCENARIOS) == set(MASTER), "scenarios and fixture out of sync" - _chdir(monkeypatch, tmp_path) - monkeypatch.setattr("flow_deploy.deploy.time.sleep", lambda _s: None) - mock_process.responses.extend(SCENARIOS[name]) +def test_rolling_deploy_matches_master(name, monkeypatch, tmp_path, capsys): + # record() swaps process.run itself; restore it after the test. + monkeypatch.setattr(process, "run", process.run) + monkeypatch.setattr(process, "run_streaming", process.run_streaming) + monkeypatch.setattr(deploy_mod.time, "sleep", deploy_mod.time.sleep) + monkeypatch.chdir(tmp_path) - code = deploy(tag="abc123", cmd=["docker", "compose"]) + observed = record(deploy_mod, process, name, str(tmp_path)) - calls = [[args, env] for _, args, env, _ in mock_process.calls] - assert calls == MASTER[name]["calls"], f"{name}: docker/compose commands differ from master" + assert observed["calls"] == MASTER[name]["calls"], f"{name}: commands differ from master" expected = {"code": MASTER[name]["code"], "lock_left": MASTER[name]["lock_left"]} expected.update(DELIBERATE_CHANGES.get(name, {})) - assert code == expected["code"] - assert (tmp_path / ".git" / "deploy-lock").exists() == expected["lock_left"] + assert observed["code"] == expected["code"] + assert observed["lock_left"] == expected["lock_left"] From afa4ebbc3cb39309edc6f3b45b0d8cde16b644f1 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sat, 10 Oct 2026 21:13:32 -0600 Subject: [PATCH 10/19] Add a real-Docker integration suite; fix two bugs it found tests/integration runs flow-deploy as a subprocess against real containers: a local registry:2, an env-driven stub service image, and a throwaway git repo + bare origin + compose project per test. A new `integration` CI job runs it; the unit job deselects it (-m 'not integration'), so the 100% coverage gate is unchanged. Scenarios: happy path (replica counts, drain/roll/start order); first deploy of a new drain-first service; failed healthcheck on the rolling service, on a rolling-only project, and on a drain-first service in phase 3; bad tag failing at pull with nothing stopped; a drain that hits its timeout and is SIGKILLed; SIGINT, SIGTERM, and a process-group SIGINT mid-drain; lock contention (exit 2); an untagged old image (exit 3); a crash-looping worker; a healthcheck that passes late. Bugs found and fixed: - A signal mid-drain left the drain-first service down while exiting 1 as "fully reverted": interrupting the docker CLI doesn't interrupt the daemon's stop, so the restore saw the container still running, left it, and it exited afterwards. Signals are now held until that container has stopped and been removed (_signals_deferred), and the drain's docker stop runs in its own session so a terminal's process-group Ctrl-C can't cut it short either. - On master, a failed rolling healthcheck's scale-back ran `compose up --scale svc=1` with the new tag, recreating the surviving OLD container on the NEW failing image. Scale-back now passes --no-recreate; the parity test records it as the one deliberate command change. CI cancel: tests/integration/test_ci_cancel.py runs a stand-in for flow-deploy over real ssh to an sshd container and kills the client. Without a pty (how deploy-action runs it) the remote process gets no signal and runs to completion; with -tt it gets SIGHUP. README, SPEC, and code comments now say a cancelled CI job does not revert a remote deploy. SPEC section 5 no longer claims the lock is retained. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- .github/workflows/ci.yml | 20 ++ README.md | 24 +- SPEC.md | 5 +- pyproject.toml | 4 +- src/flow_deploy/containers.py | 11 +- src/flow_deploy/deploy.py | 61 ++++- src/flow_deploy/process.py | 15 +- tests/conftest.py | 11 +- tests/integration/conftest.py | 328 +++++++++++++++++++++++ tests/integration/images/sshd/Dockerfile | 13 + tests/integration/images/sshd/probe.py | 40 +++ tests/integration/images/stub/Dockerfile | 6 + tests/integration/images/stub/stub.sh | 39 +++ tests/integration/test_ci_cancel.py | 116 ++++++++ tests/integration/test_deploys.py | 226 ++++++++++++++++ tests/rolling_scenarios.py | 2 +- tests/test_containers.py | 6 + tests/test_deploy_failures.py | 2 +- tests/test_drain_first.py | 2 + tests/test_process.py | 8 + tests/test_rolling_parity.py | 19 +- 21 files changed, 933 insertions(+), 25 deletions(-) create mode 100644 tests/integration/conftest.py create mode 100644 tests/integration/images/sshd/Dockerfile create mode 100644 tests/integration/images/sshd/probe.py create mode 100644 tests/integration/images/stub/Dockerfile create mode 100644 tests/integration/images/stub/stub.sh create mode 100644 tests/integration/test_ci_cancel.py create mode 100644 tests/integration/test_deploys.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98bf26b..eb5cc12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,3 +39,23 @@ jobs: - name: Test run: poetry run pytest --cov=flow_deploy --cov-report=term-missing + + # Real containers: a local registry, stub services, and an sshd, driven by + # flow-deploy as a subprocess. Kept out of the unit job's coverage gate. + integration: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install dependencies + run: | + pip install poetry + poetry install --with test + + - name: Integration tests + run: poetry run pytest -m integration --no-cov -p no:randomly diff --git a/README.md b/README.md index 93fb065..d5502cf 100644 --- a/README.md +++ b/README.md @@ -137,10 +137,26 @@ with the previous tag in `DEPLOY_TAG`. A service whose image ignores it comes back on whatever the compose file names. A signal reverts the same way, and so does an unexpected error. The signals are -SIGTERM, Ctrl-C (SIGINT), and SIGHUP. SIGHUP is what a remote deploy receives -when the CI job driving it over ssh is cancelled. Further signals are ignored -until the revert finishes, and logging keeps going even if the session's output -has gone away. Drain-first services already healthy on the new tag stay. +SIGTERM (a timeout or shutdown), Ctrl-C (SIGINT), and SIGHUP (a hung-up +terminal). Further signals are ignored until the revert finishes. + +A signal that arrives while a drain-first container is stopping is held until +that container has stopped and been removed, and the deploy then reverts. The +docker CLI being interrupted doesn't interrupt the daemon's stop, so reverting +immediately would find the container still "running" and leave it be, only to +see it exit afterwards. Holding the signal costs at most the rest of that +container's drain. + +Drain-first services already healthy on the new tag stay. + +**A cancelled CI job does not revert a remote deploy.** `deploy-action` runs +`ssh host "cd dir && flow-deploy deploy --tag X"` with no pty. Without a pty, +sshd sends the remote process no signal when the client disconnects. +`tests/integration/test_ci_cancel.py` checks this against a real sshd. The +deploy runs to completion, or reverts on its own failure, exactly as if the job +were still watching. Its output to the closed session is discarded rather than +crashing it. Check the host afterwards (`flow-deploy status`) to see how it +ended. The deploy exits `1` when it failed and everything was put back. It exits `3` only when something couldn't be put back: diff --git a/SPEC.md b/SPEC.md index 22842cb..61f3282 100644 --- a/SPEC.md +++ b/SPEC.md @@ -359,8 +359,7 @@ This detects the system's libc (musl or glibc), downloads the latest binary from Only one deploy may run at a time per project directory. The tool uses a lock file (`.git/deploy-lock`) containing the PID and timestamp of the running deploy. The lock is stored inside `.git/` to avoid dirtying the working tree. The lock is: - Acquired before any mutations (git checkout, container changes) -- Released on completion (success or failure) -- **Retained** if git restore fails after a failed deploy — prevents further deploys until manual intervention (the error message includes the fix: `git checkout --detach && rm .git/deploy-lock`) +- Released on completion: success, failure, a handled signal (SIGTERM, SIGINT, SIGHUP), or an unexpected error. That includes a deploy that couldn't be fully reverted, which exits `3` to say someone needs to look. A retained lock would not have stopped the next deploy anyway: see the next point. - Automatically broken if the holding PID is no longer running (stale lock recovery) - Reported with a clear message if held by another process (exit code 2) @@ -442,6 +441,8 @@ For multi-host deploys or when you want host discovery from compose labels, use 5. SSHes to each host: `flow-deploy deploy --tag ` 6. Streams logs back to GitHub Actions +**Cancelling the workflow does not cancel the remote deploy.** The action runs ssh without a pty, so sshd sends the remote `flow-deploy` no signal when the connection drops; `tests/integration/test_ci_cancel.py` verifies this against a real sshd. The deploy runs to completion, or reverts on its own failure, and its output to the closed session is discarded. Running ssh with `-tt` would deliver SIGHUP and make a cancel revert, but every dropped connection would then revert a deploy too. + ```yaml name: Deploy diff --git a/pyproject.toml b/pyproject.toml index ecd2c35..8af04c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,9 @@ line_length = 100 [tool.pytest.ini_options] testpaths = ["tests"] -addopts = "-v --tb=short --cov=flow_deploy --cov-report=term-missing" +# Integration tests (real Docker) run separately: pytest -m integration --no-cov +addopts = "-v --tb=short --cov=flow_deploy --cov-report=term-missing -m 'not integration'" +markers = ["integration: needs a real Docker daemon (tests/integration)"] [tool.coverage.run] source = ["flow_deploy"] diff --git a/src/flow_deploy/containers.py b/src/flow_deploy/containers.py index ee2bd67..61b2713 100644 --- a/src/flow_deploy/containers.py +++ b/src/flow_deploy/containers.py @@ -84,9 +84,14 @@ def get_container_health(container_id: str) -> str | None: return status if status else None -def stop_container(container_id: str, timeout: int = 30) -> bool: - """Stop a container with given timeout. Returns True on success.""" - result = process.run(["docker", "stop", "--time", str(timeout), container_id]) +def stop_container(container_id: str, timeout: int = 30, isolate: bool = False) -> bool: + """Stop a container with given timeout. Returns True on success. + + ``isolate`` runs docker stop in its own session so a terminal signal + can't cut it short (the daemon would carry on stopping regardless). + """ + args = ["docker", "stop", "--time", str(timeout), container_id] + result = process.run(args, new_session=True) if isolate else process.run(args) return result.returncode == 0 diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 4547d94..db04b05 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -2,6 +2,7 @@ import signal import time +from contextlib import contextmanager from dataclasses import dataclass, field from flow_deploy import compose, config, containers, git, lock, log @@ -11,8 +12,10 @@ EXIT_LOCKED = 2 EXIT_DEGRADED = 3 # failed, and something couldn't be put back -# Signals that revert the deploy. SIGHUP is what a remote deploy gets when its -# ssh session dies, e.g. when the CI job driving it is cancelled. +# Signals that revert the deploy: a timeout or shutdown (SIGTERM), Ctrl-C, and +# a hung-up terminal (SIGHUP). A cancelled CI job running `ssh host +# flow-deploy ...` without a pty sends none of them: the remote deploy runs on +# (tests/integration/test_ci_cancel.py). HANDLED_SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP) # Per-service outcomes from _deploy_service and _start_service. @@ -32,6 +35,32 @@ def __init__(self, signum: int): self.signum = signum +@contextmanager +def _signals_deferred(why: str): + """Hold handled signals until the block finishes, then act on the first one. + + The deploy's own handlers are swapped for one that only records; on exit + they're put back and, if a signal arrived, Interrupted is raised then. + """ + pending = [] + + def hold(signum, frame): + if not pending: + log.step(f"received signal {signum}; {why}, then reverting") + pending.append(signum) + + previous = {signum: signal.getsignal(signum) for signum in HANDLED_SIGNALS} + for signum in HANDLED_SIGNALS: + signal.signal(signum, hold) + try: + yield + finally: + for signum, handler in previous.items(): + signal.signal(signum, handler) + if pending: + raise Interrupted(pending[0]) + + @dataclass class Drained: """What a drain-first service was running before its drain.""" @@ -103,8 +132,8 @@ def deploy( _dry_run(tag, app_services) return EXIT_OK - # A signal (a cancelled CI job, Ctrl-C, a dropped ssh session) reverts - # like any other failure. Handlers go in before the lock is taken, so no + # A signal (Ctrl-C, a timeout, a hung-up terminal) reverts like any other + # failure. Handlers go in before the lock is taken, so no # signal can land between the two and skip cleanup. originals = {signum: signal.getsignal(signum) for signum in HANDLED_SIGNALS} @@ -354,11 +383,21 @@ def _drain_service( for ctr in ctrs: ctr_id = ctr["ID"] log.step(f"draining {ctr_id[:7]} ({svc.drain}s timeout)...") - if not containers.stop_container(ctr_id, timeout=svc.drain): + # Finish this container's stop before acting on a signal. Interrupting + # the docker CLI doesn't interrupt the daemon's stop, so a revert + # would find the container still "running", leave it be, and then + # watch it exit. Once it's stopped and removed, the revert recreates + # it cleanly. + # The docker stop runs in its own session, so a terminal Ctrl-C (sent + # to the whole foreground group) can't cut it short either. + with _signals_deferred(f"finishing the drain of {ctr_id[:7]} first"): + stopped = containers.stop_container(ctr_id, timeout=svc.drain, isolate=True) + removed = stopped and containers.remove_container(ctr_id) + if not stopped: log.failure(f"could not stop {ctr_id[:7]}; it may still be running") log.service_end() return 1 - if not containers.remove_container(ctr_id): + if not removed: log.failure(f"could not remove {ctr_id[:7]}") log.service_end() return 1 @@ -575,9 +614,15 @@ def _wait_for_healthy(container_id: str, timeout: int, poll_interval: int) -> bo def _scale_back(service_name: str, env: dict, compose_cmd: list[str]) -> bool: - """Scale service back to 1. Returns False if compose failed.""" + """Scale service back to 1. Returns False if compose failed. + + --no-recreate: scale back only ever removes extras. Without it, compose + "fixes" the surviving container to match ``env``'s DEPLOY_TAG, so after a + failed health check the old, healthy container was recreated on the new, + failing image (master did this; found by the integration suite). + """ result = compose.compose_run( - ["up", "-d", "--no-deps", "--scale", f"{service_name}=1", service_name], + ["up", "-d", "--no-deps", "--no-recreate", "--scale", f"{service_name}=1", service_name], env=env, cmd=compose_cmd, ) diff --git a/src/flow_deploy/process.py b/src/flow_deploy/process.py index 97134ec..a466e3c 100644 --- a/src/flow_deploy/process.py +++ b/src/flow_deploy/process.py @@ -11,8 +11,18 @@ class Result: stderr: str -def run(args: list[str], env: dict[str, str] | None = None, cwd: str | None = None) -> Result: - """Run a command and capture output. Raises on non-zero exit.""" +def run( + args: list[str], + env: dict[str, str] | None = None, + cwd: str | None = None, + new_session: bool = False, +) -> Result: + """Run a command and capture output. Raises on non-zero exit. + + ``new_session`` starts the command in its own session, out of this + process's group, so a terminal's Ctrl-C (sent to the whole foreground + group) reaches only flow-deploy and not the command. + """ merged_env = None if env is not None: import os @@ -25,6 +35,7 @@ def run(args: list[str], env: dict[str, str] | None = None, cwd: str | None = No text=True, env=merged_env, cwd=cwd, + start_new_session=new_session, ) return Result(returncode=proc.returncode, stdout=proc.stdout, stderr=proc.stderr) diff --git a/tests/conftest.py b/tests/conftest.py index 6af7703..0fdbfd0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,9 +10,12 @@ def mock_process(monkeypatch): calls = [] responses = [] + new_sessions = [] # commands run in their own session (process.run new_session=True) - def fake_run(args, env=None, cwd=None): + def fake_run(args, env=None, cwd=None, new_session=False): calls.append(("run", args, env, cwd)) + if new_session: + new_sessions.append(args) if responses: return responses.pop(0) return process.Result(returncode=0, stdout="", stderr="") @@ -24,4 +27,8 @@ def fake_run_streaming(args, env=None, cwd=None): monkeypatch.setattr(process, "run", fake_run) monkeypatch.setattr(process, "run_streaming", fake_run_streaming) - return type("MockProcess", (), {"calls": calls, "responses": responses})() + return type( + "MockProcess", + (), + {"calls": calls, "responses": responses, "new_sessions": new_sessions}, + )() diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 0000000..1e829e5 --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,328 @@ +"""Real-container integration harness for flow-deploy. + +Each test gets a Stack: a throwaway git repo (with a bare origin, since +flow-deploy fetches) holding one tagged commit per compose variant, and a +compose project of stub services pulled from a local registry. flow-deploy +runs as a real subprocess, so tests can signal it, against real Docker. + +Run with: poetry run pytest -m integration --no-cov +Skipped automatically when Docker isn't available. +""" + +import json +import os +import shutil +import signal +import subprocess +import sys +import threading +import time +import uuid +from pathlib import Path + +import pytest +import yaml + +IMAGES = Path(__file__).parent / "images" +SRC = Path(__file__).resolve().parents[2] / "src" +STUB_TAGS = { + "v1": {"STUB_VERSION": "v1"}, + "v2": {"STUB_VERSION": "v2"}, + "v3": {"STUB_VERSION": "v3"}, + "unhealthy": {"STUB_VERSION": "unhealthy", "STUB_HEALTH": "fail"}, +} + + +def pytest_collection_modifyitems(config, items): + for item in items: + if Path(str(item.fspath)).is_relative_to(Path(__file__).parent): + item.add_marker(pytest.mark.integration) + + +def run(args, **kwargs): + kwargs.setdefault("check", True) + kwargs.setdefault("capture_output", True) + kwargs.setdefault("text", True) + return subprocess.run(args, **kwargs) + + +@pytest.fixture(scope="session") +def docker(): + if shutil.which("docker") is None or run(["docker", "info"], check=False).returncode: + pytest.skip("Docker is not available") + up_help = run(["docker", "compose", "up", "--help"], check=False).stdout + if "--wait" not in up_help: + pytest.skip("Docker Compose is too old: `docker compose up --wait` is required") + + +@pytest.fixture(scope="session") +def registry(docker): + """A local registry:2 with the stub image pushed under each STUB_TAGS tag.""" + name = f"flowdeploy-it-registry-{uuid.uuid4().hex[:8]}" + run(["docker", "run", "-d", "--name", name, "-p", "127.0.0.1::5000", "registry:2"]) + try: + port = run(["docker", "port", name, "5000"]).stdout.strip().split(":")[-1] + host = f"localhost:{port}" + for _ in range(50): + if run(["curl", "-sf", f"http://{host}/v2/"], check=False).returncode == 0: + break + time.sleep(0.2) + for tag, args in STUB_TAGS.items(): + image = f"{host}/stub:{tag}" + build_args = [a for k, v in args.items() for a in ("--build-arg", f"{k}={v}")] + run(["docker", "build", "-q", "-t", image, *build_args, str(IMAGES / "stub")]) + run(["docker", "push", "-q", image]) + yield host + finally: + run(["docker", "rm", "-f", name], check=False) + + +def service( + order, strategy="rolling", drain=10, env=None, health_timeout=30, image=None, start_period=None +): + """One compose service of the stub image, labelled for flow-deploy.""" + labels = { + "deploy.role": "app", + "deploy.order": str(order), + "deploy.drain": str(drain), + "deploy.healthcheck.timeout": str(health_timeout), + "deploy.healthcheck.poll": "1", + } + if strategy != "rolling": + labels["deploy.strategy"] = strategy + healthcheck = { + "test": ["CMD", "test", "-f", "/tmp/healthy"], + "interval": "1s", + "timeout": "2s", + "retries": 2, + } + if start_period: + healthcheck["start_period"] = start_period + return { + "image": image or "${REGISTRY}/stub:${DEPLOY_TAG}", + "environment": dict(env or {}), + "labels": labels, + "healthcheck": healthcheck, + } + + +def standard(**overrides): + """web (rolling), scheduler and worker (drain-first), with per-service overrides. + + Pass ``scheduler=None`` to leave a service out. + """ + services = { + "web": service(100), + "scheduler": service(200, "drain-first"), + "worker": service(300, "drain-first"), + } + for name, value in overrides.items(): + if value is None: + services.pop(name, None) + else: + services[name] = value + return {"services": services} + + +class Stack: + """A git repo + compose project that flow-deploy deploys.""" + + def __init__(self, root: Path, registry: str): + self.registry = registry + self.project = f"fdit{uuid.uuid4().hex[:10]}" + self.origin = root / "origin.git" + self.repo = root / "repo" + run(["git", "init", "-q", "--bare", str(self.origin)]) + run(["git", "init", "-q", "-b", "main", str(self.repo)]) + self.git("config", "user.email", "it@example.com") + self.git("config", "user.name", "it") + self.git("config", "commit.gpgsign", "false") + self.git("remote", "add", "origin", str(self.origin)) + # Never lose a scaled-up compose project if a test fails. + self._up = False + + def env(self, tag=None, extra=None): + env = { + **(extra or {}), + **os.environ, + "COMPOSE_PROJECT_NAME": self.project, + "REGISTRY": self.registry, + "PYTHONUNBUFFERED": "1", + "PYTHONPATH": str(SRC), + } + env.pop("GITHUB_ACTIONS", None) # plain log output for assertions + if tag: + env["DEPLOY_TAG"] = tag + return env + + def git(self, *args): + return run(["git", "-C", str(self.repo), *args]).stdout.strip() + + def commit(self, tag, compose): + """Commit ``compose`` as docker-compose.yml and tag it ``tag``.""" + (self.repo / "docker-compose.yml").write_text(yaml.safe_dump(compose, sort_keys=False)) + self.git("add", "docker-compose.yml") + self.git("commit", "-q", "--allow-empty", "-m", tag) + self.git("tag", tag) + self.git("push", "-q", "origin", "HEAD:refs/heads/main", "--tags") + return self.git("rev-parse", "HEAD") + + def compose(self, *args, tag=None, check=True, extra=None): + return run( + ["docker", "compose", *args], cwd=self.repo, env=self.env(tag, extra), check=check + ) + + def up(self, tag, scale=None, wait=True, extra=None): + """Bring the stack up at ``tag``, as a running production host would be.""" + self.git("checkout", "-q", "--detach", tag) + scale_args = [a for name, n in (scale or {}).items() for a in ("--scale", f"{name}={n}")] + wait_args = ["--wait"] if wait else [] + self._up = True + self.compose("up", "-d", *wait_args, *scale_args, tag=tag, extra=extra) + + def digest(self, tag): + """The registry digest reference (repo@sha256:...) of the stub at ``tag``.""" + return run( + [ + "docker", + "inspect", + "--format", + "{{index .RepoDigests 0}}", + f"{self.registry}/stub:{tag}", + ] + ).stdout.strip() + + def deploy_cmd(self, tag): + return [sys.executable, "-m", "flow_deploy.cli", "deploy", "--tag", tag] + + def deploy(self, tag, timeout=240): + """Run a deploy to completion; returns the CompletedProcess.""" + self._up = True + return run( + self.deploy_cmd(tag), cwd=self.repo, env=self.env(), check=False, timeout=timeout + ) + + def start_deploy(self, tag): + """Start a deploy in the background; returns a Running. + + It leads its own process group, so a test can signal the whole group + the way a terminal's Ctrl-C does (os.killpg), not just flow-deploy. + """ + self._up = True + return Running( + subprocess.Popen( + self.deploy_cmd(tag), + cwd=self.repo, + env=self.env(), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + bufsize=1, + start_new_session=True, + ) + ) + + def state(self): + """service -> sorted list of (version tag, state) for its containers.""" + out = run( + [ + "docker", + "ps", + "-a", + "--filter", + f"label=com.docker.compose.project={self.project}", + "--format", + "{{json .}}", + ] + ).stdout + result = {} + for line in out.splitlines(): + ctr = json.loads(line) + labels = dict(kv.split("=", 1) for kv in ctr["Labels"].split(",") if "=" in kv) + svc = labels.get("com.docker.compose.service") + tag = ctr["Image"].rsplit(":", 1)[-1] if "/" in ctr["Image"] else ctr["Image"] + result.setdefault(svc, []).append((tag, ctr["State"])) + return {svc: sorted(v) for svc, v in result.items()} + + def running(self): + """service -> sorted list of the version tags of its running containers.""" + return { + svc: sorted(tag for tag, state in ctrs if state == "running") + for svc, ctrs in self.state().items() + if any(state == "running" for _, state in ctrs) + } + + def container_ids(self, service_name): + return set(self.compose("ps", "-q", service_name).stdout.split()) + + def head(self): + return self.git("rev-parse", "HEAD") + + def sha(self, tag): + return self.git("rev-parse", f"{tag}^{{commit}}") + + def lock_exists(self): + return (self.repo / ".git" / "deploy-lock").exists() + + def down(self): + if self._up: + self.compose("down", "-v", "--remove-orphans", "--timeout", "1", check=False) + + +@pytest.fixture +def stack(registry, tmp_path): + s = Stack(tmp_path, registry) + try: + yield s + finally: + s.down() + + +class Running: + """A background deploy whose output a thread collects, so waits can time out.""" + + def __init__(self, proc): + self.proc = proc + self.pid = proc.pid + self.lines = [] + self._reader = threading.Thread(target=self._read, daemon=True) + self._reader.start() + + def _read(self): + for line in self.proc.stdout: + self.lines.append(line) + + @property + def output(self): + return "".join(self.lines) + + def wait_for(self, needle, timeout=120): + """Block until a line contains ``needle``; fail after ``timeout``.""" + deadline = time.time() + timeout + while time.time() < deadline: + if needle in self.output: + return + if self.proc.poll() is not None and not self._reader.is_alive(): + break + time.sleep(0.1) + self.kill() + raise AssertionError(f"never saw {needle!r} in output:\n{self.output}") + + def finish(self, timeout=180): + """Wait for exit; returns (exit code, output). Kills it on timeout.""" + try: + self.proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + self.kill() + raise + self._reader.join(timeout=10) + return self.proc.returncode, self.output + + def kill(self): + try: + os.killpg(self.pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +SIGNALS = {"SIGINT": signal.SIGINT, "SIGTERM": signal.SIGTERM} diff --git a/tests/integration/images/sshd/Dockerfile b/tests/integration/images/sshd/Dockerfile new file mode 100644 index 0000000..7fd1668 --- /dev/null +++ b/tests/integration/images/sshd/Dockerfile @@ -0,0 +1,13 @@ +# An ssh target for the CI-cancel test: deploy-action runs +# `ssh host "cd dir && flow-deploy deploy --tag X"` with no pty. +FROM alpine:3.20 +RUN apk add --no-cache openssh-server python3 \ + && ssh-keygen -A \ + && adduser -D -s /bin/sh deploy \ + && echo 'deploy:*' | chpasswd -e \ + && mkdir -p /home/deploy/.ssh \ + && chmod 700 /home/deploy/.ssh \ + && chown deploy:deploy /home/deploy/.ssh +COPY probe.py /probe.py +EXPOSE 22 +CMD ["/usr/sbin/sshd", "-D", "-e"] diff --git a/tests/integration/images/sshd/probe.py b/tests/integration/images/sshd/probe.py new file mode 100644 index 0000000..0ecab29 --- /dev/null +++ b/tests/integration/images/sshd/probe.py @@ -0,0 +1,40 @@ +"""Stands in for a remote `flow-deploy deploy` to see what an ssh disconnect does. + +Logs through flow_deploy.log (mounted at /src), like a deploy, so stdout +behaves exactly as flow-deploy's does once the session is gone. Installs +handlers for the signals deploy() handles and records each one it receives +to /tmp/probe.log instead of acting on it, then keeps running for SECONDS so +we can see whether it would have finished. + +Usage: python3 /probe.py SECONDS +""" + +import signal +import sys +import time + +sys.path.insert(0, "/src") +from flow_deploy import log # noqa: E402 + +RECORD = "/tmp/probe.log" + + +def note(line): + with open(RECORD, "a") as f: + f.write(line + "\n") + + +def handler(signum, frame): + note(f"signal {signal.Signals(signum).name}") + + +for name in ("SIGTERM", "SIGINT", "SIGHUP"): + signal.signal(getattr(signal, name), handler) + +seconds = float(sys.argv[1]) +note("started") +deadline = time.time() + seconds +while time.time() < deadline: + log.info("draining...") # what a deploy prints while it works + time.sleep(0.2) +note("completed") diff --git a/tests/integration/images/stub/Dockerfile b/tests/integration/images/stub/Dockerfile new file mode 100644 index 0000000..ebd1b1e --- /dev/null +++ b/tests/integration/images/stub/Dockerfile @@ -0,0 +1,6 @@ +FROM alpine:3.20 +ARG STUB_VERSION=dev +ARG STUB_HEALTH=pass +ENV STUB_VERSION=${STUB_VERSION} STUB_HEALTH=${STUB_HEALTH} +COPY stub.sh /stub.sh +ENTRYPOINT ["/bin/sh", "/stub.sh"] diff --git a/tests/integration/images/stub/stub.sh b/tests/integration/images/stub/stub.sh new file mode 100644 index 0000000..dfca09f --- /dev/null +++ b/tests/integration/images/stub/stub.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Stand-in service for flow-deploy's integration tests. Behavior comes from env: +# +# STUB_VERSION reported in logs; baked per image tag +# STUB_HEALTH pass (default) | fail | after:N (healthy after N seconds) +# STUB_SIGTERM_DELAY seconds to keep running after SIGTERM before exiting +# STUB_IGNORE_SIGTERM 1 to ignore SIGTERM entirely (only SIGKILL stops it) +# STUB_CRASH 1 to exit 1 immediately (a crash loop under a restart policy) +# +# Health is a file the compose healthcheck tests for: /tmp/healthy. + +echo "stub ${STUB_VERSION} starting" +if [ "${STUB_CRASH}" = 1 ]; then + echo "stub ${STUB_VERSION} crashing" + exit 1 +fi + +rm -f /tmp/healthy +case "${STUB_HEALTH:-pass}" in + pass) touch /tmp/healthy ;; + fail) ;; + after:*) (sleep "${STUB_HEALTH#after:}" && touch /tmp/healthy) & ;; +esac + +on_term() { + echo "stub ${STUB_VERSION} got SIGTERM" + if [ "${STUB_IGNORE_SIGTERM}" = 1 ]; then + return + fi + sleep "${STUB_SIGTERM_DELAY:-0}" + echo "stub ${STUB_VERSION} exiting" + exit 0 +} +trap on_term TERM + +while true; do + sleep 1 & + wait $! +done diff --git a/tests/integration/test_ci_cancel.py b/tests/integration/test_ci_cancel.py new file mode 100644 index 0000000..c36a313 --- /dev/null +++ b/tests/integration/test_ci_cancel.py @@ -0,0 +1,116 @@ +"""What a cancelled CI job does to a remote deploy. + +deploy-action runs `ssh host "cd dir && flow-deploy deploy --tag X"` with no +pty. These tests run a stand-in for flow-deploy (images/sshd/probe.py, which +logs through flow_deploy.log and records the signals deploy() handles) over +real ssh, kill the client mid-run as a cancelled job does, and check what the +remote process received. + +Finding: without a pty, sshd sends the remote process no signal when the +client disconnects. The deploy runs on (output to the closed session is +swallowed) and finishes, or reverts on its own failure. With `ssh -tt` the +remote process gets SIGHUP, which flow-deploy treats as an interrupt. +""" + +import signal +import subprocess +import time +import uuid + +import pytest + +from tests.integration.conftest import IMAGES, SRC, run + +PROBE_SECONDS = 6 + + +@pytest.fixture(scope="module") +def sshd(docker, tmp_path_factory): + key = tmp_path_factory.mktemp("ssh") / "id" + run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)]) + run(["docker", "build", "-q", "-t", "flowdeploy-it-sshd", str(IMAGES / "sshd")]) + name = f"flowdeploy-it-sshd-{uuid.uuid4().hex[:8]}" + run( + [ + "docker", + "run", + "-d", + "--name", + name, + "-p", + "127.0.0.1::22", + "-v", + f"{SRC}:/src:ro", + "flowdeploy-it-sshd", + ] + ) + try: + port = run(["docker", "port", name, "22"]).stdout.strip().split(":")[-1] + run(["docker", "cp", f"{key}.pub", f"{name}:/home/deploy/.ssh/authorized_keys"]) + run( + [ + "docker", + "exec", + name, + "sh", + "-c", + "chown deploy /home/deploy/.ssh/authorized_keys" + " && chmod 600 /home/deploy/.ssh/authorized_keys", + ] + ) + yield {"name": name, "port": port, "key": str(key)} + finally: + run(["docker", "rm", "-f", name], check=False) + + +def probe_log(sshd): + out = run(["docker", "exec", sshd["name"], "cat", "/tmp/probe.log"], check=False).stdout + return out.strip().splitlines() + + +def cancel_mid_run(sshd, tty_flag, kill_with): + """Start the probe over ssh, kill the client mid-run, return the probe's record.""" + run(["docker", "exec", sshd["name"], "rm", "-f", "/tmp/probe.log"]) + client = subprocess.Popen( + [ + "ssh", + tty_flag, + "-i", + sshd["key"], + "-p", + sshd["port"], + "-o", + "StrictHostKeyChecking=no", + "-o", + "UserKnownHostsFile=/dev/null", + "-o", + "LogLevel=ERROR", + "-o", + "BatchMode=yes", + "deploy@127.0.0.1", + f"cd /tmp && python3 /probe.py {PROBE_SECONDS}", + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + deadline = time.time() + 30 + while "started" not in probe_log(sshd): + assert time.time() < deadline, "probe never started" + time.sleep(0.1) + time.sleep(1) + client.send_signal(kill_with) + client.wait(timeout=10) + time.sleep(PROBE_SECONDS + 2) # long enough for the probe to finish if it's alive + return probe_log(sshd) + + +@pytest.mark.parametrize("kill_with", [signal.SIGKILL, signal.SIGTERM], ids=["SIGKILL", "SIGTERM"]) +def test_without_a_pty_the_remote_deploy_gets_no_signal_and_runs_on(sshd, kill_with): + record = cancel_mid_run(sshd, "-T", kill_with) + assert record == ["started", "completed"], record + + +def test_with_a_forced_pty_the_remote_deploy_gets_sighup(sshd): + record = cancel_mid_run(sshd, "-tt", signal.SIGKILL) + assert "signal SIGHUP" in record, record diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py new file mode 100644 index 0000000..bc4937c --- /dev/null +++ b/tests/integration/test_deploys.py @@ -0,0 +1,226 @@ +"""flow-deploy against real containers: drain-first, rolling, and every revert path.""" + +import os +import time + +import pytest + +from tests.integration.conftest import SIGNALS, service, standard + +ALL_V1 = {"web": ["v1"], "scheduler": ["v1"], "worker": ["v1"]} + + +def assert_reverted(stack, expected_running, code, out, expected_code=1): + assert code == expected_code, out + assert stack.running() == expected_running, out + assert stack.head() == stack.sha("v1"), "repo not restored to the previous commit" + assert not stack.lock_exists(), "lock left behind" + + +def test_happy_path(stack): + stack.commit("v1", standard()) + stack.commit("v2", standard()) + stack.up("v1", scale={"worker": 2}) + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + # The worker keeps its replica count. + assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2", "v2"]} + assert stack.head() == stack.sha("v2") + assert not stack.lock_exists() + out = result.stdout + # Drain in reverse deploy.order, roll, then start in deploy.order. + order = [ + out.index("▸ worker"), + out.index("▸ scheduler"), + out.index("▸ web"), + out.rindex("▸ scheduler"), + out.rindex("▸ worker"), + ] + assert order == sorted(order) + + +def test_first_deploy_of_a_new_drain_first_service(stack): + stack.commit("v1", standard(scheduler=None)) + stack.commit("v2", standard()) + stack.up("v1") + assert "scheduler" not in stack.running() + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} + + +def test_rolling_service_fails_its_healthcheck(stack): + """Drained services come back on v1 at their replica count, and web keeps + its old container. (On master, scale-back recreated web's old container + on the failing image.)""" + stack.commit("v1", standard()) + stack.commit("unhealthy", standard()) + stack.up("v1", scale={"worker": 2}) + + result = stack.deploy("unhealthy") + + assert_reverted( + stack, + {"web": ["v1"], "scheduler": ["v1"], "worker": ["v1", "v1"]}, + result.returncode, + result.stdout, + ) + + +def test_rolling_only_project_keeps_its_old_container_on_a_failed_healthcheck(stack): + """No drain-first anywhere: the fix to scale-back applies to every project.""" + stack.commit("v1", standard(scheduler=None, worker=None)) + stack.commit("unhealthy", standard(scheduler=None, worker=None)) + stack.up("v1") + old = stack.container_ids("web") + + result = stack.deploy("unhealthy") + + assert_reverted(stack, {"web": ["v1"]}, result.returncode, result.stdout) + assert stack.container_ids("web") == old, "web's old container was replaced" + + +def test_drain_first_service_fails_its_healthcheck_in_phase_3(stack): + """The failed worker goes back to v1 at its replica count. Web and the + scheduler, healthy on v3, stay: shipped services aren't rolled back.""" + stack.commit("v1", standard()) + bad_worker = service(300, "drain-first", env={"STUB_HEALTH": "fail"}, health_timeout=20) + stack.commit("v3", standard(worker=bad_worker)) + stack.up("v1", scale={"worker": 2}) + + result = stack.deploy("v3") + + assert_reverted( + stack, + {"web": ["v3"], "scheduler": ["v3"], "worker": ["v1", "v1"]}, + result.returncode, + result.stdout, + ) + assert "worker failed to start" in result.stdout + + +def test_bad_tag_fails_at_pull_before_anything_stops(stack): + stack.commit("v1", standard()) + stack.commit("bad", standard()) # no such image in the registry + stack.up("v1") + before = {svc: stack.container_ids(svc) for svc in ("web", "scheduler", "worker")} + + result = stack.deploy("bad") + + assert_reverted(stack, ALL_V1, result.returncode, result.stdout) + after = {svc: stack.container_ids(svc) for svc in ("web", "scheduler", "worker")} + assert after == before, "a container was replaced despite the failed pull" + + +def test_drain_that_hits_its_timeout_is_killed_and_the_deploy_continues(stack): + stubborn = service(300, "drain-first", drain=3, env={"STUB_IGNORE_SIGTERM": "1"}) + stack.commit("v1", standard(worker=stubborn)) + stack.commit("v2", standard(worker=stubborn)) + stack.up("v1") + + started = time.time() + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.running()["worker"] == ["v2"] + assert "(3s timeout)" in result.stdout + assert time.time() - started >= 3 + + +@pytest.mark.parametrize( + ("signame", "to_group"), + [("SIGINT", False), ("SIGTERM", False), ("SIGINT", True)], + ids=["SIGINT", "SIGTERM", "SIGINT-to-process-group"], +) +def test_signal_mid_drain_reverts(stack, signame, to_group): + """to_group sends the signal to flow-deploy's whole process group, as a + terminal's Ctrl-C does, so the docker stop child would get it too if it + weren't in its own session.""" + slow = service(300, "drain-first", drain=30, env={"STUB_SIGTERM_DELAY": "10"}) + stack.commit("v1", standard(worker=slow)) + stack.commit("v2", standard(worker=slow)) + stack.up("v1") + + running = stack.start_deploy("v2") + running.wait_for("draining") + time.sleep(1) + if to_group: + os.killpg(running.pid, SIGNALS[signame]) + else: + os.kill(running.pid, SIGNALS[signame]) + code, out = running.finish() + + assert "finishing the drain" in out + # Outlast the old worker's SIGTERM delay: a restore that only "saw" a + # still-stopping container would leave nothing running once it exits. + time.sleep(12) + assert_reverted(stack, ALL_V1, code, out) + + +def test_lock_held_by_a_live_process_exits_2_and_changes_nothing(stack): + stack.commit("v1", standard()) + stack.commit("v2", standard()) + stack.up("v1") + lock = stack.repo / ".git" / "deploy-lock" + lock.write_text(f'{{"pid": {os.getpid()}, "timestamp": 0}}') + before = {svc: stack.container_ids(svc) for svc in ("web", "scheduler", "worker")} + + result = stack.deploy("v2") + + assert result.returncode == 2 + assert "Deploy lock held by PID" in result.stderr + assert stack.head() == stack.sha("v1") + assert {svc: stack.container_ids(svc) for svc in ("web", "scheduler", "worker")} == before + assert lock.exists(), "another process's lock was released" + + +def test_old_image_without_a_tag_exits_3(stack): + """A worker started from a digest-pinned image can't be restored by tag.""" + pinned_worker = service( + 300, "drain-first", image="${WORKER_IMAGE:-${REGISTRY}/stub:${DEPLOY_TAG}}" + ) + stack.commit("v1", standard(worker=pinned_worker)) + stack.commit("unhealthy", standard(worker=pinned_worker)) + stack.up("v1", extra={"WORKER_IMAGE": stack.digest("v1")}) + + result = stack.deploy("unhealthy") + + assert result.returncode == 3, result.stdout + result.stderr + assert "cannot restore worker: no tag in its previous image" in result.stdout + assert "could not be fully reverted" in result.stderr + assert stack.running() == {"web": ["v1"], "scheduler": ["v1"]} + assert stack.head() == stack.sha("v1") + assert not stack.lock_exists() + + +def test_crash_looping_drain_first_worker_is_drained(stack): + """A restarting container is drained too, so it can't come back on old code.""" + looping = service(300, "drain-first", env={"STUB_CRASH": "1"}) + looping["restart"] = "unless-stopped" + stack.commit("v1", standard(worker=looping)) + stack.commit("v2", standard()) + stack.up("v1", wait=False) + time.sleep(3) # let it start crash-looping + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.state()["worker"] == [("v2", "running")], "an old worker container remains" + + +def test_rolling_healthcheck_that_passes_late_still_deploys(stack): + """A slow starter needs a start_period: without one Docker marks it + unhealthy after `retries` failed checks, and flow-deploy aborts on that.""" + stack.commit("v1", standard()) + slow_web = service(100, env={"STUB_HEALTH": "after:4"}, start_period="15s") + stack.commit("v2", standard(web=slow_web)) + stack.up("v1") + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.running()["web"] == ["v2"] diff --git a/tests/rolling_scenarios.py b/tests/rolling_scenarios.py index 079be0f..b36a7a2 100644 --- a/tests/rolling_scenarios.py +++ b/tests/rolling_scenarios.py @@ -117,7 +117,7 @@ def record(deploy_module, process_module, name, workdir): queue = [process_module.Result(*r) for r in responses] calls = [] - def fake_run(args, env=None, cwd=None): + def fake_run(args, env=None, cwd=None, **_kwargs): calls.append([args, env]) return queue.pop(0) if queue else process_module.Result(0, "", "") diff --git a/tests/test_containers.py b/tests/test_containers.py index fd139b7..09da902 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -111,6 +111,12 @@ def test_stop_container(mock_process): assert args == ["docker", "stop", "--time", "60", "abc123"] +def test_stop_container_isolated_runs_in_its_own_session(mock_process): + assert stop_container("abc123", timeout=5, isolate=True) is True + assert stop_container("def456") is True + assert mock_process.new_sessions == [["docker", "stop", "--time", "5", "abc123"]] + + def test_stop_container_failure(mock_process): mock_process.responses.append(process.Result(1, "", "")) assert stop_container("abc123") is False diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py index d45828e..683aa60 100644 --- a/tests/test_deploy_failures.py +++ b/tests/test_deploy_failures.py @@ -79,7 +79,7 @@ def test_signal_while_a_drain_is_stopping_still_restores(mock_process, monkeypat """A drain can take an hour: a cancel mid-stop must still know what to restore.""" _chdir(monkeypatch, tmp_path) - def stop_interrupted(container_id, timeout=30): + def stop_interrupted(container_id, timeout=30, isolate=False): signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) monkeypatch.setattr(deploy_mod.containers, "stop_container", stop_interrupted) diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 77880fc..9bd91ef 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -78,6 +78,8 @@ def test_drain_first_runs_drain_then_rolling_then_start(mock_process, monkeypatc cmds = _commands(mock_process) drain = _index(cmds, "docker stop", "--time 3660", "old_wrk_333") roll = _index(cmds, "--scale web=2") + # Only the drain's stop is out of the process group; rolling's isn't. + assert mock_process.new_sessions == [["docker", "stop", "--time", "3660", "old_wrk_333"]] start = _index(cmds, "--scale worker=1 worker") assert drain < roll < start # The worker never scales to 2: no overlap of old and new. diff --git a/tests/test_process.py b/tests/test_process.py index 3ba0668..aefc213 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -42,6 +42,14 @@ def test_run_streaming_nonzero(): assert code != 0 +def test_run_in_a_new_session_leads_its_own_session(): + import sys + + probe = "import os; print(os.getsid(0) == os.getpid())" + assert run([sys.executable, "-c", probe], new_session=True).stdout.strip() == "True" + assert run([sys.executable, "-c", probe]).stdout.strip() == "False" + + def test_run_streaming_with_env(): code = run_streaming(["sh", "-c", 'test "$TEST_VAR" = works'], env={"TEST_VAR": "works"}) assert code == 0 diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py index 497cdc4..d7cbe61 100644 --- a/tests/test_rolling_parity.py +++ b/tests/test_rolling_parity.py @@ -29,6 +29,22 @@ } +def deliberate_command_changes(calls): + """master's commands, with the agreed command-level fix applied. + + Scale-back gains --no-recreate. On master, scale-back after a failed + health check ran `compose up --scale svc=1` with the new tag, which + recreated the surviving old container on the new, failing image. Found + by tests/integration (test_rolling_service_fails_its_healthcheck). + """ + fixed = [] + for args, env in calls: + if args[-6:-2] == ["up", "-d", "--no-deps", "--scale"] and args[-2].endswith("=1"): + args = args[:-3] + ["--no-recreate"] + args[-3:] # after --no-deps + fixed.append([args, env]) + return fixed + + def test_scenarios_and_fixture_agree(): assert set(SCENARIOS) == set(MASTER) @@ -43,7 +59,8 @@ def test_rolling_deploy_matches_master(name, monkeypatch, tmp_path, capsys): observed = record(deploy_mod, process, name, str(tmp_path)) - assert observed["calls"] == MASTER[name]["calls"], f"{name}: commands differ from master" + expected_calls = deliberate_command_changes(MASTER[name]["calls"]) + assert observed["calls"] == expected_calls, f"{name}: commands differ from master" expected = {"code": MASTER[name]["code"], "lock_left": MASTER[name]["lock_left"]} expected.update(DELIBERATE_CHANGES.get(name, {})) assert observed["code"] == expected["code"] From 52873de16b101929d02b44e2b28a23f7736ebafe Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sat, 10 Oct 2026 23:26:50 -0600 Subject: [PATCH 11/19] Deploy by version tag, and restore exactly what was running DEPLOY_TAG is normally a release version now (v0.9.2), with commit SHAs still supported, so every consumer of the tag has to handle both: - git fetch --tags --force, so release tags arrive and a re-pushed tag moves; checkout handles lightweight and annotated tags and SHAs. - compose config is rendered with DEPLOY_TAG, and a warning is printed when an app image ignores it. What a failed deploy restores is read from the containers, not from git HEAD or :latest. Before changing anything, each app service's running image ID is recorded and aliased locally as :flow-deploy-. Any failure or signal then reverts every app service onto that alias: rolling services that already shipped are rolled back, and drain-first services are restored. The restore is exact whether a service ran a version, a SHA, a moved :latest, a digest, or no tag at all. The deploy stops before touching anything if an image can't be aliased or if another compose project runs in the directory. The revert also handles cleanup failures, which master didn't: - A rollback keeps a previous-image container that survived its cutover. - Scale-back waits until the other container is really gone. - Stopped leftovers are removed before compose up --scale can restart them. The manual-ops hazard is fixed. `flow-deploy tag` prints the deployed tag, taken from the running containers, or from .git/deploy-tag when nothing runs, and refuses on ambiguity. `flow-deploy compose ARGS` runs the compose wrapper with that tag, so `up -d` on the host never silently moves services to :latest. A wrapper can default DEPLOY_TAG the same way, and a lookup placeholder keeps that from recursing. `status` shows the deployed tag. Unit tests now run on a FakeHost simulator rather than call-sequence mocks. The rolling parity test replays master's recorded commands on the same scenarios, with each deliberate change listed. New integration scenarios cover: - a version-tag deploy and a SHA deploy - restoring a previously running version - a first deploy from :latest, restored after :latest is re-pushed - manual compose - a moved tag - a renamed compose project Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 135 +++-- SPEC.md | 134 ++++- docs/github-actions.md | 81 ++- src/flow_deploy/cli.py | 53 +- src/flow_deploy/compose.py | 13 +- src/flow_deploy/containers.py | 78 ++- src/flow_deploy/deploy.py | 388 ++++++++++---- src/flow_deploy/deployed.py | 86 ++++ src/flow_deploy/git.py | 8 +- src/flow_deploy/log.py | 6 + tests/fake_host.py | 297 +++++++++++ tests/fixtures/rolling_master.json | 260 +++++----- tests/helpers.py | 47 ++ tests/integration/conftest.py | 84 +++- tests/integration/test_deploys.py | 186 ++++++- tests/rolling_scenarios.py | 173 +++---- tests/test_cli.py | 26 +- tests/test_compose.py | 8 + tests/test_containers.py | 95 ++++ tests/test_deploy.py | 778 +++++++++++++--------------- tests/test_deploy_failures.py | 504 +++++-------------- tests/test_deployed.py | 224 +++++++++ tests/test_drain_first.py | 783 ++++++++--------------------- tests/test_git.py | 2 + tests/test_log.py | 17 + tests/test_rolling_parity.py | 102 +++- 26 files changed, 2733 insertions(+), 1835 deletions(-) create mode 100644 src/flow_deploy/deployed.py create mode 100644 tests/fake_host.py create mode 100644 tests/helpers.py create mode 100644 tests/test_deployed.py diff --git a/README.md b/README.md index d5502cf..3cbe564 100644 --- a/README.md +++ b/README.md @@ -35,19 +35,23 @@ services: retries: 5 ``` +The tag is both a git ref (checked out on the host) and the image tag: every app +service's image must end in `:${DEPLOY_TAG}`, usually `:${DEPLOY_TAG:-latest}` +(see [Image Tags](#image-tags)). + Every `deploy.role=app` service **must** have a `healthcheck` defined in compose (Dockerfile `HEALTHCHECK` is not detected). To opt out, set `deploy.healthcheck.skip=true`. Services without a `deploy.role` label are ignored. **2. Deploy:** ```sh -flow-deploy deploy --tag abc123f +flow-deploy deploy --tag v1.4.0 # a release tag, or a commit SHA ``` ``` [12:34:56] ── deploy ────────────────────────────── -[12:34:56] tag: abc123f +[12:34:56] tag: v1.4.0 [12:34:58] ▸ web -[12:34:58] pulling ghcr.io/myorg/myapp:abc123f... +[12:34:58] pulling ghcr.io/myorg/myapp:v1.4.0... [12:35:02] pulled (3.8s) [12:35:02] starting new container... [12:35:05] waiting for health check (timeout: 120s)... @@ -115,26 +119,34 @@ then web and api roll, then the worker starts last, after the services it depends on. The worker is down from the start of its drain until phase 3. Queued work waits in the broker and the new worker picks it up. -**A failed deploy leaves no trace.** It doesn't need manual cleanup: - -- A rolling service that fails is reverted as always: the old container keeps - serving and the new one is removed. -- Every drained service comes back on the image tag it was running, at the same - replica count, in `deploy.order`. That holds whatever failed, including a - container that wouldn't stop and a drain-first service that failed its own - start. Phase 3 attempts every start, removes any that fail, and restores only - those. This relies on the same expand-then-contract migration discipline as - rolling deploys: old code keeps working against the new schema. +**A failed deploy leaves no trace.** Whatever fails, every app service goes +back to exactly what it ran before the deploy, with no manual cleanup: + +- The failing rolling service keeps its old container; the new one is removed. +- Rolling services that already shipped earlier in the run are rolled back, in + reverse `deploy.order`, with the same rolling deploy onto their previous image. +- Every drain-first service comes back on its previous image at the same + replica count, in `deploy.order`. That includes one that wouldn't stop, one + that failed its own start, and one already healthy on the new tag: phase 3 + attempts every start, and a failure anywhere sends them all back. A service + that wasn't running before the deploy is left stopped. - The repo goes back to the previous commit, and the lock is released. -Rolling services that already shipped earlier in the run stay deployed (see -Deploy Ordering in SPEC.md). - -Restoring relies on the same contract as every deploy: each app service's image -is tagged by `DEPLOY_TAG`, for example `image: ghcr.io/org/app:${DEPLOY_TAG}` -directly or through an env var that expands to it. A restore runs `compose up` -with the previous tag in `DEPLOY_TAG`. A service whose image ignores it comes -back on whatever the compose file names. +A rollback runs old code against whatever the new code already did (a +migration, say), so this relies on the usual expand-then-contract discipline: +old code keeps working against the new schema. + +What "previous" means is read from the containers, not from git or `:latest`. +Before changing anything, the deploy records the image each app service is +running (the most common one if its containers disagree, with a warning) and +gives it a local alias, `:flow-deploy-`. A revert runs +`compose up` with that alias in `DEPLOY_TAG`, so it restores the exact image +even if the service was started from `:latest`, from a tag that has since been +re-pushed, from a digest, or from no tag at all. See [Image Tags](#image-tags). +If an image can't be aliased, or containers of a differently named compose +project run in the same directory (a release that renamed the project would +start a second stack beside the first), the deploy stops before changing +anything. A signal reverts the same way, and so does an unexpected error. The signals are SIGTERM (a timeout or shutdown), Ctrl-C (SIGINT), and SIGHUP (a hung-up @@ -147,8 +159,6 @@ immediately would find the container still "running" and leave it be, only to see it exit afterwards. Holding the signal costs at most the rest of that container's drain. -Drain-first services already healthy on the new tag stay. - **A cancelled CI job does not revert a remote deploy.** `deploy-action` runs `ssh host "cd dir && flow-deploy deploy --tag X"` with no pty. Without a pty, sshd sends the remote process no signal when the client disconnects. @@ -162,22 +172,33 @@ The deploy exits `1` when it failed and everything was put back. It exits `3` only when something couldn't be put back: - the git restore failed -- a restore's `compose up` failed -- the old image had no tag to restore +- a rollback or restore failed - a *failed* service's own cleanup failed, such as an aborted new container that won't stop or be removed Even then the lock is released. Exit `3` is the signal that someone needs to look. -Rolling deploys otherwise behave exactly as before. `tests/test_rolling_parity.py` +Rolling deploys otherwise behave as before. `tests/test_rolling_parity.py` replays 15 rolling scenarios against a recording of the previous release: every command, its environment, the exit code, and the lock. As before, a successful cutover whose old-container cleanup fails still succeeds, with a warning: the new container is healthy and serving. -The two deliberate changes for rolling-only projects: - +The deliberate changes for rolling-only projects, each pinned by that test: + +- A later service's failure rolls back services that already shipped. + Previously they stayed on the new tag beside services on the old one. +- The deploy snapshots and aliases each service's running image first. +- `git fetch --tags --force origin`, so release tags arrive and a re-pushed + tag moves. +- `compose config` is rendered with the deploy's `DEPLOY_TAG`. +- Scale-back after a failed health check passes `--no-recreate`. Previously it + recreated the surviving old container on the new, failing image. +- Scale-back is skipped when the container it should leave behind couldn't be + stopped and removed: with two left it removes one, and could pick the wrong + one. The cutover still succeeds with a warning, as before. +- A compose project name that differs from the running containers' is refused. - A failed git restore exits `3` and releases the lock. - A signal restores the repo before exiting `1`. Previously it released the lock and exited without restoring. @@ -194,6 +215,62 @@ services: deploy.drain: "3660" # longest job + margin ``` +## Image Tags + +`DEPLOY_TAG` is normally the release version (`v1.4.0`), and a commit SHA works +just as well. The tag is used twice: `git checkout --detach ` (lightweight +and annotated tags and SHAs all work; tags are fetched with `--force`, so a +re-pushed tag moves), and as the image tag compose pulls and runs. CI pushes the +image under every tag it might deploy by, typically the version and the SHA. The +compose file must name each app image with it: + +```yaml +image: ghcr.io/myorg/myapp:${DEPLOY_TAG:-latest} +# or, through .env: DOCKER_IMAGE=ghcr.io/myorg/myapp:${DEPLOY_TAG:-latest} +# image: ${DOCKER_IMAGE} +``` + +A deploy warns when an app service's rendered image doesn't end in `:`. +Such a service keeps running whatever the compose file names. + +### Manual compose commands on the host + +The `:-latest` default is a trap: a person running `docker compose up -d` on the +host, with `DEPLOY_TAG` unset, silently moves every service to `:latest`. So +flow-deploy can tell you what's deployed, and run compose with it: + +```sh +flow-deploy tag # prints the deployed tag, e.g. v1.4.0 +flow-deploy compose up -d # compose with DEPLOY_TAG set to it +flow-deploy compose run --rm web python manage.py migrate +DEPLOY_TAG=v1.3.0 flow-deploy compose up -d # an explicit DEPLOY_TAG wins +``` + +The deployed tag is read from the running app containers when they all agree, +else from `.git/deploy-tag` (written by every successful whole-project deploy) +when nothing is running. Mixed or untagged images, or nothing to go on, are an +error ("set DEPLOY_TAG"), never a guess. `flow-deploy status` shows it too. +After a revert, services recreated from the snapshot run the +`flow-deploy-` alias of their previous image, and the record holds it; +a service that kept its old container still shows its old tag. Either way the +image is the one that ran before, and when every service runs that one image +the deployed tag is the alias. An alias is a local tag: `flow-deploy compose +up` works with it, `pull` won't. The next deploy replaces it. + +If the project has a compose wrapper (`script/prod`), make the wrapper default +`DEPLOY_TAG` the same way, so `script/prod up -d` is safe too: + +```sh +if [ -z "${DEPLOY_TAG:-}" ] && command -v flow-deploy >/dev/null; then + DEPLOY_TAG=$(flow-deploy tag 2>/dev/null) && export DEPLOY_TAG +fi +``` + +flow-deploy calls the wrapper itself; while it looks up the tag it sets +`DEPLOY_TAG` to a placeholder, so the wrapper never recurses. A `--service` +deploy that leaves some app services out leaves them on different tags, so it +clears the record and warns. + ## Host Discovery For CI/CD orchestration across multiple hosts, declare topology in your compose file: @@ -224,6 +301,8 @@ See [GitHub Actions Setup](docs/github-actions.md) for CI/CD integration. ``` flow-deploy deploy [--tag TAG] [--service NAME] [--dry-run] flow-deploy status +flow-deploy tag +flow-deploy compose ARGS... flow-deploy exec SERVICE COMMAND... flow-deploy logs SERVICE [-f] [-n LINES] flow-deploy upgrade diff --git a/SPEC.md b/SPEC.md index 61f3282..607b606 100644 --- a/SPEC.md +++ b/SPEC.md @@ -10,7 +10,7 @@ A minimal, opinionated deployment tool for Docker Compose + Traefik stacks. Repl - **Two layers, clean split.** A server-side CLI (`flow-deploy`) handles the single-node deploy lifecycle — pull, scale, health check, cutover. A GitHub Action (`flow-deploy-action`) handles host discovery, fleet orchestration, and SSH fan-out. Single-host projects can skip the action entirely. - **Accessories are left alone.** Databases, caches, and other stateful services are never restarted during a deploy unless explicitly requested. - **Builds happen in CI.** The tool does not build images. GitHub Actions builds and pushes to GHCR. The tool pulls and swaps. -- **Failure is a no-op.** If a new container fails its health check, the old container continues serving traffic untouched. The deploy exits nonzero. +- **Failure is a no-op.** If a new container fails its health check, the old container continues serving traffic untouched. Any failure puts every app service back on the exact image it ran before the deploy, and the deploy exits nonzero. - **Logging is the interface.** All output is structured, human-readable, and designed to flow through an SSH session back into GitHub Actions logs. --- @@ -29,18 +29,29 @@ Every service in `docker-compose.yml` is classified by a label: ### 2.2 Deploy Lifecycle -The deploy runs as a single transaction — `flow-deploy deploy` owns the full lifecycle including git operations. When `--tag ` is provided, the value serves double duty: it is both the Docker image tag and the git SHA to checkout. When `--tag` is omitted, the tool deploys the current HEAD — the git checkout is skipped and `DEPLOY_TAG` is set to the current commit SHA. +The deploy runs as a single transaction — `flow-deploy deploy` owns the full lifecycle including git operations. When `--tag ` is provided, the value serves double duty: it is both the Docker image tag and the git ref to checkout. It is normally a release version (`v1.4.0`); a commit SHA works too (§2.8). When `--tag` is omitted, the tool deploys the current HEAD — the git checkout is skipped and `DEPLOY_TAG` is set to the current commit SHA. **Pre-flight and git checkout (before any service work):** ``` 0a. Dirty check git status --porcelain If non-empty → log "working tree is dirty — deploy aborted", exit 1 -0b. Fetch git fetch origin +0b. Fetch git fetch --tags --force origin 0c. Record previous SHA previous_sha = git rev-parse HEAD -0d. Checkout (detached) git checkout --detach (skipped when --tag is omitted) +0d. Checkout (detached) git checkout --detach (skipped when --tag is omitted) +0e. Render config DEPLOY_TAG= config +0f. Project check docker ps by compose's working_dir label: containers + of another compose project here → refuse +0g. Snapshot for each app service: docker ps (running + restarting), + docker inspect → image IDs; the most common one is + "previous" (warn if they differ), aliased as + docker tag :flow-deploy- + in the config's repo and the container's own + If any of this fails → restore repo, exit 1 ``` +The snapshot is what a revert restores: the exact image each service was running, whatever tag (or none) it was started from (§2.8). + **For each service with `deploy.role=app`, in the order they appear in the compose file:** ``` @@ -50,18 +61,41 @@ The deploy runs as a single transaction — `flow-deploy deploy` owns the full l 4a. If healthy: Graceful shutdown docker stop --time Remove old container docker rm - Scale back to 1 up -d --no-deps --scale =1 + Scale back to 1 up -d --no-deps --no-recreate --scale =1 + (skipped, with a warning, if the old one couldn't be removed) ✓ Continue to next service 4b. If unhealthy: Stop new container docker stop && docker rm - Scale back to 1 up -d --no-deps --scale =1 - Restore repo git checkout --detach - ✗ Abort deploy, exit 1 + Scale back to 1 up -d --no-deps --no-recreate --scale =1 + ✗ Revert (below), exit 1 ``` -**On success:** the server is in detached HEAD at ``. Log `HEAD detached at `. +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 `. -**On failure:** the repo is restored to `` before exiting. The invariant is preserved: `git rev-parse HEAD` always matches the image SHA that is actively serving traffic. +**On failure** (a failed step, a signal, or an unexpected error), the deploy reverts: + +``` +R1. Restore repo git checkout --detach +R1b. Failed service remove stopped containers its abort couldn't remove +R2. Roll back shipped for each rolling service that already deployed, in reverse order: + remove its stopped leftovers (compose would restart them), then + DEPLOY_TAG= rolling deploy (no pull) back to its + previous image; if a container on the previous image + survived the cutover, remove the new ones instead; + a service that had no containers is removed +R3. Restore drain-first for each drained service, in deploy order: + remove its stopped leftovers on other images, + stop + remove containers not on its previous image, + DEPLOY_TAG= up -d --no-deps + --no-recreate --scale = + (left stopped if it wasn't running before) +R4. Record .git/deploy-tag = the restored alias (cleared if services differ) +R5. Release the lock always +``` + +Exit `1` if everything was put back, `3` if anything couldn't be (§4.1). The invariant is preserved: `git rev-parse HEAD` matches the code of the images actively serving traffic. Where `` is the project's compose wrapper (see §3.1). @@ -90,13 +124,22 @@ Configuration (via labels on the service): ### 2.5 Deploy Order -Services are deployed in the order they appear in `docker-compose.yml`. If a service fails, all subsequently listed services are skipped. Previously deployed services in the same run are NOT rolled back — they already passed health checks and are serving traffic. This matches the expand-then-contract migration discipline: each service should be independently deployable. +Services are deployed in the order they appear in `docker-compose.yml`. If a service fails, all subsequently listed services are skipped, and services that already deployed in the same run are rolled back to their previous image (§2.2, R2), so no service runs new code beside others on old code. Old code then runs against whatever the new code did (a migration, say), which is the expand-then-contract discipline every rolling deploy already relies on. If explicit ordering is needed beyond file order, a label is available: | Label | Default | Description | |---|---|---| | `deploy.order` | `100` | Integer. Lower deploys first. Ties broken by file order. | +| `deploy.strategy` | `rolling` | `rolling` or `drain-first` | + +**Drain-first services** (queue workers, schedulers) never overlap old and new. The deploy runs in three phases: + +1. **Drain** drain-first services in *reverse* `deploy.order`: pull the new image, then `docker stop --time ` every running or restarting container, then remove it. Nothing rolls until every drain has finished. +2. **Roll** rolling services in `deploy.order`, as above. +3. **Start** drain-first services in `deploy.order` on the new tag, at their previous replica count (at least 1), each health-checked. Every start is attempted; a failure removes what it started. + +A failure in any phase reverts everything (§2.2). A signal that arrives while a drain is stopping a container is held until that container has stopped and been removed, then the deploy reverts. ### 2.6 Host Discovery @@ -202,18 +245,30 @@ The GitHub Action (§7) reads these values by running ` config` The tool needs to know which image tag to deploy. When `--tag` is omitted, the tool uses the current HEAD SHA — deploying whatever is currently checked out. When `--tag` is provided, the tool checks out that ref and uses it as the image tag: ``` -flow-deploy deploy --tag abc123f +flow-deploy deploy --tag v1.4.0 +flow-deploy deploy --tag 3f2c9e1d... # a commit SHA works the same way ``` -The `--tag` value temporarily overrides the image tag for all `deploy.role=app` services before pulling. This is implemented via the `DEPLOY_TAG` environment variable, which compose files can reference: +**Git side.** Tags are fetched with `git fetch --tags --force origin`, so a new release tag is always present and a re-pushed (moved) tag updates locally. `git checkout --detach ` accepts lightweight tags, annotated tags (it checks out the tagged commit), and SHAs. + +**Image side.** The `--tag` value is passed to every compose command as the `DEPLOY_TAG` environment variable, which each `deploy.role=app` image must end with: ```yaml services: web: image: ghcr.io/myorg/myapp:${DEPLOY_TAG:-latest} + # or image: ${DOCKER_IMAGE}, with DOCKER_IMAGE=ghcr.io/myorg/myapp:${DEPLOY_TAG:-latest} in .env ``` -The deployed SHA is always available via `git rev-parse HEAD` — the server is kept in detached HEAD at the deployed commit. The tool does not write any state files to the working tree. +CI must push the image under every tag it may deploy by (the version, and the SHA as a fallback). The deploy renders its compose config with `DEPLOY_TAG` set and warns when an app image doesn't end in `:`; such a service keeps whatever image the compose file names. + +**What's running.** Restores never trust a tag name. The pre-deploy snapshot (§2.2, 0g) records each service's running image ID and tags it locally as `:flow-deploy-` (the full ID, so it can't collide), under both the new compose config's repo and the repo the container was started from. A revert deploys that alias, so it gets the exact image back even when the service was started from `:latest`, from a tag re-pushed since, from a digest, or untagged. If an alias can't be created the deploy stops before changing anything. Aliases are local only and are never pushed. + +**What's deployed.** `flow-deploy tag` (§4.7) answers "which tag is deployed here": the tag of the running app containers when they all agree; otherwise, when nothing is running, `.git/deploy-tag`. Mixed or untagged images are an error, never a guess. The record is written after every successful deploy of all app services, rewritten to the restored alias after a revert (running containers still take precedence: one that kept its old container shows its old tag), and cleared by a `--service` deploy that leaves some app services out (they're then on different tags). + +**Manual commands.** With `${DEPLOY_TAG:-latest}`, running ` up -d` on the host with `DEPLOY_TAG` unset would move every service to `:latest`. Use `flow-deploy compose ` (§4.8), which sets `DEPLOY_TAG` to the deployed tag, or have the wrapper default it (§3.1). + +The deployed commit is always available via `git rev-parse HEAD` — the server is kept in detached HEAD at the deployed commit. --- @@ -233,7 +288,7 @@ The tool expects a project directory containing a checked-out Git repository wit └── (application source) ``` -The tool writes no state files to the working tree. The deploy lock is stored at `.git/deploy-lock` (invisible to `git status`). The current deployed SHA is always `git rev-parse HEAD`. +The tool writes no state files to the working tree. The deploy lock is stored at `.git/deploy-lock` and the deployed tag at `.git/deploy-tag` (both invisible to `git status`). The current deployed commit is always `git rev-parse HEAD`. ### 3.1 Compose Command Wrapper @@ -254,14 +309,18 @@ A typical `script/prod`: docker compose -f docker-compose.yml -f docker-compose.prod.yml "$@" ``` -A wrapper that includes image tagging: +A wrapper that keeps manual commands on the deployed tag (§2.8): ```bash #!/usr/bin/env bash -DOCKER_IMAGE_TAG="${DOCKER_IMAGE_TAG:-latest}" \ - docker compose -f docker-compose.yml -f docker-compose.prod.yml "$@" +if [ -z "${DEPLOY_TAG:-}" ] && command -v flow-deploy >/dev/null; then + DEPLOY_TAG=$(flow-deploy tag 2>/dev/null) && export DEPLOY_TAG +fi +docker compose -f docker-compose.yml -f docker-compose.prod.yml "$@" ``` +`flow-deploy` always sets `DEPLOY_TAG` when it calls the wrapper (to a placeholder while looking up the tag), so the default never recurses. + This pattern means the tool is completely agnostic about which compose files exist or how they're layered. The project defines its own composition strategy, and the tool just calls the wrapper with the appropriate subcommand arguments (`pull`, `up`, `stop`, etc.). **All examples in this spec that reference `` refer to whatever this wrapper resolves to.** @@ -290,7 +349,7 @@ flow-deploy deploy [--tag TAG] [--service SERVICE] [--dry-run] | Flag | Description | |---|---| -| `--tag TAG` | Image tag and git ref to deploy (defaults to current HEAD SHA) | +| `--tag TAG` | Image tag and git ref to deploy: a version tag or a commit SHA (defaults to current HEAD SHA) | | `--service SERVICE` | Deploy only a specific service (repeatable) | | `--dry-run` | Show what would happen without executing | @@ -298,9 +357,9 @@ Exit codes: - `0` — all services deployed successfully - `1` — deploy failed (dirty tree, git error, unhealthy service, etc.) and everything it touched was put back - `2` — deploy lock held by another process -- `3` — deploy failed and could not be fully reverted (git restore or a service restore failed); the lock is still released +- `3` — deploy failed and could not be fully reverted (the git restore, a rollback or restore, or a failed service's own cleanup failed); the lock is still released -To deploy a previous version, run `flow-deploy deploy --tag `. The SHA is always a git commit — find it in your CI history or via `git log` on the server. +To deploy a previous version, run `flow-deploy deploy --tag ` (or its SHA). Find it in your CI history, `git tag` on the server, or `flow-deploy status` before deploying. ### 4.2 `flow-deploy status` @@ -310,7 +369,7 @@ Show the current state of all managed services. flow-deploy status ``` -Output includes: current HEAD SHA, service name, role, container ID, image tag, health status. +Output includes: current HEAD SHA, the deployed tag and where it came from (§2.8), and per container: service name, role, container ID, image, health status. ### 4.3 `flow-deploy exec` @@ -352,6 +411,27 @@ flow-deploy upgrade This detects the system's libc (musl or glibc), downloads the latest binary from the GitHub release, and atomically replaces the current binary. Works when run manually on the server or via SSH from a CI pipeline. +### 4.7 `flow-deploy tag` + +Print the deployed tag (§2.8) to stdout, and nothing else, for scripts: + +``` +DEPLOY_TAG=${DEPLOY_TAG:-$(flow-deploy tag)} +``` + +Exits 1 with the reason on stderr when it can't tell (mixed or untagged images, or nothing running and no record). + +### 4.8 `flow-deploy compose` + +Run the compose command (§3.1) with `DEPLOY_TAG` set to the deployed tag, for manual operations on the host: + +``` +flow-deploy compose up -d +flow-deploy compose run --rm web python manage.py migrate +``` + +An explicit `DEPLOY_TAG` in the environment wins. Refuses (exit 1) when the deployed tag can't be told, rather than fall back to `:latest`. The exit code is compose's. + --- ## 5. Deploy Locking @@ -449,6 +529,7 @@ name: Deploy on: push: branches: [main] + tags: ["v*"] env: REGISTRY: ghcr.io @@ -461,7 +542,7 @@ jobs: contents: read packages: write outputs: - tag: ${{ steps.meta.outputs.version }} + tag: ${{ github.ref_type == 'tag' && github.ref_name || github.sha }} steps: - uses: actions/checkout@v4 @@ -471,12 +552,14 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + # The version tag on release pushes, and always the full SHA. - id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE }} tags: | - type=sha,prefix= + type=ref,event=tag + type=sha,format=long,prefix= - uses: docker/build-push-action@v5 with: @@ -614,6 +697,7 @@ The tool has zero configuration files. All behavior is controlled by `x-deploy` | `deploy.port` | No | `x-deploy.port` | SSH port for this service | | `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.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 | @@ -652,7 +736,7 @@ All v1 design decisions are made with the v2 roadmap in mind. Specifically: - The single-command `flow-deploy deploy` is a convenience that runs prepare + health check + cutover in one shot. v2 splits this into discrete phases without breaking the v1 interface. - The `deploy.role` label convention is extensible — v2 adds behavior, not new classification schemes. - The compose command wrapper (§3.1) means the tool never makes assumptions about compose file structure, which keeps it compatible with arbitrarily complex service topologies. -- The tool writes no state to the working tree. The deploy lock lives in `.git/deploy-lock`, and the current deployed SHA is always `git rev-parse HEAD`. v2 adds `.git/deploy-prepare` for two-phase state tracking. +- The tool writes no state to the working tree. The deploy lock lives in `.git/deploy-lock`, the deployed tag in `.git/deploy-tag`, and the current deployed commit is always `git rev-parse HEAD`. v2 adds `.git/deploy-prepare` for two-phase state tracking. - Host discovery via `x-deploy` and `deploy.host` labels (§2.6) gives the GitHub Action enough information to orchestrate multi-host deploys in v1 (sequential) and v2 (two-phase coordinated). --- diff --git a/docs/github-actions.md b/docs/github-actions.md index c6fff92..e4a40d7 100644 --- a/docs/github-actions.md +++ b/docs/github-actions.md @@ -6,9 +6,34 @@ Flow Deploy includes a composite GitHub Action that handles host discovery, GHCR The deploy pipeline: -1. CI builds your Docker image and pushes to GHCR +1. CI builds your Docker image and pushes it to GHCR under the release version (when there is one) and the commit SHA 2. The deploy action discovers hosts from your `docker-compose.yml` -3. For each host: authenticates with GHCR and runs `flow-deploy deploy` (which handles git fetch and checkout internally) +3. For each host: authenticates with GHCR and runs `flow-deploy deploy --tag ` (which handles git fetch and checkout internally) + +## The Image Tag Contract + +The deploy tag is both the git ref checked out on the server and the image tag pulled, so: + +- **Push the image under every tag you deploy by.** Typically the version tag (`v1.4.0`) for releases and the full commit SHA for everything else. `:latest` is optional; flow-deploy never relies on it. +- **Name every app image with `DEPLOY_TAG`**, directly or through `.env`: + +```yaml +# docker-compose.yml +services: + web: + image: ${DOCKER_IMAGE} +``` + +```sh +# .env on the server +DOCKER_IMAGE=ghcr.io/yourorg/yourproject:${DEPLOY_TAG:-latest} +``` + +A bare `DOCKER_IMAGE=ghcr.io/yourorg/yourproject` (no tag) always runs `:latest`, whatever you deploy; flow-deploy warns when it sees that. + +- **Use `flow-deploy compose` for manual commands on the server** (`flow-deploy compose up -d`, `flow-deploy compose run --rm web ...`). With `${DEPLOY_TAG:-latest}`, a plain `docker compose up -d` would move every service to `:latest`; `flow-deploy compose` sets `DEPLOY_TAG` to the deployed tag. Or have `script/prod` default it (see the README's Image Tags section). + +Version tags can be lightweight or annotated, and a re-pushed tag is picked up: flow-deploy runs `git fetch --tags --force`. If a deploy fails, every service goes back to the exact image it was running, whatever it was tagged. ## Prerequisites @@ -41,18 +66,21 @@ cp .env.example .env # Edit with your values ``` -**3. Start the stack:** +**3. Install flow-deploy:** ```sh -docker compose up -d +curl -fsSL https://deploy.flowcanon.com/install | sh ``` -**4. Install flow-deploy:** +**4. Start the stack** at the version you're deploying (with `DEPLOY_TAG` unset, `${DEPLOY_TAG:-latest}` runs `:latest`): ```sh -curl -fsSL https://deploy.flowcanon.com/install | sh +git checkout --detach v1.4.0 +DEPLOY_TAG=v1.4.0 docker compose up -d ``` +Or do the first deploy with flow-deploy itself: `flow-deploy deploy --tag v1.4.0`. + From this point, CI handles all subsequent deploys. ## GitHub Configuration @@ -98,7 +126,7 @@ Use the standalone action from [`flowcanon/deploy-action`](https://github.com/fl | Input | Required | Default | Description | |---|---|---|---| -| `tag` | Yes | — | Image tag to deploy | +| `tag` | Yes | — | Tag to deploy: the version tag, or the commit SHA | | `ssh-key` | Yes | — | SSH private key | | `command` | No | `script/prod` | Compose command | | `host` | No | — | Override deploy host | @@ -108,12 +136,15 @@ Use the standalone action from [`flowcanon/deploy-action`](https://github.com/fl ### Example Workflow +Pushes to `master` deploy by commit SHA; pushing a version tag deploys that version. + ```yaml name: Deploy on: push: branches: [master] + tags: ["v*"] env: IMAGE: ghcr.io/yourorg/yourproject @@ -135,11 +166,14 @@ jobs: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + # The version tag on tag pushes, and always the full SHA. - id: meta uses: docker/metadata-action@v5 with: images: ${{ env.IMAGE }} - tags: type=sha,prefix= + tags: | + type=ref,event=tag + type=sha,format=long,prefix= - uses: docker/build-push-action@v6 with: @@ -149,7 +183,7 @@ jobs: - uses: flowcanon/deploy-action@master with: - tag: ${{ steps.meta.outputs.version }} + tag: ${{ github.ref_type == 'tag' && github.ref_name || github.sha }} ssh-key: ${{ secrets.DEPLOY_SSH_KEY }} host: ${{ vars.HOST_NAME }} user: ${{ vars.HOST_USER }} @@ -157,6 +191,26 @@ jobs: registry-token: ${{ secrets.GITHUB_TOKEN }} ``` +### Release workflows that create the tag + +When a release job creates the version tag itself (for example `salsify/action-detect-and-tag-new-version`, whose `tag` output is empty when no new version was detected), push the image under that tag and the SHA, and deploy by the tag with the SHA as the fallback: + +```yaml + - uses: docker/build-push-action@v6 + with: + push: true + tags: | + ${{ env.IMAGE }}:${{ github.sha }} + ${{ needs.release.outputs.created-tag && format('{0}:{1}', env.IMAGE, needs.release.outputs.created-tag) || '' }} + + - uses: flowcanon/deploy-action@master + with: + tag: ${{ needs.release.outputs.created-tag || github.sha }} + ssh-key: ${{ secrets.DEPLOY_SSH_KEY }} +``` + +The tag must be pushed to the repository before the deploy runs, since flow-deploy fetches it on the server. + ## What the Action Does For each host group discovered from your compose config: @@ -230,5 +284,14 @@ Pass `registry-token: ${{ secrets.GITHUB_TOKEN }}` to the deploy action. The job Install it on the server: `curl -fsSL https://deploy.flowcanon.com/install | sh` Then start a new login shell or run `. ~/.profile`. +**`warning: web's image (...) doesn't use DEPLOY_TAG`:** +The rendered image doesn't end in `:`, so the deploy doesn't change what that service runs. Make the image (or `DOCKER_IMAGE` in `.env`) end in `:${DEPLOY_TAG:-latest}`. + +**`manifest unknown` pulling `:v1.4.0`:** +CI didn't push the image under that tag. Push the version tag as well as the SHA, or deploy by SHA. + +**`can't tell which tag is deployed`** from `flow-deploy tag` or `flow-deploy compose`: +Services run different or untagged images, or nothing is running and no deploy is recorded. Set it explicitly: `DEPLOY_TAG=v1.4.0 flow-deploy compose up -d`. + **Health check timeout:** Increase the timeout via label: `deploy.healthcheck.timeout: 300`. Check that your app's health endpoint responds within the Docker healthcheck interval. diff --git a/src/flow_deploy/cli.py b/src/flow_deploy/cli.py index 251ac69..0f92bb0 100644 --- a/src/flow_deploy/cli.py +++ b/src/flow_deploy/cli.py @@ -7,7 +7,7 @@ from flow_deploy import __version__, compose from flow_deploy import deploy as deploy_mod -from flow_deploy import discovery, log, process +from flow_deploy import deployed, discovery, log, process @click.group() @@ -31,7 +31,8 @@ def deploy(tag, service, dry_run): def status(): """Show current state of all managed services.""" try: - compose_dict = compose.compose_config() + compose_dict = compose.compose_config(env={"DEPLOY_TAG": deployed.LOOKUP_PLACEHOLDER}) + tag, how = deployed.current() except RuntimeError as e: log.error(str(e)) sys.exit(1) @@ -42,6 +43,7 @@ def status(): current_sha = git.current_sha() log.info(f"Current SHA: {current_sha[:7] if current_sha else '(none)'}") + log.info(f"Deployed tag: {tag} (from {how})" if tag else f"Deployed tag: unknown ({how})") log.info("") for svc in all_services: @@ -57,6 +59,53 @@ def status(): log.info(f" {svc.name} ({svc.role}) no containers") +@main.command(name="tag") +def tag_cmd(): + """Print the image tag deployed on this host. + + From the running app containers when they agree, else the last deploy's + record. For scripts: DEPLOY_TAG=${DEPLOY_TAG:-$(flow-deploy tag)}. + """ + try: + tag, how = deployed.current() + except RuntimeError as e: + log.error(str(e)) + sys.exit(1) + if tag is None: + log.error(f"can't tell which tag is deployed: {how}") + sys.exit(1) + click.echo(tag) + + +@main.command( + name="compose", + context_settings={"ignore_unknown_options": True, "allow_interspersed_args": False}, +) +@click.argument("args", nargs=-1, type=click.UNPROCESSED) +def compose_cmd(args): + """Run compose with DEPLOY_TAG set to the deployed tag. + + For manual commands on the host (up -d, run --rm, ...), so they keep the + deployed version instead of moving services to :latest. An explicit + DEPLOY_TAG in the environment wins. + """ + import os + + command = compose.resolve_command() + tag = os.environ.get("DEPLOY_TAG") + if not tag: + try: + tag, how = deployed.current(command) + except RuntimeError as e: + log.error(str(e)) + sys.exit(1) + if tag is None: + log.error(f"can't tell which tag is deployed: {how}") + sys.exit(1) + click.echo(f"DEPLOY_TAG={tag} (from {how})", err=True) + sys.exit(process.run_streaming(command + list(args), env={"DEPLOY_TAG": tag})) + + @main.command(name="exec", context_settings={"ignore_unknown_options": True}) @click.argument("service") @click.argument("command", nargs=-1, type=click.UNPROCESSED) diff --git a/src/flow_deploy/compose.py b/src/flow_deploy/compose.py index d6be5a7..5878972 100644 --- a/src/flow_deploy/compose.py +++ b/src/flow_deploy/compose.py @@ -32,10 +32,17 @@ def compose_run( return process.run(command + args, env=env) -def compose_config(cmd: list[str] | None = None) -> dict: - """Run config and parse YAML output.""" +def compose_config(cmd: list[str] | None = None, env: dict[str, str] | None = None) -> dict: + """Run config and parse YAML output. + + ``env`` (e.g. DEPLOY_TAG) applies while compose interpolates, so the + rendered images show what a deploy with it would run. + """ command = cmd or resolve_command() - result = process.run(command + ["config"]) + if env: + result = process.run(command + ["config"], env=env) + else: + result = process.run(command + ["config"]) if result.returncode != 0: raise RuntimeError(f"compose config failed: {result.stderr}") return yaml.safe_load(result.stdout) diff --git a/src/flow_deploy/containers.py b/src/flow_deploy/containers.py index 61b2713..fb0ab41 100644 --- a/src/flow_deploy/containers.py +++ b/src/flow_deploy/containers.py @@ -1,6 +1,7 @@ """Docker inspect, identify old/new, stop/rm.""" import json +import os from flow_deploy import process @@ -20,7 +21,8 @@ def list_containers_for_service( """Like get_containers_for_service, but None when docker ps fails. For callers that must not mistake "couldn't list" for "nothing running". - ``statuses`` are OR'd docker ps status filters. + ``statuses`` are OR'd docker ps status filters. A status filter matches + stopped containers too (exited, created) without ``--all``. """ filters = ["--filter", f"label=com.docker.compose.service={service}"] if project: @@ -39,6 +41,36 @@ def list_containers_for_service( return containers +def other_projects_here(project: str) -> set[str] | None: + """Compose projects other than ``project`` with running containers in this directory. + + Read from compose's working_dir label. None if docker ps fails. + """ + cwd = os.getcwd() + dirs = {cwd} + # The shell's path for the same directory, if it went through a symlink. + # PWD is inherited, so it only counts when it really is this directory. + pwd = os.environ.get("PWD", "") + if pwd and os.path.realpath(pwd) == os.path.realpath(cwd): + dirs.add(pwd) + found = set() + for d in sorted(dirs): + result = process.run( + [ + "docker", + "ps", + "--filter", + f"label=com.docker.compose.project.working_dir={d}", + "--format", + '{{.Label "com.docker.compose.project"}}', + ] + ) + if result.returncode != 0: + return None + found |= {line.strip() for line in result.stdout.splitlines() if line.strip()} + return found - {project} + + def identify_old_new(containers: list[dict], new_tag: str) -> tuple[dict | None, dict | None]: """Identify old and new containers by image tag. @@ -99,3 +131,47 @@ def remove_container(container_id: str) -> bool: """Remove a container. Returns True on success.""" result = process.run(["docker", "rm", container_id]) return result.returncode == 0 + + +def image_tag(image: str) -> str | None: + """The tag of ``registry/name:tag[@digest]``, or None when there's no tag. + + A bare image ID (``sha256:...``) has no tag. + """ + if image.startswith("sha256:"): + return None + name = image.rsplit("/", 1)[-1].split("@", 1)[0] + return name.rsplit(":", 1)[1] if ":" in name else None + + +def image_repo(image: str) -> str: + """``registry/name`` of ``registry/name:tag[@digest]`` (the registry may have a port).""" + image = image.split("@", 1)[0] + head, _, last = image.rpartition("/") + name = last.split(":", 1)[0] + return f"{head}/{name}" if head else name + + +def image_ids(container_ids: list[str]) -> dict[str, str] | None: + """Each container's image ID (``sha256:...``), keyed by the IDs given. + + Accepts docker ps's short IDs. None if docker inspect fails. + """ + if not container_ids: + return {} + result = process.run(["docker", "inspect", "--format", "{{.Id}} {{.Image}}", *container_ids]) + if result.returncode != 0: + return None + full = dict(line.split() for line in result.stdout.splitlines() if len(line.split()) == 2) + found = {} + for short in container_ids: + match = next((img for cid, img in full.items() if cid.startswith(short)), None) + if match is None: + return None + found[short] = match + return found + + +def tag_image(image_id: str, ref: str) -> bool: + """Point the local tag ``ref`` at ``image_id``. Returns True on success.""" + return process.run(["docker", "tag", image_id, ref]).returncode == 0 diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index db04b05..774fd2a 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -2,10 +2,11 @@ import signal import time +from collections import Counter from contextlib import contextmanager from dataclasses import dataclass, field -from flow_deploy import compose, config, containers, git, lock, log +from flow_deploy import compose, config, containers, deployed, git, lock, log EXIT_OK = 0 EXIT_FAILED = 1 # failed; everything it touched was put back @@ -62,13 +63,14 @@ def hold(signum, frame): @dataclass -class Drained: - """What a drain-first service was running before its drain.""" +class Previous: + """What an app service was running when the deploy started.""" svc: config.ServiceConfig replicas: int = 0 - old_tag: str | None = None - old_image: str = "" + image_id: str = "" # the image its containers ran (the most common, if mixed) + image_ref: str = "" # how docker named it: repo:tag, repo@digest, ... + restore_tag: str | None = None # a DEPLOY_TAG that brings image_id back @dataclass @@ -76,33 +78,54 @@ class _Run: """What a deploy has changed so far, so any failure can put it back.""" compose_cmd: list[str] + project: str = "" previous_sha: str | None = None - drained: list[Drained] = field(default_factory=list) - started: set[str] = field(default_factory=set) # drain-first, healthy on the new tag - - def revert(self, reason: str, down: list[Drained] | None = None) -> int: - """Put things back as they were before the deploy. - - Restores the repo and brings ``down`` (by default every drained - service not yet healthy on the new tag) back on the tags they ran. - Expand-then-contract migrations keep old code compatible with the new - schema, as rolling deploys already assume. Exits 3 only when - something can't be put back. + previous: dict[str, Previous] = field(default_factory=dict) + drained: list[str] = field(default_factory=list) # drain-first services touched + shipped: list[str] = field(default_factory=list) # rolling services deployed + aborted: str | None = None # the rolling service whose own abort kept its old container + whole_project: bool = True # every app service is in this deploy + + def revert(self, reason: str) -> int: + """Put everything back as it was before the deploy. + + Restores the repo, rolls shipped rolling services back to the image + each was running (newest change first), then brings every drained + service back on its previous image in deploy order. What was running + comes from the containers themselves (see _snapshot), not git or + ``:latest``. Expand-then-contract migrations keep old code compatible + with the new schema, as rolling deploys already assume. Exits 3 only + when something can't be put back. """ # Don't let a further signal cut the revert short (or start a second one). for signum in HANDLED_SIGNALS: signal.signal(signum, signal.SIG_IGN) - if down is None: - down = [r for r in self.drained if r.svc.name not in self.started] log.info("") problems = [] if self.previous_sha is not None and not git.restore(self.previous_sha): problems.append("git restore failed") - if not _restore_drained(down, self.compose_cmd): + if self.aborted and not _remove_stopped(self.previous[self.aborted].svc, self.project): + # A new container its abort stopped but couldn't remove: the next + # deploy's `compose up --scale` would restart it. + problems.append(f"{self.aborted}'s stopped new container could not be removed") + for name in reversed(self.shipped): + if not _roll_back(self.previous[name], self.compose_cmd, self.project): + problems.append(f"{name} could not be rolled back") + restore = [self.previous[name] for name in self.drained] + if not _restore_drained(restore, self.compose_cmd, self.project): problems.append("drained services could not be restored") + self._record_previous_tag() log.footer(f"FAILED ({reason})") return _degraded(", ".join(problems)) if problems else EXIT_FAILED + def _record_previous_tag(self) -> None: + """After a revert, record the previous tag if every service shared one.""" + tags = {p.restore_tag for p in self.previous.values() if p.replicas} + if self.whole_project and len(tags) == 1 and None not in tags: + deployed.write(tags.pop(), self.previous_sha or "") + elif self.previous: + deployed.clear() + def deploy( tag: str | None = None, @@ -122,7 +145,7 @@ def deploy( if dry_run: # Dry run: just parse config from current checkout, no git or lock try: - compose_dict = compose.compose_config(cmd=compose_cmd) + compose_dict = compose.compose_config(cmd=compose_cmd, env={"DEPLOY_TAG": tag}) except RuntimeError as e: log.error(str(e)) return EXIT_FAILED @@ -185,9 +208,10 @@ def _deploy_locked( if git_code != 0: return EXIT_FAILED - # Parse compose config (now reading from the target commit) + # Parse compose config (now reading from the target commit), rendered with + # this deploy's tag so each image shows what will run. try: - compose_dict = compose.compose_config(cmd=run.compose_cmd) + compose_dict = compose.compose_config(cmd=run.compose_cmd, env={"DEPLOY_TAG": tag}) except RuntimeError as e: log.error(str(e)) return EXIT_FAILED if git.restore(run.previous_sha) else _degraded("git restore failed") @@ -195,17 +219,40 @@ def _deploy_locked( app_services = _resolve_app_services(compose_dict, services_filter) if app_services is None: return EXIT_FAILED if git.restore(run.previous_sha) else _degraded("git restore failed") + all_apps = [s for s in config.parse_services(compose_dict) if s.is_app] + run.whole_project = len(app_services) == len(all_apps) service_names = ", ".join(s.name for s in app_services) log.header("deploy") log.info(f"tag: {tag}") log.info(f"services: {service_names}") log.info("") + _warn_untagged_images(app_services, tag) - project = compose_dict.get("name", "") + run.project = compose_dict.get("name", "") + project = run.project compose_cmd = run.compose_cmd start_time = time.time() + # A release that renames the compose project would start a second stack + # beside the running one, and snapshot (so revert) nothing. + others = containers.other_projects_here(project) + if others is None: + log.error("could not list this directory's containers; nothing was changed") + elif others: + log.error( + f"containers from compose project(s) {', '.join(sorted(others))} are running " + f"in this directory, but this commit's project is {project or '(unnamed)'}; " + "a project rename can't be deployed in place. Nothing was changed." + ) + if others is None or others: + return EXIT_FAILED if git.restore(run.previous_sha) else _degraded("git restore failed") + + # Before changing anything, record what each service is running, so any + # failure can put back exactly that image. + if not _snapshot(run, app_services): + return EXIT_FAILED if git.restore(run.previous_sha) else _degraded("git restore failed") + # app_services is in deploy.order. Services start in that order and stop # in reverse, so a worker comes up after the web and API it depends on, # and drains before them. @@ -213,15 +260,14 @@ def _deploy_locked( rolling = [s for s in app_services if not s.drains_first] dirty = [] # services whose own failure cleanup also failed - def failed(reason: str, down: list[Drained] | None = None) -> int: - code = run.revert(reason, down) + def failed(reason: str) -> int: + code = run.revert(reason) if dirty and code == EXIT_FAILED: return _degraded(f"cleanup failed for {', '.join(dirty)}") return code # Phase 1: drain-first services stop, in reverse deploy order, before - # anything rolls, so none of their old code runs beside new code. What - # each one was running is kept to bring it back on failure. + # anything rolls, so none of their old code runs beside new code. for svc in reversed(drain_first): if _drain_service(svc, tag, compose_cmd, run.drained, project=project) != 0: return failed("deploy aborted") @@ -231,28 +277,39 @@ def failed(reason: str, down: list[Drained] | None = None) -> int: result = _deploy_service(svc, tag, compose_cmd, project=project) if result == SVC_DIRTY: dirty.append(svc.name) + if result != SVC_OK and run.previous[svc.name].replicas: + run.aborted = svc.name + return failed("deploy aborted") # its abort left the old container serving + run.shipped.append(svc.name) if result != SVC_OK: + # Nothing ran before, so whatever the failed rollout left goes too. return failed("deploy aborted") # Phase 3: drain-first services start in deploy order, at the replica # count they ran. One that wasn't running (just added in this release, # or crashed) starts at 1: a deploy brings its services up. Every one is - # attempted, so one failure doesn't strand the rest; a failed one goes - # back to what it ran before. - by_name = {record.svc.name: record for record in run.drained} + # attempted, so one failure doesn't strand the rest; any failure reverts + # the whole deploy. failures = [] for svc in drain_first: - record = by_name[svc.name] - result = _start_service(svc, tag, compose_cmd, max(record.replicas, 1), project=project) - if result == SVC_OK: - run.started.add(svc.name) - continue + replicas = max(run.previous[svc.name].replicas, 1) + result = _start_service(svc, tag, compose_cmd, replicas, project=project) if result == SVC_DIRTY: dirty.append(svc.name) - failures.append(record) + if result != SVC_OK: + failures.append(svc.name) if failures: - names = ", ".join(r.svc.name for r in failures) - return failed(f"{names} failed to start", failures) + return failed(f"{', '.join(failures)} failed to start") + + if run.whole_project: + deployed.write(tag) + else: + # Services now run different tags; no one tag describes the host. + deployed.clear() + log.warning( + "--service deployed only some app services; manual compose commands " + "on this host need DEPLOY_TAG set explicitly until a full deploy" + ) elapsed = time.time() - start_time @@ -262,6 +319,83 @@ def failed(reason: str, down: list[Drained] | None = None) -> int: return EXIT_OK +def _warn_untagged_images(services: list[config.ServiceConfig], tag: str) -> None: + """Warn about app images that don't follow DEPLOY_TAG. + + Such an image deploys whatever its fixed reference names (often + ``:latest``, possibly an unreleased build), and a revert can't target the + previous version. + """ + for svc in services: + if svc.image and containers.image_tag(svc.image) != tag: + log.warning( + f"{svc.name}'s image ({svc.image}) doesn't use DEPLOY_TAG, so this " + "deploy runs whatever it names and a revert can't target the previous " + "version. Name it repo:${DEPLOY_TAG:-latest}." + ) + + +def _snapshot(run: _Run, services: list[config.ServiceConfig]) -> bool: + """Record what each service is running on ``run.previous``. False if Docker can't say. + + Each running image gets a restore tag that names exactly it (see + _restore_tag); services sharing an image share one. + """ + aliases: dict[tuple[tuple[str, ...], str], str | None] = {} + for svc in services: + ctrs = containers.list_containers_for_service( + svc.name, project=run.project, statuses=("running", "restarting") + ) + ids = containers.image_ids([c["ID"] for c in ctrs]) if ctrs is not None else None + if ids is None: + log.error(f"could not inspect {svc.name}'s containers; nothing was changed") + return False + prev = Previous(svc, replicas=len(ctrs)) + if ctrs: + counts = Counter(ids[c["ID"]] for c in ctrs) + prev.image_id = counts.most_common(1)[0][0] + prev.image_ref = next(c.get("Image", "") for c in ctrs if ids[c["ID"]] == prev.image_id) + if len(counts) > 1: + log.warning( + f"{svc.name} is running {len(counts)} different images; a revert " + f"restores the most common, {prev.image_ref}" + ) + # A revert renders the previous commit's compose file, whose image + # repo the running container's name records. The new config's repo + # covers a container whose tag has moved (docker ps shows an ID). + repos = {containers.image_repo(svc.image or "")} + if containers.image_tag(prev.image_ref) is not None or "@" in prev.image_ref: + repos.add(containers.image_repo(prev.image_ref)) + key = (tuple(sorted(repos)), prev.image_id) + if key not in aliases: + aliases[key] = _restore_tag(*key) + prev.restore_tag = aliases[key] + if prev.restore_tag is None: + # Never start a deploy that already can't be reverted exactly. + log.error( + f"could not tag {svc.name}'s running image ({prev.image_ref}) " + "for a revert; nothing was changed" + ) + return False + run.previous[svc.name] = prev + return True + + +def _restore_tag(repos: tuple[str, ...], image_id: str) -> str | None: + """A DEPLOY_TAG that names exactly ``image_id``: a local alias of it. + + ``repo:flow-deploy-`` in each of ``repos``, created now, before + anything changes. A revert then restores the image that was running, never + whatever ``:latest`` or a re-pushed tag has since come to mean, and it + works the same whether the container ran a version tag, a sha, ``:latest``, + a digest, or nothing nameable at all. + """ + alias = "flow-deploy-" + image_id.removeprefix("sha256:") + if all(repos) and all(containers.tag_image(image_id, f"{r}:{alias}") for r in repos): + return alias + return None + + def _degraded(problem: str) -> int: log.error( f"Deploy failed and could not be fully reverted ({problem}). " @@ -321,32 +455,21 @@ def _pull(svc: config.ServiceConfig, env: dict, compose_cmd: list[str]) -> bool: return True -def _image_tag(image: str) -> str | None: - """The tag of ``registry/name:tag[@digest]``, or None when there's no tag. - - A bare image ID (``sha256:...``) has no tag. - """ - if image.startswith("sha256:"): - return None - name = image.rsplit("/", 1)[-1].split("@", 1)[0] - return name.rsplit(":", 1)[1] if ":" in name else None - - def _drain_service( svc: config.ServiceConfig, tag: str, compose_cmd: list[str], - drained: list[Drained], + drained: list[str], project: str = "", ) -> int: """Pull the new image, then stop and remove the running containers. - Pulls first so an unpullable tag fails before anything stops. Records - what was running on ``drained`` *before* stopping anything, so a signal - mid-drain (a drain can take as long as the service's longest task) still - knows what to restore. Returns 1 if the pull failed or any container - failed to stop or be removed: the caller must not roll anything while old - code may still be running. + Pulls first so an unpullable tag fails before anything stops. Adds the + service to ``drained`` *before* stopping anything, so a signal mid-drain + (a drain can take as long as the service's longest task) still restores + it. Returns 1 if the pull failed or any container failed to stop or be + removed: the caller must not roll anything while old code may still be + running. """ log.service_start(svc.name) svc_start = time.time() @@ -366,17 +489,7 @@ def _drain_service( log.failure(f"could not list {svc.name} containers; not draining blind") log.service_end() return 1 - images = list(dict.fromkeys(c.get("Image", "") for c in ctrs)) - record = Drained(svc, replicas=len(ctrs)) - if images: - record.old_image = images[0] - record.old_tag = _image_tag(images[0]) - drained.append(record) - if len(images) > 1: - log.error( - f"{svc.name} was running mixed images ({', '.join(images)}); " - f"a rollback restores {images[0]}" - ) + drained.append(svc.name) if not ctrs: log.step("not running; nothing to drain") @@ -476,43 +589,125 @@ def _remove_all(ctrs: list[dict], timeout: int) -> bool: return ok -def _restore_drained(drained: list[Drained], compose_cmd: list[str]) -> bool: - """Bring drained services back as they were, in deploy (start) order. +def _remove_stopped(svc: config.ServiceConfig, project: str, keep_image: str | None = None) -> bool: + """Remove ``svc``'s stopped leftovers (a stop that worked, then an rm that didn't). - Returns False if any couldn't be. + `compose up --scale` starts stopped containers before creating new ones, + so a revert would otherwise bring back whatever image a leftover has. + Leftovers on ``keep_image`` are kept: restarting one restores that image. """ + stopped = containers.list_containers_for_service( + svc.name, project=project, statuses=("created", "exited", "dead") + ) + ids = containers.image_ids([c["ID"] for c in stopped]) if stopped is not None else None + if ids is None: + log.failure(f"cannot revert {svc.name}: its stopped containers can't be inspected") + return False ok = True - for record in sorted(drained, key=lambda r: (r.svc.order, r.svc.file_order)): - name = record.svc.name - if not record.replicas: - log.step(f"{name} was not running before the deploy; leaving it stopped") - continue - if record.old_tag is None: - log.failure( - f"cannot restore {name}: no tag in its previous image " - f"({record.old_image or 'unknown'}); start it manually" - ) + for ctr in [c for c in stopped if keep_image is None or ids[c["ID"]] != keep_image]: + if not containers.remove_container(ctr["ID"]): + log.failure(f"could not remove stopped {svc.name} container {ctr['ID'][:7]}") + ok = False + return ok + + +def _roll_back(prev: Previous, compose_cmd: list[str], project: str) -> bool: + """Put a shipped rolling service back on the image it was running. + + A rolling deploy of the previous image (already local, so no pull): no + downtime. A service that had no container before the deploy goes back to + having none. + """ + svc = prev.svc + if not _remove_stopped(svc, project): + return False + ctrs = containers.list_containers_for_service( + svc.name, project=project, statuses=("running", "restarting") + ) + ids = containers.image_ids([c["ID"] for c in ctrs]) if ctrs is not None else None + if ids is None: + log.failure(f"cannot roll {svc.name} back: its containers can't be inspected") + return False + if not prev.replicas: + log.step(f"{svc.name} had no container before the deploy; removing the new one") + return _remove_all(ctrs, timeout=svc.drain) + newer = [c for c in ctrs if ids[c["ID"]] != prev.image_id] + if len(newer) < len(ctrs): + # The cutover's cleanup failed, so the previous image still runs beside + # the new one. A rolling deploy can't tell them apart by tag here. + log.step(f"{svc.name} still runs its previous image; removing the new container(s)") + return _remove_all(newer, timeout=svc.drain) and _scale_to_previous(prev, compose_cmd) + log.step(f"rolling {svc.name} back to {prev.restore_tag}...") + return ( + _deploy_service(svc, prev.restore_tag, compose_cmd, project=project, pull=False) == SVC_OK + ) + + +def _restore_drained(previous: list[Previous], compose_cmd: list[str], project: str) -> bool: + """Bring drained services back to what they ran, in deploy (start) order. + + Drains any new containers first (with each service's drain timeout), then + starts the previous image at its previous replica count. Returns False if + any couldn't be put back. + """ + ok = True + for prev in sorted(previous, key=lambda p: (p.svc.order, p.svc.file_order)): + svc = prev.svc + if not _remove_stopped(svc, project, keep_image=prev.image_id): ok = False continue - log.step(f"restoring {name} on {record.old_tag} ({record.replicas} replica(s))...") - result = compose.compose_run( - ["up", "-d", "--no-deps", "--scale", f"{name}={record.replicas}", name], - env={"DEPLOY_TAG": record.old_tag}, - cmd=compose_cmd, + ctrs = containers.list_containers_for_service( + svc.name, project=project, statuses=("running", "restarting") ) - if result.returncode != 0: - log.failure(f"could not restore {name}: {result.stderr.strip()}") + ids = containers.image_ids([c["ID"] for c in ctrs]) if ctrs is not None else None + if ids is None: + log.failure(f"cannot restore {svc.name}: its containers can't be inspected") ok = False + continue + newer = [c for c in ctrs if ids[c["ID"]] != prev.image_id] + if newer: + log.step(f"draining {len(newer)} new {svc.name} container(s)...") + if not _remove_all(newer, timeout=svc.drain): + ok = False + continue + if not prev.replicas: + log.step(f"{svc.name} was not running before the deploy; leaving it stopped") + continue + log.step(f"restoring {svc.name} on {prev.restore_tag} ({prev.replicas} replica(s))...") + ok = _scale_to_previous(prev, compose_cmd) and ok return ok +def _scale_to_previous(prev: Previous, compose_cmd: list[str]) -> bool: + """Bring ``prev.svc`` to its previous replica count on its previous image. + + --no-recreate: containers already on that image are kept, never replaced. + """ + svc = prev.svc + result = compose.compose_run( + ["up", "-d", "--no-deps", "--no-recreate", "--scale", f"{svc.name}={prev.replicas}"] + + [svc.name], + env={"DEPLOY_TAG": prev.restore_tag}, + cmd=compose_cmd, + ) + if result.returncode != 0: + log.failure(f"could not restore {svc.name}: {result.stderr.strip()}") + return result.returncode == 0 + + def _deploy_service( - svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" + svc: config.ServiceConfig, + tag: str, + compose_cmd: list[str], + project: str = "", + pull: bool = True, ) -> int: """Deploy a single service with a rolling cutover. - Returns SVC_OK, SVC_FAILED (old container still serving, nothing left - behind), or SVC_DIRTY (failed, and cleaning up after itself failed too). + ``pull=False`` for a rollback to an image that's already local (and may + be a local alias the registry doesn't have). Returns SVC_OK, SVC_FAILED + (old container still serving, nothing left behind), or SVC_DIRTY + (failed, and cleaning up after itself failed too). """ log.service_start(svc.name) svc_start = time.time() @@ -524,7 +719,7 @@ def end(code: int) -> int: return code # 1. Pull - if not _pull(svc, env, compose_cmd): + if pull and not _pull(svc, env, compose_cmd): return end(SVC_FAILED) # 2. Scale to 2 @@ -575,12 +770,15 @@ def end(code: int) -> int: log.step(f"draining old container ({old_id[:7]}, {svc.drain}s timeout)...") clean = containers.stop_container(old_id, timeout=svc.drain) clean = containers.remove_container(old_id) and clean - clean = _scale_back(svc.name, env, compose_cmd) and clean + # Scale back only once the old container is gone: with two left, it + # can only remove one, and compose might pick the new one. + clean = clean and _scale_back(svc.name, env, compose_cmd) if not clean: # The new container is healthy and serving, so the deploy # succeeded, as on master. A stop/rm failure here is usually the # old container having already exited; failing would revert the - # repo underneath a healthy new container. + # repo underneath a healthy new container. If it's still running, + # a later revert keeps it (_roll_back). log.step(f"warning: cleanup of old container {old_id[:7]} did not complete") elapsed = time.time() - svc_start @@ -591,7 +789,9 @@ def end(code: int) -> int: log.step(f"aborting: stopping new container ({new_id[:7]})...") clean = containers.stop_container(new_id) clean = containers.remove_container(new_id) and clean - clean = _scale_back(svc.name, env, compose_cmd) and clean + # As above: with the new container still there, scale back might + # remove the old one instead. + clean = clean and _scale_back(svc.name, env, compose_cmd) if clean: log.step("aborted, old container still serving") else: diff --git a/src/flow_deploy/deployed.py b/src/flow_deploy/deployed.py new file mode 100644 index 0000000..5f49242 --- /dev/null +++ b/src/flow_deploy/deployed.py @@ -0,0 +1,86 @@ +"""Which image tag is deployed on this host. + +A compose file that names its images ``repo:${DEPLOY_TAG:-latest}`` resolves to +``:latest`` whenever DEPLOY_TAG isn't set, so a manual ``compose up`` on the +host would quietly recreate services onto ``:latest``. ``current()`` answers +"what's deployed" so manual commands can use it: ``flow-deploy tag`` prints it +and ``flow-deploy compose ...`` runs compose with it. + +The answer comes from the running app containers when they all agree, then +from the record of the last deploy (``.git/deploy-tag``, written by +flow-deploy) when nothing is running. Mixed or untagged images are an +explicit "don't know", never a guess. +""" + +import json +import os +import time + +from flow_deploy import compose, config, containers + +RECORD = ".git/deploy-tag" +# Rendered into DEPLOY_TAG while looking up the tag, so a compose wrapper that +# defaults DEPLOY_TAG from `flow-deploy tag` doesn't call back into us forever. +LOOKUP_PLACEHOLDER = "flow-deploy-lookup" + + +def write(tag: str, sha: str = "") -> None: + with open(RECORD, "w") as f: + json.dump({"tag": tag, "sha": sha, "timestamp": time.time()}, f) + + +def clear() -> None: + if os.path.exists(RECORD): + os.remove(RECORD) + + +def read() -> dict | None: + try: + with open(RECORD) as f: + data = json.load(f) + except (OSError, ValueError): + return None + return data if isinstance(data, dict) and data.get("tag") else None + + +def current(compose_cmd: list[str] | None = None) -> tuple[str | None, str]: + """(tag, where it came from), or (None, why it can't be told). + + Raises RuntimeError if compose config or docker ps fails: "couldn't + look" must not fall through to the record as if nothing were running. + """ + compose_dict = compose.compose_config(cmd=compose_cmd, env={"DEPLOY_TAG": LOOKUP_PLACEHOLDER}) + project = compose_dict.get("name", "") + apps = [s for s in config.parse_services(compose_dict) if s.is_app] + tags = {} + ids = [] + for svc in apps: + ctrs = containers.list_containers_for_service( + svc.name, project=project, statuses=("running", "restarting") + ) + if ctrs is None: + raise RuntimeError(f"could not list {svc.name} containers (docker ps failed)") + for ctr in ctrs: + tags.setdefault(containers.image_tag(ctr.get("Image", "")), []).append(svc.name) + ids.append(ctr["ID"]) + if len(tags) == 1 and None not in tags: + return next(iter(tags)), "running containers" + if len(tags) > 1 and None not in tags: + # After a revert, a recreated service runs the flow-deploy- alias of + # the image a kept container still runs under its old tag: one image, + # two names. The alias names it exactly, so it answers. + images = containers.image_ids(ids) + if images is None: + raise RuntimeError("could not inspect the app containers (docker inspect failed)") + aliases = sorted(t for t in tags if t.startswith("flow-deploy-")) + if len(set(images.values())) == 1 and aliases: + return aliases[0], "running containers (one image under several tags)" + if tags: + seen = ", ".join( + f"{t or 'untagged'} ({', '.join(sorted(set(s)))})" for t, s in tags.items() + ) + return None, f"app services run different or untagged images: {seen}; set DEPLOY_TAG" + record = read() + if record: + return record["tag"], "last deploy record" + return None, "nothing is running and no deploy is recorded; set DEPLOY_TAG" diff --git a/src/flow_deploy/git.py b/src/flow_deploy/git.py index ab1e560..27c0936 100644 --- a/src/flow_deploy/git.py +++ b/src/flow_deploy/git.py @@ -10,8 +10,12 @@ def is_dirty() -> bool: def fetch() -> process.Result: - """Fetch from origin.""" - return process.run(["git", "fetch", "origin"]) + """Fetch from origin, including every tag. + + --tags fetches release tags even when they aren't on a fetched branch; + --force updates a tag that was moved and re-pushed instead of refusing. + """ + return process.run(["git", "fetch", "--tags", "--force", "origin"]) def current_sha() -> str: diff --git a/src/flow_deploy/log.py b/src/flow_deploy/log.py index 8ce67f6..285d64e 100644 --- a/src/flow_deploy/log.py +++ b/src/flow_deploy/log.py @@ -68,6 +68,12 @@ def failure(msg: str) -> None: info(f" ✗ {msg}") +def warning(msg: str) -> None: + if _is_github_actions(): + _write(f"::warning::{msg}") + _write(f"[{_timestamp()}] WARNING: {msg}", stream=sys.stderr) + + def error(msg: str) -> None: if _is_github_actions(): _write(f"::error::{msg}") diff --git a/tests/fake_host.py b/tests/fake_host.py new file mode 100644 index 0000000..4d6cf31 --- /dev/null +++ b/tests/fake_host.py @@ -0,0 +1,297 @@ +"""A fake Docker host for unit tests. + +Answers the docker, compose, and git commands flow-deploy runs from in-memory +state, so a test declares what's running and what should fail, runs a deploy, +and asserts on the outcome instead of on the exact sequence of calls: + + host = FakeHost(compose, running={"web": ["v1"], "worker": ["v1", "v1"]}) + host.unhealthy.add("v2") + host.install(monkeypatch) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running() == {"web": ["v1"], "worker": ["v1", "v1"]} + +Failures are injected by substring: host.fail("docker stop old_") fails every +docker stop whose command line contains that text. +""" + +import hashlib +import itertools +import json +from dataclasses import dataclass + +import yaml + +from flow_deploy import process + +COMPOSE_CMD = ["docker", "compose"] +REPO = "ghcr.io/myorg/myapp" + + +def image_id_for(tag: str) -> str: + return "sha256:" + hashlib.sha256(tag.encode()).hexdigest() + + +@dataclass +class Ctr: + id: str + service: str + tag: str # the DEPLOY_TAG it was created from + image_id: str + created: int + state: str = "running" + ref: str = "" # what docker ps shows as Image; defaults to REPO:tag + + +def ok(out: str = "") -> process.Result: + return process.Result(0, out, "") + + +def fail(msg: str = "injected failure") -> process.Result: + return process.Result(1, "", msg) + + +class FakeHost: + def __init__(self, compose: dict, running: dict | None = None, project: str = "proj"): + self.compose = compose + self.project = project + self.sha = "prev123abc" + self.dirty = False + self.ctrs: list[Ctr] = [] + self.images: dict[str, str] = {} # tags known locally or in the registry -> image id + self.unpullable: set[str] = set() # tags compose pull can't fetch + self.unhealthy: set[str] = set() # tags whose containers never become healthy + self.unhealthy_services: set[tuple[str, str]] = set() # (service, tag) pairs + self.stuck: set[str] = set() # services whose compose up succeeds but changes nothing + self.same_created = False # docker ps shows one CreatedAt for every container + self.other_projects: list[str] = [] # other compose projects running in this dir + self.failures: list[list] = [] # [substring, skip, remaining or None] + self.hooks: list[tuple[str, object]] = [] # (substring, callback) run before a command + self.calls: list[list[str]] = [] + self.envs: list[dict | None] = [] + self.new_sessions: list[list[str]] = [] + self._ids = itertools.count(1) + self._clock = itertools.count(1) + for service, tags in (running or {}).items(): + for tag in tags: + self.add(service, tag) + + # -- setup ------------------------------------------------------------- + + def add(self, service: str, tag: str, ref: str | None = None, state: str = "running") -> Ctr: + image_id = self.images.setdefault(tag, image_id_for(tag)) + ctr = Ctr( + id=f"{service}{next(self._ids):03d}", + service=service, + tag=tag, + image_id=image_id, + created=next(self._clock), + state=state, + ref=ref or f"{REPO}:{tag}", + ) + self.ctrs.append(ctr) + return ctr + + def fail(self, substring: str, times: int | None = None, skip: int = 0) -> None: + """Fail commands containing ``substring``: after ``skip`` matches, ``times`` times.""" + self.failures.append([substring, skip, times]) + + def before(self, substring: str, callback) -> None: + """Run ``callback()`` just before the first command containing ``substring``.""" + self.hooks.append((substring, callback)) + + def install(self, monkeypatch) -> "FakeHost": + monkeypatch.setattr(process, "run", self.run) + monkeypatch.setattr(process, "run_streaming", lambda args, env=None, cwd=None: 0) + monkeypatch.setattr("flow_deploy.deploy.time.sleep", lambda _s: None) + return self + + # -- observation ------------------------------------------------------- + + def running(self) -> dict[str, list[str]]: + """service -> sorted tags of its running containers.""" + out: dict[str, list[str]] = {} + for ctr in self.ctrs: + if ctr.state == "running": + out.setdefault(ctr.service, []).append(ctr.tag) + return {s: sorted(t) for s, t in out.items()} + + def running_images(self) -> dict[str, list[str]]: + """service -> sorted image IDs of its running containers.""" + out: dict[str, list[str]] = {} + for ctr in self.ctrs: + if ctr.state == "running": + out.setdefault(ctr.service, []).append(ctr.image_id) + return {s: sorted(i) for s, i in out.items()} + + def commands(self) -> list[str]: + return [" ".join(args) for args in self.calls] + + def index(self, *needles: str) -> int: + """Position of the first command containing every needle.""" + cmds = self.commands() + return next(i for i, c in enumerate(cmds) if all(n in c for n in needles)) + + # -- the fake ---------------------------------------------------------- + + def run(self, args, env=None, cwd=None, new_session=False): + self.calls.append(list(args)) + self.envs.append(env) + if new_session: + self.new_sessions.append(list(args)) + line = " ".join(args) + for i, (substring, callback) in enumerate(self.hooks): + if substring in line: + self.hooks.pop(i) + callback() + break + for rule in self.failures: + substring, skip, times = rule + if substring in line and times != 0: + if skip: + rule[1] -= 1 + continue + if times is not None: + rule[2] -= 1 + return fail() + tag = (env or {}).get("DEPLOY_TAG", "latest") + if args[:1] == ["git"]: + return self._git(args[1:]) + if args[: len(COMPOSE_CMD)] == COMPOSE_CMD: + return self._compose(args[len(COMPOSE_CMD) :], tag) + if args[:2] == ["docker", "ps"]: + return self._ps(args[2:]) + if args[:2] == ["docker", "inspect"]: + return self._inspect(args[2:]) + if args[:2] == ["docker", "stop"]: + return self._stop(args[-1]) + if args[:2] == ["docker", "rm"]: + return self._rm(args[-1]) + if args[:2] == ["docker", "tag"]: + self.images[args[3].rsplit(":", 1)[1]] = args[2] + return ok() + raise AssertionError(f"FakeHost: unexpected command {line!r}") + + def _git(self, args): + if args[:1] == ["status"]: + return ok(" M file\n" if self.dirty else "") + if args[:1] == ["fetch"]: + return ok() + if args[:1] == ["rev-parse"]: + return ok(self.sha + "\n") + if args[:2] == ["checkout", "--detach"]: + self.sha = args[2] + return ok() + raise AssertionError(f"FakeHost: unexpected git {args}") + + def _compose(self, args, tag): + if args[:1] == ["config"]: + return ok(yaml.safe_dump(self._rendered(tag))) + if args[:1] == ["pull"]: + if tag in self.unpullable: + return fail(f"manifest for {REPO}:{tag} not found") + self.images.setdefault(tag, image_id_for(tag)) + return ok() + if args[:1] == ["up"]: + return self._up(args, tag) + raise AssertionError(f"FakeHost: unexpected compose {args}") + + def _rendered(self, tag): + services = {} + for name, svc in self.compose["services"].items(): + svc = dict(svc) + image = svc.get("image", f"{REPO}:${{DEPLOY_TAG:-latest}}") + svc["image"] = image.replace("${DEPLOY_TAG:-latest}", tag).replace("${DEPLOY_TAG}", tag) + services[name] = svc + return {"name": self.project, "services": services} + + def _live(self, service): + return [ + c for c in self.ctrs if c.service == service and c.state in ("running", "restarting") + ] + + def _up(self, args, tag): + service = args[-1] + replicas = 1 + if "--scale" in args: + replicas = int(args[args.index("--scale") + 1].split("=")[1]) + if tag not in self.images: + return fail(f"No such image: {REPO}:{tag}") + if service in self.stuck: + return ok() + live = self._live(service) + if "--no-recreate" not in args: + for ctr in [c for c in live if c.tag != tag]: + self.ctrs.remove(ctr) + live.remove(ctr) + live.append(self.add(service, tag)) + while len(live) > replicas: # compose removes the newest extras + newest = max(live, key=lambda c: c.created) + self.ctrs.remove(newest) + live.remove(newest) + # Like compose, start stopped containers before creating new ones. + stopped = [c for c in self.ctrs if c.service == service and c.state == "exited"] + while len(live) < replicas and stopped: + ctr = stopped.pop(0) + ctr.state = "running" + live.append(ctr) + while len(live) < replicas: + live.append(self.add(service, tag)) + return ok() + + def _ps(self, args): + if any(a.startswith("label=com.docker.compose.project.working_dir=") for a in args): + # Compose project names of everything running in this directory. + projects = [self.project] * len(self.ctrs) + self.other_projects + return ok("".join(p + "\n" for p in projects)) + service = None + statuses = [] + for flag, value in zip(args, args[1:]): + if flag == "--filter" and value.startswith("label=com.docker.compose.service="): + service = value.split("=", 2)[2] + if flag == "--filter" and value.startswith("status="): + statuses.append(value.split("=", 1)[1]) + statuses = statuses or ["running"] + lines = [ + json.dumps( + { + "ID": c.id, + "Image": c.ref, + "CreatedAt": f"2024-01-01 00:00:{1 if self.same_created else c.created:02d}", + "State": c.state, + "Labels": f"com.docker.compose.service={c.service}", + } + ) + for c in self.ctrs + if c.service == service and c.state in statuses + ] + return ok("".join(line + "\n" for line in lines)) + + def _inspect(self, args): + fmt = args[args.index("--format") + 1] + ids = args[args.index("--format") + 2 :] + by_id = {c.id: c for c in self.ctrs} + if fmt == "{{.State.Health.Status}}": + ctr = by_id.get(ids[0]) + if ctr is None: + return fail("No such container") + sick = ctr.tag in self.unhealthy or (ctr.service, ctr.tag) in self.unhealthy_services + return ok("unhealthy\n" if sick else "healthy\n") + if any(i not in by_id for i in ids): + return fail("No such container") + return ok("".join(f"{i}{'0' * 8} {by_id[i].image_id}\n" for i in ids)) + + def _stop(self, ctr_id): + for ctr in self.ctrs: + if ctr.id == ctr_id: + ctr.state = "exited" + return ok() + return fail("No such container") + + def _rm(self, ctr_id): + for ctr in self.ctrs: + if ctr.id == ctr_id: + if ctr.state == "running": # as docker rm without -f + return fail("cannot remove a running container") + self.ctrs.remove(ctr) + return ok() + return fail("No such container") diff --git a/tests/fixtures/rolling_master.json b/tests/fixtures/rolling_master.json index 40ef70b..8379ec4 100644 --- a/tests/fixtures/rolling_master.json +++ b/tests/fixtures/rolling_master.json @@ -31,7 +31,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -51,7 +51,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -67,7 +67,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -77,6 +77,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -89,7 +91,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_web_222" + "web003" ], null ], @@ -99,7 +101,7 @@ "stop", "--time", "30", - "old_web_111" + "web001" ], null ], @@ -107,7 +109,7 @@ [ "docker", "rm", - "old_web_111" + "web001" ], null ], @@ -123,7 +125,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -134,7 +136,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -150,7 +152,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -160,6 +162,8 @@ "--filter", "label=com.docker.compose.service=worker", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -172,7 +176,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_wrk_444" + "worker004" ], null ], @@ -182,7 +186,7 @@ "stop", "--time", "30", - "old_wrk_333" + "worker002" ], null ], @@ -190,7 +194,7 @@ [ "docker", "rm", - "old_wrk_333" + "worker002" ], null ], @@ -206,7 +210,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ] ], @@ -244,7 +248,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -264,7 +268,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -280,7 +284,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -290,6 +294,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -302,7 +308,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_web_222" + "web003" ], null ], @@ -312,7 +318,7 @@ "stop", "--time", "30", - "new_web_222" + "web003" ], null ], @@ -320,7 +326,7 @@ [ "docker", "rm", - "new_web_222" + "web003" ], null ], @@ -336,7 +342,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -344,7 +350,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] @@ -383,7 +389,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -403,7 +409,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -419,7 +425,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -429,6 +435,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -441,7 +449,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_web_222" + "web003" ], null ], @@ -451,7 +459,7 @@ "stop", "--time", "30", - "old_web_111" + "web001" ], null ], @@ -459,7 +467,7 @@ [ "docker", "rm", - "old_web_111" + "web001" ], null ], @@ -475,7 +483,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -486,7 +494,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -502,7 +510,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -512,6 +520,8 @@ "--filter", "label=com.docker.compose.service=worker", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -524,7 +534,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_wrk_444" + "worker004" ], null ], @@ -534,7 +544,7 @@ "stop", "--time", "30", - "new_wrk_444" + "worker004" ], null ], @@ -542,7 +552,7 @@ [ "docker", "rm", - "new_wrk_444" + "worker004" ], null ], @@ -558,7 +568,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -566,7 +576,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] @@ -605,7 +615,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -625,7 +635,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -633,7 +643,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] @@ -672,7 +682,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -692,7 +702,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -708,7 +718,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -716,7 +726,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] @@ -755,7 +765,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -775,7 +785,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -791,7 +801,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -801,6 +811,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -819,7 +831,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -827,7 +839,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] @@ -866,7 +878,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -886,7 +898,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -902,7 +914,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -912,6 +924,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -930,7 +944,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -938,7 +952,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] @@ -977,7 +991,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -997,7 +1011,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1013,7 +1027,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1023,6 +1037,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1035,7 +1051,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_web_222" + "web003" ], null ], @@ -1045,7 +1061,7 @@ "stop", "--time", "30", - "old_web_111" + "web001" ], null ], @@ -1053,7 +1069,7 @@ [ "docker", "rm", - "old_web_111" + "web001" ], null ], @@ -1069,7 +1085,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1080,7 +1096,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1096,7 +1112,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1106,6 +1122,8 @@ "--filter", "label=com.docker.compose.service=worker", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1118,7 +1136,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_wrk_444" + "worker004" ], null ], @@ -1128,7 +1146,7 @@ "stop", "--time", "30", - "old_wrk_333" + "worker002" ], null ], @@ -1136,7 +1154,7 @@ [ "docker", "rm", - "old_wrk_333" + "worker002" ], null ], @@ -1152,7 +1170,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ] ], @@ -1190,7 +1208,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -1210,7 +1228,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1226,7 +1244,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1236,6 +1254,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1248,7 +1268,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_web_222" + "web003" ], null ], @@ -1258,7 +1278,7 @@ "stop", "--time", "30", - "old_web_111" + "web001" ], null ], @@ -1266,7 +1286,7 @@ [ "docker", "rm", - "old_web_111" + "web001" ], null ], @@ -1282,7 +1302,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1293,7 +1313,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1309,7 +1329,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1319,6 +1339,8 @@ "--filter", "label=com.docker.compose.service=worker", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1331,7 +1353,7 @@ "stop", "--time", "30", - "old_wrk_333" + "worker002" ], null ], @@ -1339,7 +1361,7 @@ [ "docker", "rm", - "old_wrk_333" + "worker002" ], null ], @@ -1355,7 +1377,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ] ], @@ -1393,7 +1415,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -1413,7 +1435,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1429,7 +1451,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1439,6 +1461,8 @@ "--filter", "label=com.docker.compose.service=worker", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1451,7 +1475,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_wrk_444" + "worker003" ], null ], @@ -1461,7 +1485,7 @@ "stop", "--time", "30", - "old_wrk_333" + "worker002" ], null ], @@ -1469,7 +1493,7 @@ [ "docker", "rm", - "old_wrk_333" + "worker002" ], null ], @@ -1485,7 +1509,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ] ], @@ -1542,7 +1566,7 @@ "web" ], { - "DEPLOY_TAG": "head456" + "DEPLOY_TAG": "prev123abc" } ], [ @@ -1558,7 +1582,7 @@ "web" ], { - "DEPLOY_TAG": "head456" + "DEPLOY_TAG": "prev123abc" } ], [ @@ -1568,6 +1592,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1580,7 +1606,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_web_222" + "web003" ], null ], @@ -1590,7 +1616,7 @@ "stop", "--time", "30", - "old_web_111" + "web001" ], null ], @@ -1598,7 +1624,7 @@ [ "docker", "rm", - "old_web_111" + "web001" ], null ], @@ -1614,7 +1640,7 @@ "web" ], { - "DEPLOY_TAG": "head456" + "DEPLOY_TAG": "prev123abc" } ], [ @@ -1625,7 +1651,7 @@ "worker" ], { - "DEPLOY_TAG": "head456" + "DEPLOY_TAG": "prev123abc" } ], [ @@ -1641,7 +1667,7 @@ "worker" ], { - "DEPLOY_TAG": "head456" + "DEPLOY_TAG": "prev123abc" } ], [ @@ -1651,6 +1677,8 @@ "--filter", "label=com.docker.compose.service=worker", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1663,7 +1691,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_wrk_444" + "worker004" ], null ], @@ -1673,7 +1701,7 @@ "stop", "--time", "30", - "old_wrk_333" + "worker002" ], null ], @@ -1681,7 +1709,7 @@ [ "docker", "rm", - "old_wrk_333" + "worker002" ], null ], @@ -1697,7 +1725,7 @@ "worker" ], { - "DEPLOY_TAG": "head456" + "DEPLOY_TAG": "prev123abc" } ] ], @@ -1735,7 +1763,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -1755,7 +1783,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1763,7 +1791,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] @@ -1802,7 +1830,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -1822,7 +1850,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1838,7 +1866,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1848,6 +1876,8 @@ "--filter", "label=com.docker.compose.service=web", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1860,7 +1890,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_web_222" + "web003" ], null ], @@ -1870,7 +1900,7 @@ "stop", "--time", "30", - "old_web_111" + "web001" ], null ], @@ -1878,7 +1908,7 @@ [ "docker", "rm", - "old_web_111" + "web001" ], null ], @@ -1894,7 +1924,7 @@ "web" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1905,7 +1935,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1921,7 +1951,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ], [ @@ -1931,6 +1961,8 @@ "--filter", "label=com.docker.compose.service=worker", "--filter", + "label=com.docker.compose.project=proj", + "--filter", "status=running", "--format", "{{json .}}" @@ -1943,7 +1975,7 @@ "inspect", "--format", "{{.State.Health.Status}}", - "new_wrk_444" + "worker005" ], null ], @@ -1953,7 +1985,7 @@ "stop", "--time", "30", - "old_wrk_333" + "worker002" ], null ], @@ -1961,7 +1993,7 @@ [ "docker", "rm", - "old_wrk_333" + "worker002" ], null ], @@ -1977,7 +2009,7 @@ "worker" ], { - "DEPLOY_TAG": "abc123" + "DEPLOY_TAG": "v2" } ] ], @@ -2029,7 +2061,7 @@ "git", "checkout", "--detach", - "abc123" + "v2" ], null ], @@ -2046,7 +2078,7 @@ "git", "checkout", "--detach", - "prev123" + "prev123abc" ], null ] diff --git a/tests/helpers.py b/tests/helpers.py new file mode 100644 index 0000000..3a7d71d --- /dev/null +++ b/tests/helpers.py @@ -0,0 +1,47 @@ +"""Compose builders and setup shared by the FakeHost-based tests.""" + +import json + +from tests.fake_host import REPO + + +def app(order=100, strategy=None, drain=None, healthcheck=True, skip=False, image=None): + """An app service for FakeHost's compose config.""" + labels = {"deploy.role": "app", "deploy.order": str(order)} + if strategy: + labels["deploy.strategy"] = strategy + if drain is not None: + labels["deploy.drain"] = str(drain) + if skip: + labels["deploy.healthcheck.skip"] = "true" + svc = {"image": image or f"{REPO}:${{DEPLOY_TAG:-latest}}", "labels": labels} + if healthcheck: + svc["healthcheck"] = {"test": ["CMD", "true"]} + return svc + + +def stack(**services): + """A compose config: ``stack(web=app(100), worker=app(300, "drain-first"))``.""" + return {"services": services} + + +# web rolls; scheduler and worker drain first. +DRAIN = stack( + web=app(100), + scheduler=app(200, "drain-first"), + worker=app(300, "drain-first", drain=3660), +) +# Rolling only: web then worker, as on master. +ROLLING = stack(web=app(100), worker=app(200)) + + +def chdir(monkeypatch, tmp_path): + """Work in tmp_path, with a .git/ for the lock and the deploy-tag record.""" + (tmp_path / ".git").mkdir(exist_ok=True) + monkeypatch.chdir(tmp_path) + + +def record(tmp_path): + """The .git/deploy-tag record, or None.""" + path = tmp_path / ".git" / "deploy-tag" + return json.loads(path.read_text()) if path.exists() else None diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 1e829e5..4c9d389 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -72,6 +72,9 @@ def registry(docker): build_args = [a for k, v in args.items() for a in ("--build-arg", f"{k}={v}")] run(["docker", "build", "-q", "-t", image, *build_args, str(IMAGES / "stub")]) run(["docker", "push", "-q", image]) + # :latest starts out as v1, as a host first brought up by hand would be. + run(["docker", "tag", f"{host}/stub:v1", f"{host}/stub:latest"]) + run(["docker", "push", "-q", f"{host}/stub:latest"]) yield host finally: run(["docker", "rm", "-f", name], check=False) @@ -99,7 +102,7 @@ def service( if start_period: healthcheck["start_period"] = start_period return { - "image": image or "${REGISTRY}/stub:${DEPLOY_TAG}", + "image": image or "${REGISTRY}/stub:${DEPLOY_TAG:-latest}", "environment": dict(env or {}), "labels": labels, "healthcheck": healthcheck, @@ -158,23 +161,49 @@ def env(self, tag=None, extra=None): def git(self, *args): return run(["git", "-C", str(self.repo), *args]).stdout.strip() - def commit(self, tag, compose): - """Commit ``compose`` as docker-compose.yml and tag it ``tag``.""" + def commit(self, tag, compose, annotated=False, force=False): + """Commit ``compose`` as docker-compose.yml, tag it ``tag`` (unless None), push. + + ``force`` moves an existing tag, here and on origin, as a re-release does. + """ (self.repo / "docker-compose.yml").write_text(yaml.safe_dump(compose, sort_keys=False)) self.git("add", "docker-compose.yml") - self.git("commit", "-q", "--allow-empty", "-m", tag) - self.git("tag", tag) - self.git("push", "-q", "origin", "HEAD:refs/heads/main", "--tags") + self.git("commit", "-q", "--allow-empty", "-m", tag or "untagged") + if tag: + args = ["-a", "-m", f"release {tag}"] if annotated else [] + self.git("tag", *(["-f"] if force else []), *args, tag) + self.git("push", "-q", "origin", "HEAD:refs/heads/main") + if tag: + self.git("push", "-q", *(["-f"] if force else []), "origin", f"refs/tags/{tag}") return self.git("rev-parse", "HEAD") + def push_image(self, source, tag): + """Publish the stub image built as ``source`` under ``tag`` too.""" + image = f"{self.registry}/stub:{tag}" + run(["docker", "tag", f"{self.registry}/stub:{source}", image]) + run(["docker", "push", "-q", image]) + + def flow(self, *args, extra=None): + """Run a flow-deploy command in the repo; returns the CompletedProcess.""" + return run( + [sys.executable, "-m", "flow_deploy.cli", *args], + cwd=self.repo, + env=self.env(extra=extra), + check=False, + ) + def compose(self, *args, tag=None, check=True, extra=None): return run( ["docker", "compose", *args], cwd=self.repo, env=self.env(tag, extra), check=check ) - def up(self, tag, scale=None, wait=True, extra=None): - """Bring the stack up at ``tag``, as a running production host would be.""" - self.git("checkout", "-q", "--detach", tag) + def up(self, tag, scale=None, wait=True, extra=None, ref=None): + """Bring the stack up at ``tag``, as a running production host would be. + + ``tag=None`` runs compose without DEPLOY_TAG (so images resolve to + :latest), checked out at ``ref``. + """ + self.git("checkout", "-q", "--detach", ref or tag) scale_args = [a for name, n in (scale or {}).items() for a in ("--scale", f"{name}={n}")] wait_args = ["--wait"] if wait else [] self._up = True @@ -223,27 +252,35 @@ def start_deploy(self, tag): ) def state(self): - """service -> sorted list of (version tag, state) for its containers.""" - out = run( + """service -> sorted list of (version, state) for its containers. + + The version is the STUB_VERSION baked into the image, not its tag: a + reverted container runs a flow-deploy- alias of the image it ran. + """ + ids = run( [ "docker", "ps", - "-a", + "-aq", "--filter", f"label=com.docker.compose.project={self.project}", - "--format", - "{{json .}}", ] - ).stdout + ).stdout.split() result = {} - for line in out.splitlines(): - ctr = json.loads(line) - labels = dict(kv.split("=", 1) for kv in ctr["Labels"].split(",") if "=" in kv) - svc = labels.get("com.docker.compose.service") - tag = ctr["Image"].rsplit(":", 1)[-1] if "/" in ctr["Image"] else ctr["Image"] - result.setdefault(svc, []).append((tag, ctr["State"])) + for ctr in self.inspect(ids): + svc = ctr["Config"]["Labels"].get("com.docker.compose.service") + env = dict(e.split("=", 1) for e in ctr["Config"]["Env"] if "=" in e) + result.setdefault(svc, []).append((env.get("STUB_VERSION"), ctr["State"]["Status"])) return {svc: sorted(v) for svc, v in result.items()} + def inspect(self, ids): + return json.loads(run(["docker", "inspect", *ids]).stdout) if ids else [] + + def image_refs(self, service_name): + """The image references (repo:tag) of a service's running containers.""" + ids = self.compose("ps", "-q", service_name).stdout.split() + return sorted(ctr["Config"]["Image"] for ctr in self.inspect(ids)) + def running(self): """service -> sorted list of the version tags of its running containers.""" return { @@ -261,6 +298,11 @@ def head(self): def sha(self, tag): return self.git("rev-parse", f"{tag}^{{commit}}") + def record(self): + """The .git/deploy-tag record flow-deploy keeps, or None.""" + path = self.repo / ".git" / "deploy-tag" + return json.loads(path.read_text()) if path.exists() else None + def lock_exists(self): return (self.repo / ".git" / "deploy-lock").exists() diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index bc4937c..80dfcd5 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -8,12 +8,13 @@ from tests.integration.conftest import SIGNALS, service, standard ALL_V1 = {"web": ["v1"], "scheduler": ["v1"], "worker": ["v1"]} +SERVICES = ("web", "scheduler", "worker") -def assert_reverted(stack, expected_running, code, out, expected_code=1): +def assert_reverted(stack, expected_running, code, out, expected_code=1, previous="v1"): assert code == expected_code, out assert stack.running() == expected_running, out - assert stack.head() == stack.sha("v1"), "repo not restored to the previous commit" + assert stack.head() == stack.sha(previous), "repo not restored to the previous commit" assert not stack.lock_exists(), "lock left behind" @@ -84,19 +85,21 @@ def test_rolling_only_project_keeps_its_old_container_on_a_failed_healthcheck(st assert stack.container_ids("web") == old, "web's old container was replaced" +BAD_WORKER = service(300, "drain-first", env={"STUB_HEALTH": "fail"}, health_timeout=20) + + def test_drain_first_service_fails_its_healthcheck_in_phase_3(stack): - """The failed worker goes back to v1 at its replica count. Web and the - scheduler, healthy on v3, stay: shipped services aren't rolled back.""" + """Everything goes back to v1: web (shipped) and the scheduler (started + healthy) too, and the worker at its replica count.""" stack.commit("v1", standard()) - bad_worker = service(300, "drain-first", env={"STUB_HEALTH": "fail"}, health_timeout=20) - stack.commit("v3", standard(worker=bad_worker)) + stack.commit("v3", standard(worker=BAD_WORKER)) stack.up("v1", scale={"worker": 2}) result = stack.deploy("v3") assert_reverted( stack, - {"web": ["v3"], "scheduler": ["v3"], "worker": ["v1", "v1"]}, + {"web": ["v1"], "scheduler": ["v1"], "worker": ["v1", "v1"]}, result.returncode, result.stdout, ) @@ -178,10 +181,10 @@ def test_lock_held_by_a_live_process_exits_2_and_changes_nothing(stack): assert lock.exists(), "another process's lock was released" -def test_old_image_without_a_tag_exits_3(stack): - """A worker started from a digest-pinned image can't be restored by tag.""" +def test_digest_pinned_worker_is_restored_to_the_same_image(stack): + """A worker started from a digest (no tag at all) is restored by image ID.""" pinned_worker = service( - 300, "drain-first", image="${WORKER_IMAGE:-${REGISTRY}/stub:${DEPLOY_TAG}}" + 300, "drain-first", image="${WORKER_IMAGE:-${REGISTRY}/stub:${DEPLOY_TAG:-latest}}" ) stack.commit("v1", standard(worker=pinned_worker)) stack.commit("unhealthy", standard(worker=pinned_worker)) @@ -189,12 +192,8 @@ def test_old_image_without_a_tag_exits_3(stack): result = stack.deploy("unhealthy") - assert result.returncode == 3, result.stdout + result.stderr - assert "cannot restore worker: no tag in its previous image" in result.stdout - assert "could not be fully reverted" in result.stderr - assert stack.running() == {"web": ["v1"], "scheduler": ["v1"]} - assert stack.head() == stack.sha("v1") - assert not stack.lock_exists() + assert_reverted(stack, ALL_V1, result.returncode, result.stdout) + assert stack.image_refs("worker")[0].split(":")[-1].startswith("flow-deploy-") def test_crash_looping_drain_first_worker_is_drained(stack): @@ -224,3 +223,158 @@ def test_rolling_healthcheck_that_passes_late_still_deploys(stack): assert result.returncode == 0, result.stdout + result.stderr assert stack.running()["web"] == ["v2"] + + +# --------------------------------------------------------------------------- +# Image tags: versions, shas, restores, :latest, and manual compose +# --------------------------------------------------------------------------- + + +def test_annotated_version_tag_deploy(stack): + """Releases deploy by version tag; an annotated tag checks out its commit.""" + stack.commit("v1", standard()) + stack.commit("v2", standard(), annotated=True) + stack.up("v1") + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} + assert stack.head() == stack.sha("v2") + assert stack.image_refs("web") == [f"{stack.registry}/stub:v2"] + assert stack.record()["tag"] == "v2" + assert stack.flow("tag").stdout == "v2\n" + + +def test_sha_deploy(stack): + """A commit SHA still works as the tag: CI pushes the image under it.""" + stack.commit("v1", standard()) + sha = stack.commit(None, standard()) + stack.push_image("v2", sha) + stack.up("v1") + + result = stack.deploy(sha) + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} + assert stack.head() == sha + assert stack.flow("tag").stdout == f"{sha}\n" + + +def test_failed_deploy_restores_the_version_that_was_running(stack): + """v1 -> v2 succeeds; v3 then fails in phase 3 and everything returns to + v2 (not v1, not :latest), shipped web included.""" + stack.commit("v1", standard()) + stack.commit("v2", standard()) + stack.commit("v3", standard(worker=BAD_WORKER)) + stack.up("v1") + assert stack.deploy("v2").returncode == 0 + + result = stack.deploy("v3") + + assert_reverted( + stack, + {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]}, + result.returncode, + result.stdout, + previous="v2", + ) + # Restored by an alias of the exact image; the record follows it. The + # worker kept its v2 container, web was recreated on the alias: one image. + tag = stack.record()["tag"] + assert tag.startswith("flow-deploy-") + assert stack.flow("tag").stdout == f"{tag}\n" + assert stack.flow("compose", "up", "-d", "--wait").returncode == 0 + assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} + + +def test_first_deploy_from_latest_restores_that_image_after_latest_moves(stack): + """A host brought up by hand runs :latest. If :latest is re-pushed and + pulled before a failed deploy, the revert still restores the image that + was running, not what :latest names now.""" + latest = f"latest-{os.getpid()}-{int(time.time())}" # don't move the shared :latest + stack.push_image("v1", latest) + image = f"${{REGISTRY}}/stub:${{DEPLOY_TAG:-{latest}}}" + by_hand = standard(**{s: {**standard()["services"][s], "image": image} for s in SERVICES}) + stack.commit("v1", by_hand) + bad = {**BAD_WORKER, "image": image} + stack.commit("v3", {"services": {**by_hand["services"], "worker": bad}}) + stack.up(None, ref="v1") + assert stack.image_refs("web") == [f"{stack.registry}/stub:{latest}"] + stack.push_image("v2", latest) + assert stack.compose("pull", "web").returncode == 0 # the host's tag now names v2 + + result = stack.deploy("v3") + + assert_reverted(stack, ALL_V1, result.returncode, result.stdout) + + +def test_manual_compose_keeps_the_deployed_version(stack): + """`flow-deploy compose up -d` on the host changes nothing after a deploy; + plain compose without DEPLOY_TAG would move every service to :latest.""" + stack.commit("v1", standard()) + stack.commit("v2", standard()) + stack.up("v1") + assert stack.deploy("v2").returncode == 0 + before = {svc: stack.container_ids(svc) for svc in SERVICES} + + result = stack.flow("compose", "up", "-d", "--wait") + + assert result.returncode == 0, result.stdout + result.stderr + assert "DEPLOY_TAG=v2 (from running containers)" in result.stderr + assert {svc: stack.container_ids(svc) for svc in SERVICES} == before + # The hazard it prevents: compose's ${DEPLOY_TAG:-latest} default. + images = stack.compose("config", "--images").stdout.split() + assert images == [f"{stack.registry}/stub:latest"] * 3 + + +def test_manual_compose_refuses_when_nothing_tells_the_tag(stack): + stack.commit("v1", standard()) + stack.git("checkout", "-q", "--detach", "v1") + + result = stack.flow("compose", "up", "-d") + + assert result.returncode == 1 + assert "nothing is running and no deploy is recorded" in result.stderr + assert stack.running() == {} + + +def test_moved_tag_deploys_its_new_commit_and_image(stack): + """A re-pushed release tag is fetched (--force) and its image re-pulled.""" + tag = f"moved-{os.getpid()}-{int(time.time())}" + stack.commit("v1", standard()) + first = stack.commit(tag, standard()) + stack.push_image("v1", tag) + stack.up("v1") + assert stack.deploy(tag).returncode == 0 + # Re-release: the tag moves to a new commit and a new image. + second = stack.commit(tag, standard(), force=True) + stack.push_image("v2", tag) + assert first != second + + result = stack.deploy(tag) + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.head() == second + assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} + + +def test_containers_of_another_project_name_here_are_refused(stack): + """A release that renamed the compose project would start a second stack + beside the first and have nothing to revert to: refused, nothing changed.""" + stack.commit("v1", standard()) + stack.commit("v2", standard()) + stack.up("v1") + other = f"{stack.project}old" + stack.compose("-p", other, "up", "-d", "--wait", "web", tag="v1") + try: + before = {svc: stack.container_ids(svc) for svc in SERVICES} + + result = stack.deploy("v2") + + assert result.returncode == 1, result.stdout + result.stderr + assert f"compose project(s) {other} are running" in result.stderr + assert {svc: stack.container_ids(svc) for svc in SERVICES} == before + assert stack.head() == stack.sha("v1") + finally: + stack.compose("-p", other, "down", "--timeout", "1", check=False) diff --git a/tests/rolling_scenarios.py b/tests/rolling_scenarios.py index b36a7a2..99627d4 100644 --- a/tests/rolling_scenarios.py +++ b/tests/rolling_scenarios.py @@ -1,146 +1,113 @@ -"""Rolling-only deploy scenarios, shared by the parity test and its recorder. +"""Rolling-only deploy scenarios on a FakeHost, shared by the parity test and its recorder. -Responses are plain (returncode, stdout, stderr) tuples so the recorder can run -them against another checkout's flow_deploy (master) without importing this -branch's code. To re-record fixtures/rolling_master.json from a master -checkout: +fixtures/rolling_master.json holds what master (0.3.0) did in each scenario: +every command, its env, the exit code, and whether the lock was left behind. +To re-record it from a master checkout: git worktree add /tmp/deploy-master master poetry run python tests/rolling_scenarios.py /tmp/deploy-master \ > tests/fixtures/rolling_master.json -""" -import json - -CONFIG = """\ -services: - web: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/health"] - worker: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - deploy.order: "200" - healthcheck: - test: ["CMD", "celery", "inspect", "ping"] - postgres: - image: postgres:16 - labels: - deploy.role: accessory +Scenarios declare what's running and what fails, not a call sequence, so the +same scenario runs unchanged against master's code and this branch's even +though this branch issues extra commands (the pre-deploy snapshot). """ -SKIP_CONFIG = CONFIG.replace( - ' deploy.order: "200"\n', - ' deploy.order: "200"\n deploy.healthcheck.skip: "true"\n', -) - - -def _ctr(cid, tag, created): - return json.dumps({"ID": cid, "Image": f"ghcr.io/myorg/myapp:{tag}", "CreatedAt": created}) - - -WEB = _ctr("old_web_111", "old", "2024-01-01") + "\n" + _ctr("new_web_222", "abc123", "2024-01-02") -WRK = _ctr("old_wrk_333", "old", "2024-01-01") + "\n" + _ctr("new_wrk_444", "abc123", "2024-01-02") -# Same tag on both: old/new told apart by CreatedAt. -WEB_SAME_TAG = ( - _ctr("old_web_111", "abc123", "2024-01-01") + "\n" + _ctr("new_web_222", "abc123", "2024-01-02") -) -# Same tag and same CreatedAt: can't tell them apart. -WEB_TWINS = _ctr("a1", "abc123", "2024-01-01") + "\n" + _ctr("b2", "abc123", "2024-01-01") - - -def ok(out=""): - return (0, out, "") - - -def err(msg="error"): - return (1, "", msg) - +import copy +import os +import sys + +CONFIG = { + "services": { + "web": { + "image": "ghcr.io/myorg/myapp:${DEPLOY_TAG:-latest}", + "labels": {"deploy.role": "app"}, + "healthcheck": {"test": ["CMD", "true"]}, + }, + "worker": { + "image": "ghcr.io/myorg/myapp:${DEPLOY_TAG:-latest}", + "labels": {"deploy.role": "app", "deploy.order": "200"}, + "healthcheck": {"test": ["CMD", "true"]}, + }, + "postgres": {"image": "postgres:16", "labels": {"deploy.role": "accessory"}}, + } +} -GIT = [ok(""), ok(), ok("prev123\n"), ok()] -GIT_NO_TAG = [ok("head456\n"), ok(""), ok(), ok("head456\n")] # rev-parse, status, fetch, rev-parse +V1 = {"web": ["v1"], "worker": ["v1"]} -def roll(ps, health="healthy\n", stop=None): - return [ok(), ok(), ok(ps), ok(health), stop or ok(), ok(), ok()] +def _skip_worker_health(config): + labels = config["services"]["worker"]["labels"] + labels["deploy.healthcheck.skip"] = "true" + return config -def roll_skip(ps): - return [ok(), ok(), ok(ps), ok(), ok(), ok()] +def _twins(host): + """Old and new containers on the deploy tag with the same CreatedAt: unidentifiable.""" + host.same_created = True -# name -> (responses, deploy kwargs) +# name -> (running, setup(host) or None, deploy kwargs, config transform or None) SCENARIOS = { - "happy": (GIT + [ok(CONFIG)] + roll(WEB) + roll(WRK), {}), - "health_abort": ( - GIT + [ok(CONFIG), ok(), ok(), ok(WEB), ok("unhealthy\n"), ok(), ok(), ok(), ok()], - {}, - ), + "happy": (V1, None, {}, None), + "health_abort": (V1, lambda h: h.unhealthy_services.add(("web", "v2")), {}, None), "second_service_health_abort": ( - GIT - + [ok(CONFIG)] - + roll(WEB) - + [ok(), ok(), ok(WRK), ok("unhealthy\n")] - + [ok(), ok(), ok(), ok()], + V1, + lambda h: h.unhealthy_services.add(("worker", "v2")), {}, + None, ), - "pull_fail": (GIT + [ok(CONFIG), err("pull"), ok()], {}), - "scale_up_fail": (GIT + [ok(CONFIG), ok(), err("port"), ok()], {}), - "count_mismatch": ( - GIT + [ok(CONFIG), ok(), ok(), ok(WEB.split("\n")[0]), ok(), ok()], + "pull_fail": (V1, lambda h: h.unpullable.add("v2"), {}, None), + "scale_up_fail": (V1, lambda h: h.fail("--scale web=2 web", times=1), {}, None), + "count_mismatch": (V1, lambda h: h.stuck.add("web"), {}, None), + "unidentifiable": ({"web": ["v2"], "worker": ["v2"]}, _twins, {}, None), + "same_tag_redeploy": ({"web": ["v2"], "worker": ["v2"]}, None, {}, None), + "healthcheck_skip": (V1, None, {}, _skip_worker_health), + "service_filter": (V1, None, {"services_filter": ["worker"]}, None), + "no_tag_current_head": (V1, None, {"tag": None}, None), + "restore_fail": ( + V1, + lambda h: (h.unpullable.add("v2"), h.fail("git checkout --detach prev123abc")), {}, + None, ), - "unidentifiable": (GIT + [ok(CONFIG), ok(), ok(), ok(WEB_TWINS), ok(), ok()], {}), - "same_tag_redeploy": (GIT + [ok(CONFIG)] + roll(WEB_SAME_TAG) + roll(WRK), {}), - "healthcheck_skip": (GIT + [ok(SKIP_CONFIG)] + roll(WEB) + roll_skip(WRK), {}), - "service_filter": (GIT + [ok(CONFIG)] + roll(WRK), {"services_filter": ["worker"]}), - "no_tag_current_head": (GIT_NO_TAG + [ok(CONFIG)] + roll(WEB) + roll(WRK), {"tag": None}), - "restore_fail": (GIT + [ok(CONFIG), err("pull"), err("checkout")], {}), - "cutover_stop_fail": ( - GIT + [ok(CONFIG)] + roll(WEB, stop=err("No such container")) + roll(WRK), - {}, - ), - "dirty_tree": ([ok(" M file")], {}), - "compose_config_fail": (GIT + [err("bad yaml"), ok()], {}), + "cutover_stop_fail": (V1, lambda h: h.fail("docker stop --time 30 web001"), {}, None), + "dirty_tree": (V1, lambda h: setattr(h, "dirty", True), {}, None), + "compose_config_fail": (V1, lambda h: h.fail("docker compose config"), {}, None), } def record(deploy_module, process_module, name, workdir): """Run one scenario against the given flow_deploy modules; return the observation.""" - import os - - responses, kwargs = SCENARIOS[name] - queue = [process_module.Result(*r) for r in responses] - calls = [] - - def fake_run(args, env=None, cwd=None, **_kwargs): - calls.append([args, env]) - return queue.pop(0) if queue else process_module.Result(0, "", "") - - process_module.run = fake_run + from tests.fake_host import COMPOSE_CMD, FakeHost + + running, setup, kwargs, transform = SCENARIOS[name] + config = copy.deepcopy(CONFIG) + if transform: + config = transform(config) + host = FakeHost(config, running=running) + if setup: + setup(host) + process_module.run = host.run process_module.run_streaming = lambda *a, **k: 0 deploy_module.time.sleep = lambda _s: None os.makedirs(os.path.join(workdir, ".git"), exist_ok=True) os.chdir(workdir) - kwargs = {"tag": "abc123", **kwargs} - code = deploy_module.deploy(cmd=["docker", "compose"], **kwargs) + code = deploy_module.deploy(cmd=COMPOSE_CMD, **{"tag": "v2", **kwargs}) return { "code": code, - "calls": calls, + "calls": [[args, env] for args, env in zip(host.calls, host.envs)], "lock_left": os.path.exists(".git/deploy-lock"), } if __name__ == "__main__": - import os - import sys + import json import tempfile + # The target checkout's flow_deploy must win over this one's. sys.path.insert(0, os.path.join(sys.argv[1], "src")) + sys.path.insert(1, os.getcwd()) from flow_deploy import deploy as deploy_mod from flow_deploy import process diff --git a/tests/test_cli.py b/tests/test_cli.py index 3f8c3e1..fa7fcff 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -148,31 +148,7 @@ def test_config_with_command(mock_config, mock_env, mock_discover): mock_config.assert_called_once_with(cmd=["docker", "compose"]) -STATUS_COMPOSE = { - "services": { - "web": {"labels": {"deploy.role": "app"}}, - "postgres": {"labels": {"deploy.role": "accessory"}}, - } -} - - -@patch("flow_deploy.containers.get_container_health") -@patch("flow_deploy.containers.get_containers_for_service") -@patch("flow_deploy.git.current_sha") -@patch("flow_deploy.compose.compose_config") -def test_status_lists_each_service(mock_config, mock_sha, mock_ctrs, mock_health, capsys): - mock_config.return_value = STATUS_COMPOSE - mock_sha.return_value = "abc1234def" - mock_ctrs.side_effect = lambda name: ( - [{"ID": "0123456789abcdef", "Image": "app:v1", "State": "running"}] if name == "web" else [] - ) - mock_health.return_value = None - result = CliRunner().invoke(main, ["status"]) - assert result.exit_code == 0 - out = capsys.readouterr().out + result.output - assert "Current SHA: abc1234" in out - assert "web (app) 0123456789ab app:v1 running/none" in out - assert "postgres (accessory) no containers" in out +# Status with containers and the deployed tag: tests/test_deployed.py. @patch("flow_deploy.git.current_sha") diff --git a/tests/test_compose.py b/tests/test_compose.py index 0db4319..d75dab9 100644 --- a/tests/test_compose.py +++ b/tests/test_compose.py @@ -47,6 +47,14 @@ def test_compose_config_parses_yaml(mock_process): assert config["services"]["web"]["image"] == "myapp:latest" +def test_compose_config_with_env(mock_process): + mock_process.responses.append(process.Result(0, "services: {}\n", "")) + compose_config(cmd=["docker", "compose"], env={"DEPLOY_TAG": "v2"}) + _, args, env, _ = mock_process.calls[0] + assert args == ["docker", "compose", "config"] + assert env == {"DEPLOY_TAG": "v2"} + + def test_compose_config_raises_on_failure(mock_process): mock_process.responses.append(process.Result(1, "", "error")) try: diff --git a/tests/test_containers.py b/tests/test_containers.py index 09da902..93b0bb9 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -7,8 +7,13 @@ get_container_health, get_containers_for_service, identify_old_new, + image_ids, + image_repo, + image_tag, + other_projects_here, remove_container, stop_container, + tag_image, ) @@ -127,3 +132,93 @@ def test_remove_container(mock_process): assert remove_container("abc123") is True _, args, _, _ = mock_process.calls[0] assert args == ["docker", "rm", "abc123"] + + +def test_image_tag(): + assert image_tag("ghcr.io/org/app:v1.2.0") == "v1.2.0" + assert image_tag("localhost:5000/app:abc123@sha256:ff") == "abc123" + assert image_tag("localhost:5000/app") is None + assert image_tag("ghcr.io/org/app@sha256:ff") is None + assert image_tag("sha256:" + "a" * 64) is None + + +def test_image_repo(): + assert image_repo("ghcr.io/org/app:v1") == "ghcr.io/org/app" + assert image_repo("localhost:5000/app:v1@sha256:ff") == "localhost:5000/app" + assert image_repo("app:v1") == "app" + assert image_repo("app") == "app" + + +def test_image_ids_maps_short_ids(mock_process): + mock_process.responses.append( + process.Result(0, "aaa111ffff sha256:one\nbbb222ffff sha256:two\n", "") + ) + assert image_ids(["aaa111", "bbb222"]) == {"aaa111": "sha256:one", "bbb222": "sha256:two"} + assert mock_process.calls[0][1] == [ + "docker", + "inspect", + "--format", + "{{.Id}} {{.Image}}", + "aaa111", + "bbb222", + ] + + +def test_image_ids_empty_makes_no_call(mock_process): + assert image_ids([]) == {} + assert mock_process.calls == [] + + +def test_image_ids_inspect_failure(mock_process): + mock_process.responses.append(process.Result(1, "", "No such container")) + assert image_ids(["aaa111"]) is None + + +def test_image_ids_missing_container(mock_process): + mock_process.responses.append(process.Result(0, "aaa111ffff sha256:one\n", "")) + assert image_ids(["aaa111", "ccc333"]) is None + + +def test_tag_image(mock_process): + mock_process.responses.append(process.Result(0, "", "")) + mock_process.responses.append(process.Result(1, "", "no such image")) + assert tag_image("sha256:one", "app:flow-deploy-one") is True + assert mock_process.calls[0][1] == ["docker", "tag", "sha256:one", "app:flow-deploy-one"] + assert tag_image("sha256:two", "app:flow-deploy-two") is False + + +def test_other_projects_here(mock_process, monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("PWD", str(tmp_path)) + mock_process.responses.append(process.Result(0, "proj\nproj\nold\n\n", "")) + assert other_projects_here("proj") == {"old"} + args = mock_process.calls[0][1] + assert f"label=com.docker.compose.project.working_dir={tmp_path}" in args + + +def test_other_projects_here_checks_the_shell_path_too(mock_process, monkeypatch, tmp_path): + """compose records the directory as given, which may be a symlinked path.""" + real = tmp_path / "real" + real.mkdir() + (tmp_path / "link").symlink_to(real) + monkeypatch.chdir(real) + monkeypatch.setenv("PWD", str(tmp_path / "link")) + mock_process.responses.append(process.Result(0, "", "")) + mock_process.responses.append(process.Result(0, "other\n", "")) + assert other_projects_here("proj") == {"other"} + assert len(mock_process.calls) == 2 + + +def test_other_projects_here_ignores_an_inherited_pwd(mock_process, monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("PWD", "/somewhere/else") + mock_process.responses.append(process.Result(0, "", "")) + assert other_projects_here("proj") == set() + assert len(mock_process.calls) == 1 + + +def test_other_projects_here_failure(mock_process, monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("PWD", raising=False) + mock_process.responses.append(process.Result(1, "", "daemon down")) + assert other_projects_here("proj") is None diff --git a/tests/test_deploy.py b/tests/test_deploy.py index c5da3ea..63db1a0 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -1,447 +1,377 @@ -"""Tests for deploy.py — full deploy lifecycle, dry-run.""" +"""Rolling deploys on a FakeHost: success, failures, rollback, and the tag record.""" -import json +import pytest -from flow_deploy import process +from flow_deploy import lock from flow_deploy.deploy import deploy +from tests.fake_host import COMPOSE_CMD, FakeHost +from tests.helpers import ROLLING, app, chdir, record, stack -COMPOSE_CMD = ["docker", "compose"] -PREV_SHA = "prev123abc" - -COMPOSE_CONFIG_YAML = """\ -services: - web: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/health"] - worker: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - deploy.order: "200" - healthcheck: - test: ["CMD", "celery", "inspect", "ping"] - postgres: - image: postgres:16 - labels: - deploy.role: accessory -""" - -WEB_CONTAINER_OLD = json.dumps( - { - "ID": "old_web_111", - "Image": "ghcr.io/myorg/myapp:oldtag", - "CreatedAt": "2024-01-01 00:00:00", - "State": "running", - } -) -WEB_CONTAINER_NEW = json.dumps( - { - "ID": "new_web_222", - "Image": "ghcr.io/myorg/myapp:abc123", - "CreatedAt": "2024-01-02 00:00:00", - "State": "running", - } -) -WORKER_CONTAINER_OLD = json.dumps( - { - "ID": "old_wrk_333", - "Image": "ghcr.io/myorg/myapp:oldtag", - "CreatedAt": "2024-01-01 00:00:00", - "State": "running", - } -) -WORKER_CONTAINER_NEW = json.dumps( - { - "ID": "new_wrk_444", - "Image": "ghcr.io/myorg/myapp:abc123", - "CreatedAt": "2024-01-02 00:00:00", - "State": "running", - } -) - - -def _ok(stdout=""): - return process.Result(0, stdout, "") - - -def _err(stderr="error"): - return process.Result(1, "", stderr) - - -def _git_preflight(): - """Return the 4 mock responses for a clean git preflight.""" - return [ - _ok(""), # git status --porcelain (clean) - _ok(), # git fetch origin - _ok(PREV_SHA + "\n"), # git rev-parse HEAD - _ok(), # git checkout --detach - ] - - -HEAD_SHA = "head456def" - - -def _git_preflight_no_checkout(): - """Return the 3 mock responses for preflight when no tag is provided (no checkout).""" - return [ - _ok(""), # git status --porcelain (clean) - _ok(), # git fetch origin - _ok(HEAD_SHA + "\n"), # git rev-parse HEAD - ] - - -def _chdir(monkeypatch, tmp_path): - """Set working directory and ensure .git/ exists for lock file.""" - (tmp_path / ".git").mkdir(exist_ok=True) - monkeypatch.chdir(tmp_path) - - -def _setup_happy_path(mock_process, monkeypatch, tmp_path): - """Set up mock responses for a successful 2-service deploy.""" - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - # git preflight (before compose config) - *_git_preflight(), - # compose config - _ok(COMPOSE_CONFIG_YAML), - # web: pull - _ok(), - # web: scale to 2 - _ok(), - # web: docker ps (get containers) - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), - # web: health check (healthy) - _ok("healthy\n"), - # web: docker stop old - _ok(), - # web: docker rm old - _ok(), - # web: scale back to 1 - _ok(), - # worker: pull - _ok(), - # worker: scale to 2 - _ok(), - # worker: docker ps - _ok(WORKER_CONTAINER_OLD + "\n" + WORKER_CONTAINER_NEW + "\n"), - # worker: health check (healthy) - _ok("healthy\n"), - # worker: docker stop old - _ok(), - # worker: docker rm old - _ok(), - # worker: scale back to 1 - _ok(), - ] - ) - - -def test_deploy_happy_path(mock_process, monkeypatch, tmp_path): - _setup_happy_path(mock_process, monkeypatch, tmp_path) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 0 - - -def test_deploy_service_filter(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - # web only: pull, scale, ps, health, stop, rm, scale back - _ok(), - _ok(), - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), - _ok("healthy\n"), - _ok(), - _ok(), - _ok(), - ] - ) - result = deploy(tag="abc123", services_filter=["web"], cmd=COMPOSE_CMD) - assert result == 0 - - -def test_deploy_dry_run(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - mock_process.responses.append(_ok(COMPOSE_CONFIG_YAML)) - result = deploy(tag="abc123", dry_run=True, cmd=COMPOSE_CMD) - assert result == 0 + +@pytest.fixture +def host(monkeypatch, tmp_path): + """A rolling-only host with web and worker on v1.""" + chdir(monkeypatch, tmp_path) + return FakeHost(ROLLING, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + + +def test_deploy_happy_path(host, tmp_path): + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"], "worker": ["v2"]} + assert host.sha == "v2" + assert record(tmp_path)["tag"] == "v2" + assert not (tmp_path / ".git" / "deploy-lock").exists() + + +def test_deploy_order_follows_deploy_order(host, capsys): + deploy(tag="v2", cmd=COMPOSE_CMD) + out = capsys.readouterr().out + assert out.index("▸ web") < out.index("▸ worker") + + +def test_deploy_service_filter_leaves_others_and_clears_the_record(host, tmp_path, capsys): + (tmp_path / ".git" / "deploy-tag").write_text('{"tag": "v1"}') + assert deploy(tag="v2", services_filter=["web"], cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"], "worker": ["v1"]} + # Services now run different tags: no single tag describes the host. + assert record(tmp_path) is None + assert "manual compose commands on this host need DEPLOY_TAG" in capsys.readouterr().err + + +def test_deploy_dry_run_changes_nothing(host, tmp_path, capsys): + assert deploy(tag="v2", dry_run=True, cmd=COMPOSE_CMD) == 0 out = capsys.readouterr().out - assert "dry-run" in out - assert "web" in out - assert "worker" in out - # No lock file should exist + assert "dry-run" in out and "web" in out and "worker" in out + assert host.running() == {"web": ["v1"], "worker": ["v1"]} assert not (tmp_path / ".git" / "deploy-lock").exists() -def test_deploy_health_check_failure(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - # Patch _wait_for_healthy to avoid real sleep - monkeypatch.setattr("flow_deploy.deploy._wait_for_healthy", lambda *a, **kw: False) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - # web: pull - _ok(), - # web: scale to 2 - _ok(), - # web: docker ps - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), - # web: stop new (abort) - _ok(), - # web: rm new - _ok(), - # web: scale back to 1 - _ok(), - # git restore to previous SHA - _ok(), - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - - -def test_deploy_pull_failure(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _err("pull failed"), - # git restore to previous SHA - _ok(), - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - - -def test_deploy_lock_held(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - # No git or compose responses needed — lock check happens first - # Pre-acquire lock with current PID - from flow_deploy import lock +def test_deploy_health_check_failure_keeps_the_old_container(host): + before = [c.id for c in host.ctrs if c.service == "web"] + host.unhealthy_services.add(("web", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + assert [c.id for c in host.ctrs if c.service == "web"] == before + assert host.sha == "prev123abc" + + +def test_deploy_pull_failure_changes_nothing(host): + host.unpullable.add("v2") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + +def test_deploy_lock_held(host): lock.acquire() try: - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 2 + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 2 finally: lock.release() + assert host.calls == [] -def test_deploy_missing_healthcheck(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - config_no_hc = """\ -services: - web: - image: app:latest - labels: - deploy.role: app -""" - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(config_no_hc), - _ok(), # git restore - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - - -def test_deploy_no_services(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - config_empty = "services:\n redis:\n image: redis:7\n" - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(config_empty), - _ok(), # git restore - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - - -def test_deploy_compose_config_failure(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _err("compose error"), - _ok(), # git restore - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - - -def test_deploy_container_count_mismatch(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - single_svc_config = """\ -services: - web: - image: app:latest - labels: - deploy.role: app - healthcheck: - test: ["CMD", "true"] -""" - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(single_svc_config), - _ok(), # pull - _ok(), # scale to 2 - _ok(WEB_CONTAINER_OLD + "\n"), # only 1 container returned - _ok(), # scale back to 1 - _ok(), # git restore - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - - -def test_deploy_order(mock_process, monkeypatch, tmp_path, capsys): - """Verify services deploy in order (web before worker due to deploy.order).""" - _setup_happy_path(mock_process, monkeypatch, tmp_path) - deploy(tag="abc123", cmd=COMPOSE_CMD) - out = capsys.readouterr().out - web_pos = out.index("▸ web") - worker_pos = out.index("▸ worker") - assert web_pos < worker_pos +def test_deploy_missing_healthcheck(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + FakeHost(stack(web=app(healthcheck=False))).install(monkeypatch) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + + +def test_deploy_no_app_services(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + FakeHost(stack(redis={"image": "redis:7"})).install(monkeypatch) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + + +def test_deploy_compose_config_failure(host): + host.fail("docker compose config") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.sha == "prev123abc" + +def test_deploy_container_count_mismatch_scales_back(host): + host.stuck.add("web") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running() == {"web": ["v1"], "worker": ["v1"]} -def test_deploy_restore_failure_exits_degraded_and_releases_lock( - mock_process, monkeypatch, tmp_path, capsys -): + +def test_deploy_restore_failure_exits_degraded_and_releases_lock(host, tmp_path, capsys): """A failed git restore exits 3 but still releases the lock: no manual cleanup.""" - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - # web: pull fails - _err("pull failed"), - # git restore fails - _err("checkout error"), - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 3 + host.unpullable.add("v2") + host.fail("git checkout --detach prev123abc") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 assert not (tmp_path / ".git" / "deploy-lock").exists() assert "could not be fully reverted (git restore failed)" in capsys.readouterr().err -def test_deploy_dirty_tree_fails(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - # git status --porcelain returns dirty (before compose config) - _ok(" M somefile.py\n"), - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 1 - err = capsys.readouterr().err - assert "dirty" in err - - -def test_deploy_healthcheck_skip(mock_process, monkeypatch, tmp_path): - """Services with deploy.healthcheck.skip=true skip health check waiting.""" - _chdir(monkeypatch, tmp_path) - config_with_skip = """\ -services: - beat: - image: app:latest - labels: - deploy.role: app - deploy.healthcheck.skip: "true" - deploy.drain: "1" -""" - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(config_with_skip), - # beat: pull - _ok(), - # beat: scale to 2 - _ok(), - # beat: docker ps - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), - # beat: no health check poll — skips straight to cutover - # beat: docker stop old - _ok(), - # beat: docker rm old - _ok(), - # beat: scale back to 1 - _ok(), - ] - ) - result = deploy(tag="abc123", cmd=COMPOSE_CMD) - assert result == 0 - - -def test_deploy_no_tag_uses_head(mock_process, monkeypatch, tmp_path): - """Deploy without --tag uses current HEAD SHA and skips git checkout.""" - _chdir(monkeypatch, tmp_path) - single_svc_config = """\ -services: - web: - image: app:latest - labels: - deploy.role: app - healthcheck: - test: ["CMD", "true"] -""" - mock_process.responses.extend( - [ - # git rev-parse HEAD for tag resolution - _ok(HEAD_SHA + "\n"), - # git preflight (no checkout) - *_git_preflight_no_checkout(), - # compose config - _ok(single_svc_config), - # web: pull - _ok(), - # web: scale to 2 - _ok(), - # web: docker ps - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), - # web: health check - _ok("healthy\n"), - # web: docker stop old - _ok(), - # web: docker rm old - _ok(), - # web: scale back to 1 - _ok(), - ] - ) - result = deploy(cmd=COMPOSE_CMD) - assert result == 0 - - -def test_deploy_no_tag_dry_run(mock_process, monkeypatch, tmp_path, capsys): - """Dry run without --tag resolves tag from HEAD.""" - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - # git rev-parse HEAD for tag resolution - _ok(HEAD_SHA + "\n"), - # compose config - _ok(COMPOSE_CONFIG_YAML), - ] - ) - result = deploy(dry_run=True, cmd=COMPOSE_CMD) - assert result == 0 +def test_deploy_dirty_tree_fails(host, capsys): + host.dirty = True + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "dirty" in capsys.readouterr().err + + +def test_deploy_healthcheck_skip(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(stack(beat=app(skip=True, healthcheck=False)), running={"beat": ["v1"]}) + host.install(monkeypatch) + host.unhealthy.add("v2") # never consulted + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"beat": ["v2"]} + + +def test_deploy_no_tag_uses_head(host): + """Without --tag, deploy the current HEAD: no checkout, its SHA as the tag.""" + assert deploy(cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["prev123abc"], "worker": ["prev123abc"]} + assert not any("checkout" in c for c in host.commands()) + + +def test_deploy_no_tag_dry_run(host, capsys): + assert deploy(dry_run=True, cmd=COMPOSE_CMD) == 0 out = capsys.readouterr().out - assert "dry-run" in out - assert HEAD_SHA in out + assert "dry-run" in out and "prev123abc" in out + + +def test_fetches_every_tag_and_updates_moved_ones(host): + deploy(tag="v2", cmd=COMPOSE_CMD) + assert "git fetch --tags --force origin" in host.commands() + + +def test_config_is_rendered_with_the_deploy_tag(host): + deploy(tag="v2", cmd=COMPOSE_CMD) + config_call = host.calls.index(["docker", "compose", "config"]) + assert host.envs[config_call] == {"DEPLOY_TAG": "v2"} + + +# --------------------------------------------------------------------------- +# A failure reverts everything, shipped rolling services included +# --------------------------------------------------------------------------- + + +def test_second_service_failing_rolls_the_first_back(host, tmp_path): + host.unhealthy_services.add(("worker", "v2")) + before = host.running_images() + + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + + # web had shipped v2; it's rolled back to the exact image it ran. + assert host.running_images() == before + assert host.sha == "prev123abc" + rollback = host.index("--scale web=2", "web") + assert host.calls[rollback] and host.commands().count("docker compose pull web") == 1 + assert record(tmp_path)["tag"].startswith("flow-deploy-") + + +def test_rollback_failure_exits_3(host, capsys): + host.unhealthy_services.add(("worker", "v2")) + host.fail("docker compose up -d --no-deps --no-recreate --scale web=2 web", skip=1) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + assert "web could not be rolled back" in capsys.readouterr().err + + +def test_no_restore_alias_means_no_deploy(host, capsys): + """A deploy that already couldn't be reverted exactly never starts.""" + host.fail("docker tag") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "could not tag web's running image" in capsys.readouterr().err + assert not any("compose pull" in c for c in host.commands()) + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + assert host.sha == "prev123abc" + + +def test_rollback_after_a_failed_cutover_cleanup_keeps_the_previous_container(host): + """web's old container survived its cutover (stop failed); when worker then + fails, the rollback removes web's new container and keeps the old one.""" + old = next(c.id for c in host.ctrs if c.service == "web") + host.fail("docker stop --time 30 web001", times=1) + host.unhealthy_services.add(("worker", "v2")) + before = host.running_images() + + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + + assert host.running_images() == before + assert [c.id for c in host.ctrs if c.service == "web" and c.state == "running"] == [old] + + +def test_rollback_removes_a_stopped_leftover_first(host): + """web's cutover stopped its old container but couldn't remove it. compose + would restart that leftover during the rollback; it's removed instead.""" + host.fail("docker rm web001", times=1) + host.unhealthy_services.add(("worker", "v2")) + before = host.running_images() + + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + + assert host.running_images() == before + assert not any(c.id == "web001" for c in host.ctrs) + assert not any(c.state == "exited" for c in host.ctrs) + + +def test_rollback_that_cannot_list_stopped_containers_exits_3(host, capsys): + host.unhealthy_services.add(("worker", "v2")) + host.fail("--filter status=created") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + assert "its stopped containers can't be inspected" in capsys.readouterr().out + + +def test_rollback_that_cannot_remove_a_stopped_leftover_exits_3(host, capsys): + host.fail("docker rm web001") # the cutover's, and the rollback's retry + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + assert "could not remove stopped web container web001" in capsys.readouterr().out + + +def test_failed_abort_leaves_no_stopped_container_for_the_next_deploy(host): + """web's new container failed its health check and was stopped, but not + removed. The next deploy's `compose up --scale` would restart it, so the + revert removes it; the deploy still exits 3 (its own cleanup failed).""" + host.unhealthy_services.add(("web", "v2")) + host.fail("docker rm web003", times=1) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + assert not any(c.state == "exited" for c in host.ctrs) + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + + host.unhealthy_services.clear() + assert deploy(tag="v3", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v3"], "worker": ["v3"]} + + +def test_stopped_new_container_that_cannot_be_removed_on_revert_exits_3(host, capsys): + host.unhealthy_services.add(("web", "v2")) + host.fail("docker rm web003") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + assert "web's stopped new container could not be removed" in capsys.readouterr().err + + +def test_rollback_that_cannot_inspect_exits_3(host, capsys): + host.unhealthy_services.add(("worker", "v2")) + host.fail("docker inspect --format {{.Id}} {{.Image}} web", skip=1) # past the snapshot + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + assert "cannot roll web back: its containers can't be inspected" in capsys.readouterr().out + + +def test_renamed_compose_project_is_refused(host, capsys): + """The running stack belongs to another project name: deploying would + start a second stack beside it, and snapshot nothing to revert to.""" + host.other_projects = ["oldname"] + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "compose project(s) oldname are running" in capsys.readouterr().err + assert not any("compose pull" in c for c in host.commands()) + assert host.sha == "prev123abc" + + +def test_project_check_failure_changes_nothing(host, capsys): + host.fail("label=com.docker.compose.project.working_dir=") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "could not list this directory's containers" in capsys.readouterr().err + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + + +def test_service_with_no_previous_container_is_removed_on_revert(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(ROLLING, running={}).install(monkeypatch) # nothing running yet + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running() == {} + assert record(tmp_path) is None + + +def test_first_deploy_onto_an_empty_host(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(stack(web=app()), running={}).install(monkeypatch) + host.fail("docker compose up", times=0) # never fires + # Rolling with no old container: compose brings up two, one is cut over. + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"]} + + +# --------------------------------------------------------------------------- +# What's running is read from the containers, whatever they're tagged +# --------------------------------------------------------------------------- + + +def test_revert_from_latest_restores_the_exact_image_not_what_latest_became(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(ROLLING, running={"web": ["latest"], "worker": ["latest"]}) + host.install(monkeypatch) + before = host.running_images() + # Something re-pulls :latest during the deploy: it now names a new build. + host.images["latest"] = "sha256:" + "f" * 64 + host.unhealthy_services.add(("worker", "v2")) + + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running_images() == before + + +def test_digest_pinned_container_is_restored_by_alias(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(ROLLING, running={"worker": ["v1"]}).install(monkeypatch) + host.add("web", "v1", ref="ghcr.io/myorg/myapp@sha256:abc") + before = host.running_images() + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running_images() == before + + +def test_services_sharing_an_image_share_one_alias(host): + deploy(tag="v2", cmd=COMPOSE_CMD) + tags = [c for c in host.commands() if c.startswith("docker tag")] + assert len(tags) == 1 # web and worker both ran v1 + + +def test_mixed_images_warn_and_restore_the_most_common(monkeypatch, tmp_path, capsys): + chdir(monkeypatch, tmp_path) + host = FakeHost(stack(web=app()), running={"web": ["v1", "v1", "v0"]}).install(monkeypatch) + host.unhealthy_services.add(("web", "v2")) + deploy(tag="v2", cmd=COMPOSE_CMD) + assert "web is running 2 different images" in capsys.readouterr().err + + +def test_snapshot_failure_changes_nothing(host, capsys): + host.fail("docker ps") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "nothing was changed" in capsys.readouterr().err + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + assert host.sha == "prev123abc" + + +def test_snapshot_inspect_failure_changes_nothing(host): + host.fail("docker inspect --format {{.Id}} {{.Image}}") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + + +def test_snapshot_failure_with_failed_git_restore_exits_3(host): + host.fail("docker ps") + host.fail("git checkout --detach prev123abc") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + + +def test_alias_is_made_in_the_running_containers_repo_too(monkeypatch, tmp_path): + """A revert renders the previous commit's compose file: if the release + renamed the image repo, the alias must exist under the old name as well.""" + chdir(monkeypatch, tmp_path) + host = FakeHost(stack(web=app()), running={}).install(monkeypatch) + host.add("web", "v1", ref="ghcr.io/oldorg/myapp:v1") + deploy(tag="v2", cmd=COMPOSE_CMD) + tagged = sorted(c.split()[-1] for c in host.commands() if c.startswith("docker tag")) + alias = tagged[0].split(":")[-1] + assert tagged == [f"ghcr.io/myorg/myapp:{alias}", f"ghcr.io/oldorg/myapp:{alias}"] + + +def test_container_shown_by_image_id_is_aliased_in_the_config_repo(monkeypatch, tmp_path): + """docker ps shows a bare image ID once the container's tag has moved.""" + chdir(monkeypatch, tmp_path) + host = FakeHost(stack(web=app()), running={}).install(monkeypatch) + ctr = host.add("web", "v1") + ctr.ref = ctr.image_id.removeprefix("sha256:")[:12] + deploy(tag="v2", cmd=COMPOSE_CMD) + tagged = [c.split()[-1] for c in host.commands() if c.startswith("docker tag")] + assert len(tagged) == 1 and tagged[0].startswith("ghcr.io/myorg/myapp:flow-deploy-") + + +def test_image_that_ignores_deploy_tag_warns(monkeypatch, tmp_path, capsys): + chdir(monkeypatch, tmp_path) + fixed = stack(web=app(image="ghcr.io/myorg/myapp")) + FakeHost(fixed, running={"web": ["latest"]}).install(monkeypatch) + deploy(tag="v2", cmd=COMPOSE_CMD) + assert "web's image (ghcr.io/myorg/myapp) doesn't use DEPLOY_TAG" in capsys.readouterr().err diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py index 683aa60..c0bee51 100644 --- a/tests/test_deploy_failures.py +++ b/tests/test_deploy_failures.py @@ -1,143 +1,100 @@ -"""Failure paths: signals, crashes, cleanup failures, and their exit codes.""" +"""Failure paths on a FakeHost: signals, crashes, cleanup failures, exit codes.""" import signal import pytest from flow_deploy import deploy as deploy_mod -from flow_deploy.deploy import EXIT_DEGRADED, EXIT_FAILED, _image_tag, _wait_for_healthy, deploy -from tests.test_deploy import ( - COMPOSE_CMD, - COMPOSE_CONFIG_YAML, - WEB_CONTAINER_NEW, - WEB_CONTAINER_OLD, - _chdir, - _err, - _git_preflight, - _ok, -) -from tests.test_drain_first import COMPOSE_CONFIG_YAML as DRAIN_CONFIG -from tests.test_drain_first import WORKER_DRAIN, WORKER_NEW, _commands - -WEB_ONLY = ["web"] - - -def _lock_released(tmp_path): +from flow_deploy.deploy import EXIT_DEGRADED, EXIT_FAILED, _wait_for_healthy, deploy +from tests.fake_host import COMPOSE_CMD, FakeHost +from tests.helpers import DRAIN, ROLLING, app, chdir, stack + + +def send(signum): + """Deliver ``signum`` to the current handler, as the kernel would mid-command.""" + return lambda: signal.getsignal(signum)(signum, None) + + +def lock_released(tmp_path): return not (tmp_path / ".git" / "deploy-lock").exists() +@pytest.fixture +def drain_host(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["v1"], "scheduler": ["v1"], "worker": ["v1"]}) + return host.install(monkeypatch) + + +@pytest.fixture +def rolling_host(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + return FakeHost(ROLLING, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + + +def v1(host, *services): + return {s: [host.images["v1"]] for s in services} + + # --------------------------------------------------------------------------- # Signals and unexpected exceptions revert like any other failure # --------------------------------------------------------------------------- -def test_sigterm_mid_deploy_restores_drained_and_releases(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - original = signal.getsignal(signal.SIGTERM) +@pytest.mark.parametrize("signum", [signal.SIGTERM, signal.SIGINT, signal.SIGHUP]) +def test_signal_mid_roll_reverts_everything(drain_host, tmp_path, signum): + original = signal.getsignal(signum) + drain_host.before("--scale web=2", send(signum)) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + assert drain_host.running_images() == v1(drain_host, "web", "scheduler", "worker") + assert drain_host.sha == "prev123abc" + assert lock_released(tmp_path) + assert signal.getsignal(signum) is original - def cancelled(*args, **kwargs): - # What a cancelled CI job delivers while web is rolling. - signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) - monkeypatch.setattr(deploy_mod, "_deploy_service", cancelled) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - *WORKER_DRAIN, - _ok(), # git restore - _ok(), # worker: restore on old tag - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - assert _lock_released(tmp_path) - assert signal.getsignal(signal.SIGTERM) is original - - -def test_sighup_from_a_dropped_ssh_session_reverts(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - - def hung_up(*args, **kwargs): - signal.getsignal(signal.SIGHUP)(signal.SIGHUP, None) - - monkeypatch.setattr(deploy_mod, "_deploy_service", hung_up) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - *WORKER_DRAIN, - _ok(), # git restore - _ok(), # worker: restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - - -def test_signal_while_a_drain_is_stopping_still_restores(mock_process, monkeypatch, tmp_path): - """A drain can take an hour: a cancel mid-stop must still know what to restore.""" - _chdir(monkeypatch, tmp_path) - - def stop_interrupted(container_id, timeout=30, isolate=False): - signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) - - monkeypatch.setattr(deploy_mod.containers, "stop_container", stop_interrupted) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - _ok(), # worker: pull - WORKER_DRAIN[1], # worker: docker ps - _ok(), # git restore - _ok(), # worker: restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - assert "--scale worker=1 worker" in _commands(mock_process)[-1] - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} +def test_signal_while_a_drain_is_stopping_waits_for_it_then_reverts(drain_host, capsys): + """Held until the container has stopped and been removed, then reverted.""" + drain_host.before("docker stop --time 3660 worker", send(signal.SIGINT)) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + assert "finishing the drain of worker0" in capsys.readouterr().out + cmds = drain_host.commands() + stop = drain_host.index("docker stop --time 3660 worker") + assert cmds[stop + 1].startswith("docker rm worker") # the stop and rm finished + assert drain_host.running_images() == v1(drain_host, "web", "scheduler", "worker") -def test_signals_are_ignored_while_reverting(mock_process, monkeypatch, tmp_path): - """A second signal mid-revert neither cuts it short nor starts another.""" - _chdir(monkeypatch, tmp_path) - seen = [] +def test_a_second_signal_during_a_held_drain_is_also_held(drain_host): + def two(): + send(signal.SIGINT)() + send(signal.SIGTERM)() - def restore(drained, compose_cmd): - seen.append(signal.getsignal(signal.SIGTERM)) - return True - - monkeypatch.setattr(deploy_mod, "_restore_drained", restore) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - *WORKER_DRAIN, - _err("pull failed"), # web: pull - _ok(), # git restore - ] + drain_host.before("docker stop --time 3660 worker", two) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + + +def test_signals_are_ignored_while_reverting(drain_host): + seen = [] + drain_host.unpullable.add("v2") + drain_host.before( + "git checkout --detach prev123abc", lambda: seen.append(signal.getsignal(signal.SIGTERM)) ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED assert seen == [signal.SIG_IGN] -def test_signal_while_taking_the_lock_changes_nothing(mock_process, monkeypatch, tmp_path): +def test_signal_while_taking_the_lock_changes_nothing(monkeypatch, tmp_path): """Handlers are installed before the lock, so even this signal is handled.""" - _chdir(monkeypatch, tmp_path) + chdir(monkeypatch, tmp_path) + host = FakeHost(ROLLING).install(monkeypatch) released = [] - - def acquire_interrupted(): - signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) - - monkeypatch.setattr(deploy_mod.lock, "acquire", acquire_interrupted) + monkeypatch.setattr(deploy_mod.lock, "acquire", send(signal.SIGTERM)) monkeypatch.setattr(deploy_mod.lock, "release", lambda: released.append(True)) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - assert mock_process.calls == [] + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + assert host.calls == [] assert released == [] # never held, so never released -def test_finally_ignores_signals_while_releasing(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) +def test_finally_ignores_signals_while_releasing(rolling_host, monkeypatch): original = signal.getsignal(signal.SIGHUP) during_release = [] real_release = deploy_mod.lock.release @@ -147,100 +104,39 @@ def release(): real_release() monkeypatch.setattr(deploy_mod.lock, "release", release) - mock_process.responses.extend([*_git_preflight(), _ok(COMPOSE_CONFIG_YAML), *_web_roll()]) - assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == 0 + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 assert during_release == [signal.SIG_IGN] assert signal.getsignal(signal.SIGHUP) is original -def _web_roll(): - return [ - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps - _ok("healthy\n"), # web: health - _ok(), # web: stop old - _ok(), # web: rm old - _ok(), # web: scale back - ] - - -def test_unexpected_exception_reverts(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - +def test_unexpected_exception_reverts(drain_host, monkeypatch, capsys): def boom(*args, **kwargs): raise KeyError("Image") monkeypatch.setattr(deploy_mod, "_deploy_service", boom) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - *WORKER_DRAIN, - _ok(), # git restore - _ok(), # worker: restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED assert "unexpected error: KeyError('Image'); reverting" in capsys.readouterr().err - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - assert _lock_released(tmp_path) + assert drain_host.running_images() == v1(drain_host, "web", "scheduler", "worker") -def test_exception_before_checkout_skips_git_restore(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) +def test_exception_before_checkout_skips_git_restore(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(ROLLING).install(monkeypatch) def broken(_tag): raise OSError("git not found") monkeypatch.setattr(deploy_mod.git, "preflight_and_checkout", broken) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - assert mock_process.calls == [] # nothing to restore - assert _lock_released(tmp_path) - - -def test_interrupt_during_start_keeps_already_started_services(mock_process, monkeypatch, tmp_path): - """Services healthy on the new tag stay; only unstarted ones are restored.""" - _chdir(monkeypatch, tmp_path) - two = DRAIN_CONFIG + ( - " scheduler:\n" - " image: ghcr.io/myorg/myapp:latest\n" - " labels:\n" - " deploy.role: app\n" - " deploy.strategy: drain-first\n" - ' deploy.order: "300"\n' - " healthcheck:\n" - ' test: ["CMD", "true"]\n' - ) - real_start = deploy_mod._start_service - - def start(svc, *args, **kwargs): - if svc.name == "scheduler": - signal.getsignal(signal.SIGINT)(signal.SIGINT, None) - return real_start(svc, *args, **kwargs) - - monkeypatch.setattr(deploy_mod, "_start_service", start) - monkeypatch.setattr(deploy_mod, "_deploy_service", lambda *a, **kw: 0) - sched_old = '{"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.1.0"}' - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(two), - _ok(), # scheduler: pull - _ok(sched_old + "\n"), # scheduler: ps - _ok(), # scheduler: stop - _ok(), # scheduler: rm - *WORKER_DRAIN, - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: ps - _ok("healthy\n"), # worker: health - _ok(), # git restore - _ok(), # scheduler: restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - restores = [c for c in mock_process.calls if c[2] and c[2]["DEPLOY_TAG"] != "abc123"] - assert [c[2]["DEPLOY_TAG"] for c in restores] == ["v1.1.0"] # scheduler only + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + assert host.calls == [] + assert lock_released(tmp_path) + + +def test_interrupt_during_start_reverts_services_already_started(drain_host): + drain_host.before("--scale worker=1 worker", send(signal.SIGINT)) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + # The scheduler was already healthy on v2; it goes back with the rest. + assert drain_host.running_images() == v1(drain_host, "web", "scheduler", "worker") # --------------------------------------------------------------------------- @@ -248,203 +144,62 @@ def start(svc, *args, **kwargs): # --------------------------------------------------------------------------- -def test_rolling_abort_cleanup_failure_is_degraded(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - monkeypatch.setattr(deploy_mod, "_wait_for_healthy", lambda *a, **kw: False) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps - _err("stop failed"), # web: stop new - _ok(), # web: rm new - _ok(), # web: scale back - _ok(), # git restore - ] - ) - result = deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) +def test_rolling_abort_cleanup_failure_is_degraded(rolling_host, capsys): + rolling_host.unhealthy_services.add(("web", "v2")) + rolling_host.fail("docker stop --time 30 web003") # the new container won't stop + result = deploy(tag="v2", services_filter=["web"], cmd=COMPOSE_CMD) assert result == EXIT_DEGRADED captured = capsys.readouterr() - assert "abort incomplete: new container new_web" in captured.out + assert "abort incomplete: new container web003" in captured.out assert "cleanup failed for web" in captured.err -def test_rolling_cutover_cleanup_failure_still_succeeds( - mock_process, monkeypatch, tmp_path, capsys -): - """As on master: the new container is healthy and serving, so it's a success. - - The usual cause is the old container having exited on its own; failing - here would revert the repo underneath a healthy new container. - """ - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps - _ok("healthy\n"), # web: health - _err("No such container"), # web: stop old - _ok(), # web: rm old - _ok(), # web: scale back - ] - ) - assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == 0 +def test_rolling_cutover_cleanup_failure_still_succeeds(rolling_host, capsys): + """As on master: the new container is healthy and serving, so it's a success.""" + rolling_host.fail("docker stop --time 30 web001") # e.g. the old container already exited + assert deploy(tag="v2", services_filter=["web"], cmd=COMPOSE_CMD) == 0 captured = capsys.readouterr() - assert "warning: cleanup of old container old_web" in captured.out + assert "warning: cleanup of old container web001 did not complete" in captured.out assert "::error::" not in captured.out -def test_rolling_scale_up_failure_issues_no_further_commands(mock_process, monkeypatch, tmp_path): - """As on master: no scale-back after a failed scale-up.""" - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # web: pull - _err("port in use"), # web: scale to 2 - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == EXIT_FAILED - assert not any("--scale web=1" in c for c in _commands(mock_process)) +def test_rolling_scale_up_failure_issues_no_further_commands(rolling_host): + rolling_host.fail("--scale web=2 web", times=1) + assert deploy(tag="v2", services_filter=["web"], cmd=COMPOSE_CMD) == EXIT_FAILED + assert not any("--scale web=1" in c for c in rolling_host.commands()) -@pytest.mark.parametrize(("scale_back", "expected"), [(_ok(), 1), (_err("busy"), 3)]) +@pytest.mark.parametrize("scale_back_fails, expected", [(False, 1), (True, 3)]) def test_rolling_unidentifiable_containers_scale_back( - mock_process, monkeypatch, tmp_path, scale_back, expected + monkeypatch, tmp_path, scale_back_fails, expected ): - _chdir(monkeypatch, tmp_path) - twin = '{"ID": "%s", "Image": "ghcr.io/myorg/myapp:abc123", "CreatedAt": "2024-01-01"}' - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(twin % "a1" + "\n" + twin % "b2" + "\n"), # web: ps (same tag, same time) - scale_back, # web: scale back - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", services_filter=WEB_ONLY, cmd=COMPOSE_CMD) == expected + chdir(monkeypatch, tmp_path) + host = FakeHost(stack(web=app()), running={"web": ["v2"]}).install(monkeypatch) + # Same tag on both, so old and new are told apart by CreatedAt: make them equal. + monkeypatch.setattr(deploy_mod.containers, "identify_old_new", lambda ctrs, tag: (None, None)) + if scale_back_fails: + host.fail("--scale web=1 web") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == expected -def test_start_cannot_list_containers_is_degraded(mock_process, monkeypatch, tmp_path): +def test_start_cannot_list_containers_is_degraded(drain_host): """Couldn't see what started, so couldn't remove it: exit 3, not a clean revert.""" - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - *WORKER_DRAIN, - _ok(), # worker: compose up - _err("Cannot connect to the Docker daemon"), # worker: docker ps - _ok(), # git restore - _ok(), # worker: restore - ] - ) - result = deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) - assert result == EXIT_DEGRADED - start_ps = [c for c in _commands(mock_process) if c.startswith("docker ps")][-1] - assert "--filter status=running --filter status=restarting" in start_ps - - -def test_signal_during_rolling_only_deploy_restores_git(mock_process, monkeypatch, tmp_path): - """Deliberate change from master (which released the lock and exited 1 - without restoring): a signal now also puts the repo back.""" - _chdir(monkeypatch, tmp_path) - - def cancelled(*args, **kwargs): - signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None) - - monkeypatch.setattr(deploy_mod, "_deploy_service", cancelled) - mock_process.responses.extend([*_git_preflight(), _ok(COMPOSE_CONFIG_YAML), _ok()]) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - assert _commands(mock_process)[-1] == "git checkout --detach prev123abc" - assert _lock_released(tmp_path) - - -def test_drain_aborts_when_docker_ps_fails(mock_process, monkeypatch, tmp_path, capsys): - """Couldn't list != nothing running: never roll past an unknown drain.""" - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - _ok(), # worker: pull - _err("Cannot connect to the Docker daemon"), # worker: docker ps - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == EXIT_FAILED - cmds = _commands(mock_process) - assert not any("--scale web=2" in c for c in cmds) - assert "not draining blind" in capsys.readouterr().out + drain_host.fail("--filter label=com.docker.compose.service=worker", skip=2, times=1) + assert deploy(tag="v2", services_filter=["worker"], cmd=COMPOSE_CMD) == EXIT_DEGRADED -def test_drain_lists_restarting_containers_too(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [*_git_preflight(), _ok(DRAIN_CONFIG), _ok(), _err("stop here"), _ok()] - ) - deploy(tag="abc123", cmd=COMPOSE_CMD) - ps = next(c for c in _commands(mock_process) if c.startswith("docker ps")) - assert "--filter status=running --filter status=restarting" in ps +@pytest.mark.parametrize("command", ["docker stop --time 3660 worker", "docker rm worker"]) +def test_failed_start_that_cannot_be_removed_is_degraded(drain_host, command): + drain_host.unhealthy_services.add(("worker", "v2")) + drain_host.fail(command, skip=1) # past the drain's own stop/rm + assert deploy(tag="v2", services_filter=["worker"], cmd=COMPOSE_CMD) == EXIT_DEGRADED -@pytest.mark.parametrize( - ("stop", "rm"), [(_err("stuck"), _ok()), (_ok(), _err("in use"))], ids=["stop", "rm"] -) -def test_failed_start_that_cannot_be_removed_is_degraded( - mock_process, monkeypatch, tmp_path, stop, rm -): - _chdir(monkeypatch, tmp_path) - monkeypatch.setattr(deploy_mod, "_wait_for_healthy", lambda *a, **kw: False) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - *WORKER_DRAIN, - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: ps - stop, # worker: stop unhealthy new - rm, # worker: rm unhealthy new - _ok(), # git restore - _ok(), # worker: restore - ] - ) - result = deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) - assert result == EXIT_DEGRADED - - -def test_start_scales_to_the_drained_replica_count(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - old2 = '{"ID": "old_wrk_555", "Image": "ghcr.io/myorg/myapp:v1.2.0"}' - new2 = '{"ID": "new_wrk_888", "Image": "ghcr.io/myorg/myapp:abc123"}' - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(DRAIN_CONFIG), - _ok(), # worker: pull - _ok(WORKER_DRAIN[1].stdout.strip() + "\n" + old2 + "\n"), # worker: ps (2) - _ok(), # stop 1 - _ok(), # rm 1 - _ok(), # stop 2 - _ok(), # rm 2 - _ok(), # worker: compose up --scale worker=2 - _ok(WORKER_NEW + "\n" + new2 + "\n"), # worker: ps (2) - _ok("healthy\n"), # worker 1: health - _ok("healthy\n"), # worker 2: health - ] - ) - assert deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) == 0 - assert any("--scale worker=2 worker" in c for c in _commands(mock_process)) +def test_start_scales_to_the_drained_replica_count(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"worker": ["v1", "v1"]}).install(monkeypatch) + assert deploy(tag="v2", services_filter=["worker"], cmd=COMPOSE_CMD) == 0 + assert host.running() == {"worker": ["v2", "v2"]} # --------------------------------------------------------------------------- @@ -452,20 +207,13 @@ def test_start_scales_to_the_drained_replica_count(mock_process, monkeypatch, tm # --------------------------------------------------------------------------- -def test_dry_run_compose_failure(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.append(_err("bad compose file")) - assert deploy(tag="abc123", dry_run=True, cmd=COMPOSE_CMD) == 1 - - -def test_dry_run_unknown_service(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.append(_ok(COMPOSE_CONFIG_YAML)) - assert deploy(tag="abc123", dry_run=True, services_filter=["nope"], cmd=COMPOSE_CMD) == 1 +def test_dry_run_compose_failure(rolling_host): + rolling_host.fail("docker compose config") + assert deploy(tag="v2", dry_run=True, cmd=COMPOSE_CMD) == 1 -def test_image_tag_bare_id_has_no_tag(): - assert _image_tag("sha256:0123abcd") is None +def test_dry_run_unknown_service(rolling_host): + assert deploy(tag="v2", dry_run=True, services_filter=["nope"], cmd=COMPOSE_CMD) == 1 def test_wait_for_healthy_returns_false_when_unhealthy(monkeypatch): diff --git a/tests/test_deployed.py b/tests/test_deployed.py new file mode 100644 index 0000000..57115f0 --- /dev/null +++ b/tests/test_deployed.py @@ -0,0 +1,224 @@ +"""What's deployed on this host: deployed.current(), and the tag/compose/status commands.""" + +import json + +import pytest +from click.testing import CliRunner + +from flow_deploy import compose, deployed, process +from flow_deploy.cli import main +from tests.fake_host import COMPOSE_CMD, FakeHost +from tests.helpers import ROLLING, chdir + + +@pytest.fixture +def host(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + monkeypatch.delenv("DEPLOY_TAG", raising=False) + monkeypatch.setattr(compose, "resolve_command", lambda: list(COMPOSE_CMD)) + return FakeHost(ROLLING).install(monkeypatch) + + +@pytest.fixture +def streamed(monkeypatch): + """What `flow-deploy compose` streams: [(args, env)].""" + calls = [] + + def run_streaming(args, env=None, cwd=None): + calls.append((args, env)) + return 0 + + monkeypatch.setattr(process, "run_streaming", run_streaming) + return calls + + +# --------------------------------------------------------------------------- +# The record +# --------------------------------------------------------------------------- + + +def test_write_read_clear(host, tmp_path): + deployed.write("v2", sha="abc") + assert deployed.read()["tag"] == "v2" + assert json.loads((tmp_path / ".git" / "deploy-tag").read_text())["sha"] == "abc" + deployed.clear() + assert deployed.read() is None + deployed.clear() # already gone: fine + + +@pytest.mark.parametrize("content", ["not json", "[]", '{"tag": ""}']) +def test_unreadable_record_is_no_record(host, tmp_path, content): + (tmp_path / ".git" / "deploy-tag").write_text(content) + assert deployed.read() is None + + +# --------------------------------------------------------------------------- +# current(): containers first, then the record, never a guess +# --------------------------------------------------------------------------- + + +def test_current_from_running_containers(host): + host.add("web", "v1.4.0") + host.add("worker", "v1.4.0") + deployed.write("v1.3.0") # the containers win over a stale record + assert deployed.current() == ("v1.4.0", "running containers") + + +def test_current_counts_restarting_containers(host): + host.add("web", "v1", state="restarting") + assert deployed.current() == ("v1", "running containers") + + +def test_current_renders_config_with_a_placeholder_tag(host): + """So a wrapper that defaults DEPLOY_TAG from `flow-deploy tag` can't recurse.""" + deployed.current() + config_call = host.calls.index(["docker", "compose", "config"]) + assert host.envs[config_call] == {"DEPLOY_TAG": deployed.LOOKUP_PLACEHOLDER} + + +def test_current_refuses_mixed_tags(host): + host.add("web", "v2") + host.add("worker", "v1") + tag, why = deployed.current() + assert tag is None + assert "different or untagged images" in why and "v2 (web)" in why and "v1 (worker)" in why + + +def test_current_after_a_revert_names_the_one_image_by_its_alias(host): + """A revert recreates shipped services on the alias, while the failed one + keeps its old container and tag: the same image under two names.""" + host.add("web", "flow-deploy-abc") + worker = host.add("worker", "v2") + host.ctrs[0].image_id = worker.image_id + assert deployed.current() == ( + "flow-deploy-abc", + "running containers (one image under several tags)", + ) + + +def test_current_refuses_different_tags_without_an_alias(host): + """Same image, but no alias among the tags: no exact name to pick.""" + web = host.add("web", "v2") + worker = host.add("worker", "v2-again") + worker.image_id = web.image_id + tag, why = deployed.current() + assert tag is None and "different or untagged images" in why + + +def test_current_raises_when_docker_inspect_fails(host): + host.add("web", "flow-deploy-abc") + host.add("worker", "v2") + host.fail("docker inspect") + with pytest.raises(RuntimeError, match="could not inspect the app containers"): + deployed.current() + + +def test_current_refuses_untagged_images(host): + host.add("web", "v1", ref="sha256:" + "a" * 64) + tag, why = deployed.current() + assert tag is None and "untagged (web)" in why + + +def test_current_falls_back_to_the_record_when_nothing_runs(host): + deployed.write("v3") + assert deployed.current() == ("v3", "last deploy record") + + +def test_current_with_nothing_to_go_on(host): + tag, why = deployed.current() + assert tag is None and "nothing is running and no deploy is recorded" in why + + +def test_current_raises_when_docker_ps_fails(host): + """Couldn't look is not "nothing running": no fallback to a stale record.""" + deployed.write("v3") + host.fail("docker ps") + with pytest.raises(RuntimeError, match="could not list web containers"): + deployed.current() + + +# --------------------------------------------------------------------------- +# flow-deploy tag +# --------------------------------------------------------------------------- + + +def test_tag_prints_only_the_tag(host): + host.add("web", "v2.0.1") + result = CliRunner().invoke(main, ["tag"]) + assert result.exit_code == 0 + assert result.stdout == "v2.0.1\n" + + +def test_tag_unknown_exits_1(host): + result = CliRunner().invoke(main, ["tag"]) + assert result.exit_code == 1 + assert result.stdout == "" + assert "can't tell which tag is deployed" in result.stderr + + +def test_tag_compose_failure_exits_1(host): + host.fail("docker compose config") + assert CliRunner().invoke(main, ["tag"]).exit_code == 1 + + +# --------------------------------------------------------------------------- +# flow-deploy compose +# --------------------------------------------------------------------------- + + +def test_compose_runs_with_the_deployed_tag(host, streamed): + host.add("web", "v2") + result = CliRunner().invoke(main, ["compose", "up", "-d", "--no-deps", "web"]) + assert result.exit_code == 0 + assert streamed == [(COMPOSE_CMD + ["up", "-d", "--no-deps", "web"], {"DEPLOY_TAG": "v2"})] + assert "DEPLOY_TAG=v2 (from running containers)" in result.stderr + + +def test_compose_explicit_deploy_tag_wins(host, streamed, monkeypatch): + monkeypatch.setenv("DEPLOY_TAG", "v9") + host.add("web", "v2") + assert CliRunner().invoke(main, ["compose", "pull"]).exit_code == 0 + assert streamed == [(COMPOSE_CMD + ["pull"], {"DEPLOY_TAG": "v9"})] + assert host.calls == [] # no lookup + + +def test_compose_refuses_when_the_tag_is_unknown(host, streamed): + host.add("web", "v2") + host.add("worker", "v1") + result = CliRunner().invoke(main, ["compose", "up", "-d"]) + assert result.exit_code == 1 + assert streamed == [] + + +def test_compose_lookup_failure_exits_1(host, streamed): + host.fail("docker compose config") + assert CliRunner().invoke(main, ["compose", "ps"]).exit_code == 1 + assert streamed == [] + + +def test_compose_propagates_the_exit_code(host, monkeypatch): + host.add("web", "v2") + monkeypatch.setattr(process, "run_streaming", lambda args, env=None, cwd=None: 17) + assert CliRunner().invoke(main, ["compose", "logs"]).exit_code == 17 + + +# --------------------------------------------------------------------------- +# flow-deploy status +# --------------------------------------------------------------------------- + + +def test_status_shows_the_deployed_tag_and_each_service(host): + host.add("web", "v2") + result = CliRunner().invoke(main, ["status"]) + assert result.exit_code == 0 + out = result.stdout + assert "Current SHA: prev123" in out + assert "Deployed tag: v2 (from running containers)" in out + assert "web (app) web001 ghcr.io/myorg/myapp:v2 running/healthy" in out + assert "worker (app) no containers" in out + + +def test_status_unknown_tag(host): + result = CliRunner().invoke(main, ["status"]) + assert result.exit_code == 0 + assert "Deployed tag: unknown (nothing is running" in result.stdout diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 9bd91ef..5a9989a 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -1,609 +1,254 @@ -"""Tests for deploy.strategy=drain-first: drain before rolling, start after.""" +"""deploy.strategy=drain-first on a FakeHost: ordering, replicas, and full reverts.""" -import json +import pytest from flow_deploy import config -from flow_deploy.deploy import _image_tag, deploy -from tests.test_deploy import ( - COMPOSE_CMD, - WEB_CONTAINER_NEW, - WEB_CONTAINER_OLD, - _chdir, - _err, - _git_preflight, - _ok, -) - -COMPOSE_CONFIG_YAML = """\ -services: - web: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/health"] - worker: - image: ghcr.io/myorg/myapp:latest - labels: - deploy.role: app - deploy.strategy: drain-first - deploy.drain: "3660" - healthcheck: - test: ["CMD", "celery", "inspect", "ping"] -""" - -WORKER_OLD = json.dumps({"ID": "old_wrk_333", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) -WORKER_NEW = json.dumps({"ID": "new_wrk_444", "Image": "ghcr.io/myorg/myapp:abc123"}) - -WEB_ROLL = [ - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: docker ps - _ok("healthy\n"), # web: health - _ok(), # web: docker stop old - _ok(), # web: docker rm old - _ok(), # web: scale back to 1 -] -WORKER_DRAIN = [ - _ok(), # worker: pull - _ok(WORKER_OLD + "\n"), # worker: docker ps - _ok(), # worker: docker stop old - _ok(), # worker: docker rm old -] - - -def _commands(mock_process): - return [" ".join(args) for _, args, _, _ in mock_process.calls] - - -def _index(commands, *needles): - return next(i for i, c in enumerate(commands) if all(n in c for n in needles)) - - -def test_drain_first_runs_drain_then_rolling_then_start(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - *WORKER_DRAIN, - *WEB_ROLL, - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: docker ps - _ok("healthy\n"), # worker: health - ] +from flow_deploy.deploy import deploy +from tests.fake_host import COMPOSE_CMD, FakeHost +from tests.helpers import DRAIN, app, chdir, record, stack + +V1 = {"web": ["v1"], "scheduler": ["v1"], "worker": ["v1", "v1"]} + + +@pytest.fixture +def host(monkeypatch, tmp_path): + """web, scheduler, and 2 worker replicas on v1.""" + chdir(monkeypatch, tmp_path) + return FakeHost(DRAIN, running=dict(V1)).install(monkeypatch) + + +def v1_images(host): + """What V1 looks like by image: a revert restores images (by alias), not tag names.""" + image = host.images["v1"] + return {svc: [image] * len(tags) for svc, tags in V1.items()} + + +def test_happy_path_drains_in_reverse_rolls_then_starts_in_order(host, tmp_path): + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2", "v2"]} + assert record(tmp_path)["tag"] == "v2" + assert ( + host.index("docker stop", "worker") + < host.index("docker stop", "scheduler") + < host.index("--scale web=2") + < host.index("--scale scheduler=1 scheduler") + < host.index("--scale worker=2 worker") ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 - - cmds = _commands(mock_process) - drain = _index(cmds, "docker stop", "--time 3660", "old_wrk_333") - roll = _index(cmds, "--scale web=2") - # Only the drain's stop is out of the process group; rolling's isn't. - assert mock_process.new_sessions == [["docker", "stop", "--time", "3660", "old_wrk_333"]] - start = _index(cmds, "--scale worker=1 worker") - assert drain < roll < start - # The worker never scales to 2: no overlap of old and new. - assert not any("--scale worker=2" in c for c in cmds) - - -def test_drain_first_service_not_running_is_started_at_one_replica( - mock_process, monkeypatch, tmp_path -): + # Drains use the service's drain timeout, out of the process group. + assert any("docker stop --time 3660 worker" in c for c in host.commands()) + assert all(args[1] == "stop" for args in host.new_sessions) and len(host.new_sessions) == 3 + # The worker never overlaps old and new. + assert not any("--scale worker=3" in c or "--scale worker=4" in c for c in host.commands()) + + +def test_new_drain_first_service_starts_at_one_replica(monkeypatch, tmp_path): """Deliberate: a service with no containers (newly added, or crashed) comes up with the deploy rather than staying at zero.""" - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # worker: pull - _ok(""), # worker: docker ps (none running) - *WEB_ROLL, - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: docker ps - _ok("healthy\n"), # worker: health - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 - assert any("--scale worker=1 worker" in c for c in _commands(mock_process)) - - -def test_rolling_failure_restores_drained_service_on_its_old_tag( - mock_process, monkeypatch, tmp_path -): - _chdir(monkeypatch, tmp_path) - monkeypatch.setattr("flow_deploy.deploy._wait_for_healthy", lambda *a, **kw: False) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - *WORKER_DRAIN, - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps - _ok(), # web: stop new (abort) - _ok(), # web: rm new - _ok(), # web: scale back to 1 - _ok(), # git restore - _ok(), # worker: compose up on the old tag - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - - restore = mock_process.calls[-1] - assert "up -d --no-deps --scale worker=1 worker" in " ".join(restore[1]) - assert restore[2] == {"DEPLOY_TAG": "v1.2.0"} - - -def test_drain_pull_failure_stops_nothing(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _err("manifest unknown"), # worker: pull - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert not any("docker stop" in c for c in _commands(mock_process)) + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} + + +def test_bad_tag_fails_at_pull_before_anything_stops(host, tmp_path): + host.unpullable.add("bad") + assert deploy(tag="bad", cmd=COMPOSE_CMD) == 1 + assert not any(c.startswith("docker stop") for c in host.commands()) + assert host.running_images() == v1_images(host) + assert host.sha == "prev123abc" + assert not (tmp_path / ".git" / "deploy-lock").exists() -def test_second_drain_failure_restores_the_first(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - two_drainers = COMPOSE_CONFIG_YAML.replace(" web:", " scheduler:", 1).replace( - ' deploy.role: app\n healthcheck:\n test: ["CMD", "curl"', - " deploy.role: app\n deploy.strategy: drain-first\n" - ' deploy.order: "300"\n healthcheck:\n test: ["CMD", "curl"', - 1, - ) - sched_old = json.dumps({"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.1.0"}) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(two_drainers), - # Drains run in reverse deploy order: scheduler (300) before worker (100). - _ok(), # scheduler: pull - _ok(sched_old + "\n"), # scheduler: ps - _ok(), # scheduler: stop - _ok(), # scheduler: rm - _err("pull failed"), # worker: pull - _ok(), # git restore - _err("no such image"), # scheduler: restore fails - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 3 - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.1.0"} - assert not (tmp_path / ".git" / "deploy-lock").exists() +@pytest.mark.parametrize("command", ["docker stop", "docker rm"]) +def test_drain_cleanup_failure_aborts_before_rolling(host, command): + host.fail(command) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert not any("--scale web=2" in c for c in host.commands()) + assert host.running_images() == v1_images(host) -def test_drained_service_that_was_not_running_stays_stopped_on_failure( - mock_process, monkeypatch, tmp_path -): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # worker: pull - _ok(""), # worker: docker ps (none running) - _err("pull failed"), # web: pull - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert not any("--scale worker=1 worker" in c for c in _commands(mock_process)) +def test_drain_aborts_when_docker_ps_fails(host, capsys): + """Couldn't list != nothing running: never roll past an unknown drain.""" + host.fail("--filter label=com.docker.compose.service=worker", skip=1, times=1) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert not any("--scale web=2" in c for c in host.commands()) + assert "not draining blind" in capsys.readouterr().out + assert host.running_images() == v1_images(host) -def test_start_failure_restores_previous_container(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - # Web comes up healthy; the new worker never does. - monkeypatch.setattr( - "flow_deploy.deploy._wait_for_healthy", lambda ctr_id, *a: ctr_id != "new_wrk_444" - ) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - *WORKER_DRAIN, - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps - _ok(), # web: docker stop old - _ok(), # web: docker rm old - _ok(), # web: scale back to 1 - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: docker ps - _ok(), # worker: stop unhealthy new - _ok(), # worker: rm unhealthy new - _ok(), # git restore - _ok(), # worker: restore on old tag - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert "worker failed to start" in capsys.readouterr().out - # The unhealthy container is gone, not left consuming... - cmds = _commands(mock_process) - assert any("docker stop --time 3660 new_wrk_444" in c for c in cmds) - assert any("docker rm new_wrk_444" in c for c in cmds) - # ...and the previous one is back, even though web shipped. - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - assert not (tmp_path / ".git" / "deploy-lock").exists() +def test_restarting_containers_are_drained_too(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["v1"], "scheduler": ["v1"]}).install(monkeypatch) + host.add("worker", "v1", state="restarting") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert [(c.tag, c.state) for c in host.ctrs if c.service == "worker"] == [("v2", "running")] -def test_start_compose_failure(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - *WORKER_DRAIN, - *WEB_ROLL, - _err("port in use"), # worker: compose up - _ok(""), # worker: docker ps - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 +def test_rolling_failure_restores_drained_services(host): + host.unhealthy_services.add(("web", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running_images() == v1_images(host) + restores = [c for c in host.commands() if "--no-recreate --scale worker=2 worker" in c] + assert len(restores) == 1 -def test_start_healthcheck_skip(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - skip = COMPOSE_CONFIG_YAML.replace( - "deploy.strategy: drain-first", - 'deploy.strategy: drain-first\n deploy.healthcheck.skip: "true"', - ) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(skip), - *WORKER_DRAIN, - *WEB_ROLL, - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: docker ps - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 +def test_phase_3_failure_reverts_everything(host, tmp_path): + """The worker fails to start: web (shipped) and the scheduler (started + healthy) go back too, so nothing new runs beside old.""" + host.unhealthy_services.add(("worker", "v2")) + before = host.running_images() + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 -def test_unknown_strategy_is_rejected(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML.replace("drain-first", "blue-green")), - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert "Unknown deploy.strategy: worker=blue-green" in capsys.readouterr().err + assert host.running_images() == before + assert host.sha == "prev123abc" + assert record(tmp_path)["tag"].startswith("flow-deploy-") + # Undo order: web rolled back before the drain-first services come back. + aliased = [ + i + for i, env in enumerate(host.envs) + if (env or {}).get("DEPLOY_TAG", "").startswith("flow-deploy-") + ] + rollback = next(i for i in aliased if "web=2" in host.calls[i]) + restore = next(i for i in aliased if "scheduler=1" in host.calls[i]) + assert rollback < restore -def test_dry_run_shows_the_three_phases(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - mock_process.responses.append(_ok(COMPOSE_CONFIG_YAML)) - assert deploy(tag="abc123", dry_run=True, cmd=COMPOSE_CMD) == 0 - out = capsys.readouterr().out - first = out.index("would drain running containers first (3660s timeout)") - rolling = out.index("would scale to 2") - last = out.index("would start on abc123") - assert first < rolling < last - - -def test_drain_stop_failure_aborts_before_rolling(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # worker: pull - _ok(WORKER_OLD + "\n"), # worker: docker ps - _err("daemon unreachable"), # worker: docker stop fails - _ok(), # git restore - _ok(), # worker: restore on old tag - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - cmds = _commands(mock_process) - assert not any("--scale web=2" in c for c in cmds) - assert "--scale worker=1 worker" in cmds[-1] - - -def test_drain_remove_failure_aborts_before_rolling(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # worker: pull - _ok(WORKER_OLD + "\n"), # worker: docker ps - _ok(), # worker: docker stop - _err("removal in progress"), # worker: docker rm fails - _ok(), # git restore - _ok(), # worker: restore on old tag - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert not any("--scale web=2" in c for c in _commands(mock_process)) - - -def test_restore_brings_back_every_replica(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - second = json.dumps({"ID": "old_wrk_555", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # worker: pull - _ok(WORKER_OLD + "\n" + second + "\n"), # worker: docker ps (2 replicas) - _ok(), # stop 1 - _ok(), # rm 1 - _ok(), # stop 2 - _ok(), # rm 2 - _err("pull failed"), # web: pull - _ok(), # git restore - _ok(), # worker: restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert "--scale worker=2 worker" in _commands(mock_process)[-1] - - -def test_mixed_old_images_are_flagged(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - other = json.dumps({"ID": "old_wrk_555", "Image": "ghcr.io/myorg/myapp:v1.1.9"}) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # worker: pull - _ok(WORKER_OLD + "\n" + other + "\n"), # worker: docker ps - _ok(), # stop 1 - _ok(), # rm 1 - _ok(), # stop 2 - _ok(), # rm 2 - _err("pull failed"), # web: pull - _ok(), # git restore - _ok(), # worker: restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert "was running mixed images" in capsys.readouterr().err - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - - -def test_failed_restore_exits_degraded_and_releases_the_lock( - mock_process, monkeypatch, tmp_path, capsys -): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - *WORKER_DRAIN, - _err("pull failed"), # web: pull - _ok(), # git restore - _err("no such image"), # worker: restore fails - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 3 +def test_one_start_failure_does_not_strand_the_others(host): + host.unhealthy_services.add(("scheduler", "v2")) + deploy(tag="v2", cmd=COMPOSE_CMD) + # The worker was still started (and then reverted with everything else). + assert any("--no-recreate" not in c and "--scale worker=2 worker" in c for c in host.commands()) + + +def test_failed_start_that_cannot_be_removed_exits_3(host): + host.unhealthy_services.add(("worker", "v2")) + host.fail("docker rm worker", skip=2) # the drain's two removals succeed + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + + +def test_start_that_cannot_list_containers_exits_3(host): + # Snapshot and drain list worker containers first; the third lookup is the start's. + host.fail("--filter label=com.docker.compose.service=worker", skip=2, times=1) + assert deploy(tag="v2", services_filter=["worker"], cmd=COMPOSE_CMD) == 3 + + +def test_start_compose_failure_reverts(host): + host.fail("--no-deps --scale worker=2 worker") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running_images() == v1_images(host) + + +def test_restore_failure_exits_3_and_releases_the_lock(host, tmp_path, capsys): + host.unhealthy_services.add(("web", "v2")) + host.fail("--no-recreate --scale worker=2 worker") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 assert "drained services could not be restored" in capsys.readouterr().err assert not (tmp_path / ".git" / "deploy-lock").exists() -def test_untagged_old_image_cannot_be_restored(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - digest = json.dumps({"ID": "old_wrk_333", "Image": "ghcr.io/myorg/myapp@sha256:abc"}) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - _ok(), # worker: pull - _ok(digest + "\n"), # worker: docker ps - _ok(), # stop - _ok(), # rm - _err("pull failed"), # web: pull - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 3 - captured = capsys.readouterr() - output = captured.out + captured.err - assert "cannot restore worker: no tag in its previous image" in output - assert "ghcr.io/myorg/myapp@sha256:abc" in output +def test_restore_removes_a_stopped_new_container_first(host): + """The worker's failed start was stopped but not removed; the restore must + not let compose start that new-image leftover again.""" + host.unhealthy_services.add(("worker", "v2")) + host.fail("docker rm worker", skip=2, times=1) # past the drain's two removals + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 # the failed start's cleanup failed + assert host.running_images() == v1_images(host) + assert not any(c.state == "exited" for c in host.ctrs) + + +def test_restore_that_cannot_list_stopped_containers_exits_3(host): + host.unhealthy_services.add(("web", "v2")) + host.fail("--filter status=created") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + + +def test_restore_cannot_inspect_exits_3(host): + """The scheduler started healthy, so its restore must inspect what's running.""" + host.unhealthy_services.add(("worker", "v2")) + host.fail("docker inspect --format {{.Id}} {{.Image}} scheduler", skip=1) # past the snapshot + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 -def test_service_filter_skipping_drain_first_warns(mock_process, monkeypatch, tmp_path, capsys): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend([*_git_preflight(), _ok(COMPOSE_CONFIG_YAML), *WEB_ROLL]) +def test_no_restore_alias_means_nothing_is_drained(host, capsys): + host.fail("docker tag") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "for a revert; nothing was changed" in capsys.readouterr().err + assert not any(c.startswith("docker stop") for c in host.commands()) + assert host.running() == V1 + + +def test_new_containers_that_cannot_be_drained_on_revert_exit_3(host): + host.unhealthy_services.add(("worker", "v2")) + # Phase 3 starts the scheduler healthy; reverting must drain it first. + host.fail("docker stop --time 30 scheduler", skip=1) # past phase 1's drain + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 + + +def test_service_not_running_before_stays_stopped_after_revert(monkeypatch, tmp_path, capsys): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + v1 = host.images["v1"] + # The scheduler phase 3 started is drained away again: it wasn't running before. + assert host.running_images() == {"web": [v1], "worker": [v1]} + assert "scheduler was not running before the deploy" in capsys.readouterr().out + + +def test_service_filter_skipping_drain_first_warns_without_an_error(host, monkeypatch, capsys): monkeypatch.setenv("GITHUB_ACTIONS", "true") - assert deploy(tag="abc123", services_filter=["web"], cmd=COMPOSE_CMD) == 0 - captured = capsys.readouterr() - assert "warning: --service leaves drain-first worker running old code" in captured.out - # A warning on a deploy that succeeds: no error annotation. - assert "::error::" not in captured.out - assert captured.err == "" - - -def test_start_failure_with_nothing_rolled_restores_old_tag( - mock_process, monkeypatch, tmp_path, capsys -): - _chdir(monkeypatch, tmp_path) - monkeypatch.setattr("flow_deploy.deploy._wait_for_healthy", lambda *a, **kw: False) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - *WORKER_DRAIN, - _ok(), # worker: compose up (new tag) - _ok(WORKER_NEW + "\n"), # worker: docker ps - _ok(), # worker: stop unhealthy new - _ok(), # worker: rm unhealthy new - _ok(), # git restore - _ok(), # worker: restore on old tag - ] - ) - assert deploy(tag="abc123", services_filter=["worker"], cmd=COMPOSE_CMD) == 1 - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} + assert deploy(tag="v2", services_filter=["web"], cmd=COMPOSE_CMD) == 0 + out = capsys.readouterr().out + assert "warning: --service leaves drain-first scheduler, worker running old code" in out + assert "::error::" not in out + + +def test_service_filter_drain_first_only_failure_restores(host): + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", services_filter=["worker"], cmd=COMPOSE_CMD) == 1 + assert host.running_images() == v1_images(host) + + +def test_unknown_strategy_is_rejected(monkeypatch, tmp_path, capsys): + chdir(monkeypatch, tmp_path) + FakeHost(stack(web=app(strategy="blue-green"))).install(monkeypatch) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "Unknown deploy.strategy: web=blue-green" in capsys.readouterr().err + + +def test_dry_run_shows_the_three_phases(host, capsys): + assert deploy(tag="v2", dry_run=True, cmd=COMPOSE_CMD) == 0 out = capsys.readouterr().out - assert "restoring worker on v1.2.0" in out - assert "worker failed to start" in out - - -def test_drains_in_reverse_order_and_starts_in_order(mock_process, monkeypatch, tmp_path): - """worker (100) then scheduler (300) in deploy order: drain scheduler first, - start worker first, roll web in between.""" - _chdir(monkeypatch, tmp_path) - ordered = COMPOSE_CONFIG_YAML + ( - " scheduler:\n" - " image: ghcr.io/myorg/myapp:latest\n" - " labels:\n" - " deploy.role: app\n" - " deploy.strategy: drain-first\n" - ' deploy.order: "300"\n' - " healthcheck:\n" - ' test: ["CMD", "true"]\n' - ) - sched_old = json.dumps({"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) - sched_new = json.dumps({"ID": "new_sch_777", "Image": "ghcr.io/myorg/myapp:abc123"}) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(ordered), - _ok(), # scheduler: pull - _ok(sched_old + "\n"), # scheduler: ps - _ok(), # scheduler: stop - _ok(), # scheduler: rm - *WORKER_DRAIN, - *WEB_ROLL, - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: ps - _ok("healthy\n"), # worker: health - _ok(), # scheduler: compose up - _ok(sched_new + "\n"), # scheduler: ps - _ok("healthy\n"), # scheduler: health - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 0 - cmds = _commands(mock_process) assert ( - _index(cmds, "docker stop", "old_sch_666") - < _index(cmds, "docker stop", "old_wrk_333") - < _index(cmds, "--scale web=2") - < _index(cmds, "--scale worker=1 worker") - < _index(cmds, "--scale scheduler=1 scheduler") + out.index("would drain running containers first (3660s timeout)") + < out.index("would scale to 2") + < out.index("would start on v2") ) + assert out.index("▸ worker") < out.index("▸ scheduler") -def test_one_start_failure_does_not_strand_the_others(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - two = COMPOSE_CONFIG_YAML + ( - " scheduler:\n" - " image: ghcr.io/myorg/myapp:latest\n" - " labels:\n" - " deploy.role: app\n" - " deploy.strategy: drain-first\n" - " healthcheck:\n" - ' test: ["CMD", "true"]\n' - ) - sched_old = json.dumps({"ID": "old_sch_666", "Image": "ghcr.io/myorg/myapp:v1.2.0"}) - sched_new = json.dumps({"ID": "new_sch_777", "Image": "ghcr.io/myorg/myapp:abc123"}) - monkeypatch.setattr( - "flow_deploy.deploy._wait_for_healthy", lambda ctr_id, *a: ctr_id != "new_wrk_444" - ) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(two), - # Same order, so file order breaks the tie: scheduler drains first. - _ok(), # scheduler: pull - _ok(sched_old + "\n"), # scheduler: ps - _ok(), # scheduler: stop - _ok(), # scheduler: rm - *WORKER_DRAIN, - _ok(), # web: pull - _ok(), # web: scale to 2 - _ok(WEB_CONTAINER_OLD + "\n" + WEB_CONTAINER_NEW + "\n"), # web: ps - _ok(), # web: stop old - _ok(), # web: rm old - _ok(), # web: scale back - _ok(), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: ps (then unhealthy) - _ok(), # worker: stop unhealthy new - _ok(), # worker: rm unhealthy new - _ok(), # scheduler: compose up - _ok(sched_new + "\n"), # scheduler: ps (healthy) - _ok(), # git restore - _ok(), # worker: restore on old tag - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - cmds = _commands(mock_process) - assert any("--scale scheduler=1 scheduler" in c for c in cmds) - # Only the failed worker goes back; the healthy new scheduler stays. - assert "--scale worker=1 worker" in cmds[-1] - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - - -def test_rolling_failure_after_another_shipped_still_restores_drained( - mock_process, monkeypatch, tmp_path -): - _chdir(monkeypatch, tmp_path) - with_api = COMPOSE_CONFIG_YAML + ( - " api:\n" - " image: ghcr.io/myorg/myapp:latest\n" - " labels:\n" - " deploy.role: app\n" - " healthcheck:\n" - ' test: ["CMD", "true"]\n' - ) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(with_api), - *WORKER_DRAIN, - *WEB_ROLL, # web ships - _err("pull failed"), # api: pull - _ok(), # git restore - _ok(), # worker: restore on old tag - ] - ) - # Expand-then-contract keeps the old worker compatible with whatever web - # migrated, so it comes back rather than leaving the queue unworked. - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert mock_process.calls[-1][2] == {"DEPLOY_TAG": "v1.2.0"} - assert not (tmp_path / ".git" / "deploy-lock").exists() +def test_ties_in_deploy_order_follow_file_order(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + tied = stack(web=app(100), a=app(300, "drain-first"), b=app(300, "drain-first")) + host = FakeHost(tied, running={"web": ["v1"], "a": ["v1"], "b": ["v1"]}) + host.install(monkeypatch) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.index("docker stop", " b0") < host.index("docker stop", " a0") + assert host.index("--scale a=1 a") < host.index("--scale b=1 b") -def test_start_compose_failure_removes_partial_containers(mock_process, monkeypatch, tmp_path): - _chdir(monkeypatch, tmp_path) - mock_process.responses.extend( - [ - *_git_preflight(), - _ok(COMPOSE_CONFIG_YAML), - *WORKER_DRAIN, - *WEB_ROLL, - _err("partial"), # worker: compose up - _ok(WORKER_NEW + "\n"), # worker: docker ps (one started anyway) - _ok(), # worker: stop - _ok(), # worker: rm - _ok(), # git restore - ] - ) - assert deploy(tag="abc123", cmd=COMPOSE_CMD) == 1 - assert any("docker rm new_wrk_444" in c for c in _commands(mock_process)) +def test_drain_first_service_can_skip_its_healthcheck(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + beat = app(200, "drain-first", skip=True, healthcheck=False) + host = FakeHost(stack(web=app(), beat=beat), running={"web": ["v1"], "beat": ["v1"]}) + host.install(monkeypatch) + host.unhealthy_services.add(("beat", "v2")) # never consulted + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert host.running() == {"web": ["v2"], "beat": ["v2"]} def test_parse_strategy_defaults_to_rolling(): services = config.parse_services({"services": {"web": {"labels": {"deploy.role": "app"}}}}) assert services[0].strategy == "rolling" assert not services[0].drains_first - - -def test_image_tag(): - assert _image_tag("ghcr.io/org/app:v1.2.0") == "v1.2.0" - assert _image_tag("localhost:5000/app:abc") == "abc" - assert _image_tag("localhost:5000/app") is None - assert _image_tag("app") is None - assert _image_tag("ghcr.io/org/app@sha256:abc") is None - assert _image_tag("ghcr.io/org/app:v1.2.0@sha256:abc") == "v1.2.0" diff --git a/tests/test_git.py b/tests/test_git.py index f8c183e..ee12459 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -33,6 +33,8 @@ def test_fetch_success(mock_process): mock_process.responses.append(_ok()) result = fetch() assert result.returncode == 0 + # Version tags are fetched, and a re-pushed tag moves locally. + assert mock_process.calls[0][1] == ["git", "fetch", "--tags", "--force", "origin"] def test_current_sha(mock_process): diff --git a/tests/test_log.py b/tests/test_log.py index 1fa1736..f0e7b52 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -105,6 +105,23 @@ def test_service_end_github_actions(capsys, monkeypatch): assert "::endgroup::" in out +def test_warning(capsys): + from flow_deploy.log import warning + + warning("heads up") + captured = capsys.readouterr() + assert "WARNING: heads up" in captured.err + assert "::warning::" not in captured.out + + +def test_warning_github_actions_annotates(capsys, monkeypatch): + monkeypatch.setenv("GITHUB_ACTIONS", "true") + from flow_deploy.log import warning + + warning("heads up") + assert "::warning::heads up" in capsys.readouterr().out + + def test_error(capsys): from flow_deploy.log import error diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py index d7cbe61..96f4d48 100644 --- a/tests/test_rolling_parity.py +++ b/tests/test_rolling_parity.py @@ -1,15 +1,16 @@ -"""Rolling deploys behave exactly as on master (0.3.0). +"""Rolling deploys behave as on master (0.3.0), apart from listed, deliberate changes. fixtures/rolling_master.json was recorded by running tests/rolling_scenarios.py -against master's flow_deploy: every docker/compose/git command, its env, the -exit code, and whether the lock was left behind. A project that doesn't use -drain-first must see the same commands in the same order. Agreed departures -are listed in DELIBERATE_CHANGES; signals are covered separately in -test_deploy_failures.py (master exited without restoring git; this branch -restores it). +against master's flow_deploy on a FakeHost: every docker/compose/git command, +its env, the exit code, and whether the lock was left behind. A project that +doesn't use drain-first must see the same commands in the same order, once +the departures below are applied to master's record. Signals are covered +separately in test_deploy_failures.py (master exited without restoring git; +this branch restores it). """ import json +import re from pathlib import Path import pytest @@ -20,8 +21,8 @@ MASTER = json.loads((Path(__file__).parent / "fixtures" / "rolling_master.json").read_text()) -# Agreed departures from master, by scenario. -DELIBERATE_CHANGES = { +# Agreed departures from master's outcome, by scenario. +DELIBERATE_OUTCOMES = { # A failed git restore exits 3 ("needs a person") instead of 1, and the # lock is released: master's retained lock was broken by the next deploy # anyway, since acquire() clears locks whose PID has exited. @@ -29,28 +30,70 @@ } -def deliberate_command_changes(calls): - """master's commands, with the agreed command-level fix applied. +def is_snapshot(args): + """The pre-deploy checks: what each app service runs, aliased by image ID, + and that no other compose project runs in this directory. Plus a revert's + look for stopped leftovers that compose would otherwise restart. - Scale-back gains --no-recreate. On master, scale-back after a failed - health check ran `compose up --scale svc=1` with the new tag, which - recreated the surviving old container on the new, failing image. Found - by tests/integration (test_rolling_service_fails_its_healthcheck). + New on this branch, issued before anything changes, so a failure can + restore the exact image each service ran whatever tag it was started + from (a version, a sha, a moved :latest, or none). """ + line = " ".join(args) + return ( + (args[:2] == ["docker", "ps"] and "status=restarting" in line) + or (args[:2] == ["docker", "ps"] and "project.working_dir=" in line) + or (args[:2] == ["docker", "ps"] and "status=created" in line) + or args[:4] == ["docker", "inspect", "--format", "{{.Id}} {{.Image}}"] + or args[:2] == ["docker", "tag"] + ) + + +def as_on_this_branch(calls, tag): + """master's commands with the agreed command-level changes applied.""" fixed = [] for args, env in calls: - if args[-6:-2] == ["up", "-d", "--no-deps", "--scale"] and args[-2].endswith("=1"): - args = args[:-3] + ["--no-recreate"] + args[-3:] # after --no-deps + if args == ["git", "fetch", "origin"]: + # Version tags are fetched, and a re-pushed tag moves locally. + args = ["git", "fetch", "--tags", "--force", "origin"] + elif args[-1:] == ["config"]: + # Rendered with the deploy tag, so image refs are the ones deployed. + env = {"DEPLOY_TAG": tag} + elif args[-6:-2] == ["up", "-d", "--no-deps", "--scale"] and args[-2].endswith("=1"): + # Scale-back gains --no-recreate. On master, scale-back after a + # failed health check recreated the surviving old container on the + # new, failing image. Found by tests/integration. + args = args[:-3] + ["--no-recreate"] + args[-3:] fixed.append([args, env]) return fixed +def by_appearance(calls): + """Container IDs renamed in order of first mention, per service. + + FakeHost numbers containers from one counter, so a container master + created and this branch doesn't would shift every later ID. + """ + names = {} + out = [] + for args, env in calls: + renamed = [] + for arg in args: + m = re.fullmatch(r"(web|worker)\d{3}", arg) + if m: + seen = [v for k, v in names.items() if k.startswith(m.group(1))] + arg = names.setdefault(arg, f"{m.group(1)}#{len(seen) + 1}") + renamed.append(arg) + out.append([renamed, env]) + return out + + def test_scenarios_and_fixture_agree(): assert set(SCENARIOS) == set(MASTER) @pytest.mark.parametrize("name", sorted(SCENARIOS)) -def test_rolling_deploy_matches_master(name, monkeypatch, tmp_path, capsys): +def test_rolling_deploy_matches_master(name, monkeypatch, tmp_path): # record() swaps process.run itself; restore it after the test. monkeypatch.setattr(process, "run", process.run) monkeypatch.setattr(process, "run_streaming", process.run_streaming) @@ -59,9 +102,26 @@ def test_rolling_deploy_matches_master(name, monkeypatch, tmp_path, capsys): observed = record(deploy_mod, process, name, str(tmp_path)) - expected_calls = deliberate_command_changes(MASTER[name]["calls"]) - assert observed["calls"] == expected_calls, f"{name}: commands differ from master" + calls = [[args, env] for args, env in observed["calls"] if not is_snapshot(args)] + tag = SCENARIOS[name][2].get("tag", "v2") or "prev123abc" + expected_calls = as_on_this_branch(MASTER[name]["calls"], tag) + if name == "cutover_stop_fail": + # Deliberate: no scale-back while the old container may still be + # running. With two containers left, scale-back removes one, and + # with --no-recreate compose might remove the new one. + expected_calls = [c for c in expected_calls if c[0][-2:] != ["web=1", "web"]] + if name == "second_service_health_abort": + # Deliberate: a later service's failure rolls back services that had + # already shipped. master left web on the new tag beside a worker on + # the old one; this branch rolls web back to the image it ran. + rollback = calls[len(expected_calls) :] + calls = calls[: len(expected_calls)] + composes = [env for args, env in rollback if args[:2] == ["docker", "compose"]] + assert composes and all(env["DEPLOY_TAG"].startswith("flow-deploy-") for env in composes) + assert any(args[-1] == "web" and "--scale" in args for args, _ in rollback) + assert by_appearance(calls) == by_appearance(expected_calls), f"{name}: commands differ" + expected = {"code": MASTER[name]["code"], "lock_left": MASTER[name]["lock_left"]} - expected.update(DELIBERATE_CHANGES.get(name, {})) + expected.update(DELIBERATE_OUTCOMES.get(name, {})) assert observed["code"] == expected["code"] assert observed["lock_left"] == expected["lock_left"] From 72a559e2e33142f6cdae64949517ceb1d26fc00f Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 00:10:11 -0600 Subject: [PATCH 12/19] Keep flow-deploy tag's stdout clean on GitHub Actions Under GITHUB_ACTIONS, log.error also writes an ::error:: annotation to stdout. A failing `flow-deploy tag` therefore printed that annotation where scripts read the tag. `tag` and `compose` now report "can't tell" on stderr only. The unit suite assumed GITHUB_ACTIONS was unset, so it failed in CI (test_warning, test_tag_unknown_exits_1). An autouse fixture now clears it; tests that need annotations set it explicitly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- src/flow_deploy/cli.py | 28 +++++++++++++++------------- tests/conftest.py | 6 ++++++ tests/test_deployed.py | 10 ++++++++++ 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/flow_deploy/cli.py b/src/flow_deploy/cli.py index 0f92bb0..632ad8f 100644 --- a/src/flow_deploy/cli.py +++ b/src/flow_deploy/cli.py @@ -66,15 +66,24 @@ def tag_cmd(): From the running app containers when they agree, else the last deploy's record. For scripts: DEPLOY_TAG=${DEPLOY_TAG:-$(flow-deploy tag)}. """ + tag, how = _deployed_tag() + click.echo(tag) + + +def _deployed_tag(compose_cmd: list[str] | None = None) -> tuple[str, str]: + """deployed.current(), or exit 1 with the reason. + + The reason goes to stderr only, never as a GitHub Actions annotation on + stdout: scripts capture `flow-deploy tag`'s stdout as the tag. + """ try: - tag, how = deployed.current() + tag, how = deployed.current(compose_cmd) except RuntimeError as e: - log.error(str(e)) - sys.exit(1) + tag, how = None, str(e) if tag is None: - log.error(f"can't tell which tag is deployed: {how}") + click.echo(f"Error: can't tell which tag is deployed: {how}", err=True) sys.exit(1) - click.echo(tag) + return tag, how @main.command( @@ -94,14 +103,7 @@ def compose_cmd(args): command = compose.resolve_command() tag = os.environ.get("DEPLOY_TAG") if not tag: - try: - tag, how = deployed.current(command) - except RuntimeError as e: - log.error(str(e)) - sys.exit(1) - if tag is None: - log.error(f"can't tell which tag is deployed: {how}") - sys.exit(1) + tag, how = _deployed_tag(command) click.echo(f"DEPLOY_TAG={tag} (from {how})", err=True) sys.exit(process.run_streaming(command + list(args), env={"DEPLOY_TAG": tag})) diff --git a/tests/conftest.py b/tests/conftest.py index 0fdbfd0..dbc3308 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,6 +3,12 @@ import pytest +@pytest.fixture(autouse=True) +def _not_on_github_actions(monkeypatch): + """Plain log output, as on a host; tests that need annotations set it.""" + monkeypatch.delenv("GITHUB_ACTIONS", raising=False) + + @pytest.fixture def mock_process(monkeypatch): """Mock process.run and process.run_streaming for tests.""" diff --git a/tests/test_deployed.py b/tests/test_deployed.py index 57115f0..878d00c 100644 --- a/tests/test_deployed.py +++ b/tests/test_deployed.py @@ -156,6 +156,16 @@ def test_tag_unknown_exits_1(host): assert "can't tell which tag is deployed" in result.stderr +def test_tag_failure_keeps_stdout_clean_on_github_actions(host, monkeypatch): + """No ::error:: annotation on stdout: a script would capture it as the tag.""" + monkeypatch.setenv("GITHUB_ACTIONS", "true") + host.fail("docker compose config") + result = CliRunner().invoke(main, ["tag"]) + assert result.exit_code == 1 + assert result.stdout == "" + assert "can't tell which tag is deployed" in result.stderr + + def test_tag_compose_failure_exits_1(host): host.fail("docker compose config") assert CliRunner().invoke(main, ["tag"]).exit_code == 1 From 346fbc2bb8027455ec3c2537a9b1fdea26a86fb7 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 00:51:52 -0600 Subject: [PATCH 13/19] Restore by git tags and SHAs, never local alias tags A revert no longer creates flow-deploy- tags on the host. Restores are named by git, so nothing is stashed on the server. - The deploy records the tag each service was started from, and a revert uses it when all of these hold: - it's a git ref (git rev-parse --verify) - it still names the running image locally - it isn't the tag being deployed, which this deploy pulls - Otherwise (:latest, a moved tag, a digest, no tag, a redeploy of the same tag) a revert uses the full SHA of the commit checked out before the deploy, which CI pushes every image under. - A ref like repo:v1@sha256:... is checked as repo:v1, the name a revert renders. - Redeploying the commit that's already running leaves no other git name for its build. If that image was rebuilt under the same tag, a revert restores the rebuild. The deploy warns up front. Master didn't roll shipped services back at all. Fixes two compatibility problems in the previous commits: - App services whose image can't be tagged (e.g. build-only) no longer abort every deploy, since the snapshot needs no tag to proceed. - The renamed-project guard only refuses when another compose project runs this deploy's services in the directory. An unrelated project sharing the directory no longer blocks deploys. flow-deploy tag treats one image running under :latest plus one other tag, as after a revert from :latest, as that other tag. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 44 +++++++------ SPEC.md | 29 +++++---- docs/github-actions.md | 6 +- src/flow_deploy/containers.py | 23 ++++--- src/flow_deploy/deploy.py | 81 ++++++++++++----------- src/flow_deploy/deployed.py | 13 ++-- src/flow_deploy/git.py | 6 ++ tests/fake_host.py | 33 +++++++--- tests/integration/test_deploys.py | 68 +++++++++++++++----- tests/test_containers.py | 35 ++++++---- tests/test_deploy.py | 103 ++++++++++++++++++++---------- tests/test_deployed.py | 29 ++++----- tests/test_drain_first.py | 18 ++++-- tests/test_git.py | 15 +++++ tests/test_rolling_parity.py | 15 +++-- 15 files changed, 328 insertions(+), 190 deletions(-) diff --git a/README.md b/README.md index 3cbe564..1ee24d9 100644 --- a/README.md +++ b/README.md @@ -136,17 +136,24 @@ A rollback runs old code against whatever the new code already did (a migration, say), so this relies on the usual expand-then-contract discipline: old code keeps working against the new schema. -What "previous" means is read from the containers, not from git or `:latest`. -Before changing anything, the deploy records the image each app service is -running (the most common one if its containers disagree, with a warning) and -gives it a local alias, `:flow-deploy-`. A revert runs -`compose up` with that alias in `DEPLOY_TAG`, so it restores the exact image -even if the service was started from `:latest`, from a tag that has since been -re-pushed, from a digest, or from no tag at all. See [Image Tags](#image-tags). -If an image can't be aliased, or containers of a differently named compose -project run in the same directory (a release that renamed the project would -start a second stack beside the first), the deploy stops before changing -anything. +What "previous" means is read from the containers, and named by git. Before +changing anything, the deploy records the image each app service is running +(the most common one if its containers disagree, with a warning) and the tag +it was started from. A revert runs `compose up` with that tag in `DEPLOY_TAG` +when it's a git ref (a release tag or a commit SHA) that still names the +running image and isn't the tag being deployed (which this deploy pulls). +Otherwise (`:latest`, a tag re-pushed since, a digest, no tag, a redeploy of +the same tag) +it uses the SHA of the commit that was checked out before the deploy, so CI +must push every image under its full commit SHA (see [Image Tags](#image-tags)). +One case has no git name for the previous build: redeploying the commit that's +already running. If its image was rebuilt and re-pushed under the same tag, a +revert restores that commit as pulled now; the deploy warns when it sees this. +(Before this release, shipped services weren't rolled back at all.) +Nothing is tagged or written on the host. If another compose project runs this +deploy's services in the same directory (a release that renamed the project +would start a second stack beside the first), the deploy stops before +changing anything. A signal reverts the same way, and so does an unexpected error. The signals are SIGTERM (a timeout or shutdown), Ctrl-C (SIGINT), and SIGHUP (a hung-up @@ -189,7 +196,7 @@ The deliberate changes for rolling-only projects, each pinned by that test: - A later service's failure rolls back services that already shipped. Previously they stayed on the new tag beside services on the old one. -- The deploy snapshots and aliases each service's running image first. +- The deploy records each service's running image and restore tag first. - `git fetch --tags --force origin`, so release tags arrive and a re-pushed tag moves. - `compose config` is rendered with the deploy's `DEPLOY_TAG`. @@ -221,7 +228,8 @@ services: just as well. The tag is used twice: `git checkout --detach ` (lightweight and annotated tags and SHAs all work; tags are fetched with `--force`, so a re-pushed tag moves), and as the image tag compose pulls and runs. CI pushes the -image under every tag it might deploy by, typically the version and the SHA. The +image under every tag it might deploy by: the version, and always the full +commit SHA, which is also what a revert falls back to. The compose file must name each app image with it: ```yaml @@ -250,12 +258,10 @@ The deployed tag is read from the running app containers when they all agree, else from `.git/deploy-tag` (written by every successful whole-project deploy) when nothing is running. Mixed or untagged images, or nothing to go on, are an error ("set DEPLOY_TAG"), never a guess. `flow-deploy status` shows it too. -After a revert, services recreated from the snapshot run the -`flow-deploy-` alias of their previous image, and the record holds it; -a service that kept its old container still shows its old tag. Either way the -image is the one that ran before, and when every service runs that one image -the deployed tag is the alias. An alias is a local tag: `flow-deploy compose -up` works with it, `pull` won't. The next deploy replaces it. +After a revert, the deployed tag is the release tag or SHA that was +restored. After a revert from `:latest`, a kept container still says `latest` +while recreated ones run the previous SHA; when they all run one image, the +SHA is the answer. If the project has a compose wrapper (`script/prod`), make the wrapper default `DEPLOY_TAG` the same way, so `script/prod up -d` is safe too: diff --git a/SPEC.md b/SPEC.md index 607b606..4e80cea 100644 --- a/SPEC.md +++ b/SPEC.md @@ -40,17 +40,18 @@ The deploy runs as a single transaction — `flow-deploy deploy` owns the full l 0c. Record previous SHA previous_sha = git rev-parse HEAD 0d. Checkout (detached) git checkout --detach (skipped when --tag is omitted) 0e. Render config DEPLOY_TAG= config -0f. Project check docker ps by compose's working_dir label: containers - of another compose project here → refuse +0f. Project check docker ps by compose's working_dir and service labels: + another compose project running these services here → refuse 0g. Snapshot for each app service: docker ps (running + restarting), docker inspect → image IDs; the most common one is - "previous" (warn if they differ), aliased as - docker tag :flow-deploy- - in the config's repo and the container's own - If any of this fails → restore repo, exit 1 + "previous" (warn if they differ). Its restore tag is the + tag it was started from if that's a git ref + (git rev-parse --verify) still naming that image + (docker image inspect) and isn't ; else + If listing or inspecting fails → restore repo, exit 1 ``` -The snapshot is what a revert restores: the exact image each service was running, whatever tag (or none) it was started from (§2.8). +The snapshot is what a revert restores: the image each service was running, named by a git tag or commit SHA (§2.8). **For each service with `deploy.role=app`, in the order they appear in the compose file:** @@ -81,17 +82,17 @@ R1. Restore repo git checkout --detach R1b. Failed service remove stopped containers its abort couldn't remove R2. Roll back shipped for each rolling service that already deployed, in reverse order: remove its stopped leftovers (compose would restart them), then - DEPLOY_TAG= rolling deploy (no pull) back to its + DEPLOY_TAG= rolling deploy (no pull) back to its previous image; if a container on the previous image survived the cutover, remove the new ones instead; a service that had no containers is removed R3. Restore drain-first for each drained service, in deploy order: remove its stopped leftovers on other images, stop + remove containers not on its previous image, - DEPLOY_TAG= up -d --no-deps + DEPLOY_TAG= up -d --no-deps --no-recreate --scale = (left stopped if it wasn't running before) -R4. Record .git/deploy-tag = the restored alias (cleared if services differ) +R4. Record .git/deploy-tag = the restore tag (cleared if services differ) R5. Release the lock always ``` @@ -260,11 +261,11 @@ services: # or image: ${DOCKER_IMAGE}, with DOCKER_IMAGE=ghcr.io/myorg/myapp:${DEPLOY_TAG:-latest} in .env ``` -CI must push the image under every tag it may deploy by (the version, and the SHA as a fallback). The deploy renders its compose config with `DEPLOY_TAG` set and warns when an app image doesn't end in `:`; such a service keeps whatever image the compose file names. +CI must push the image under every tag it may deploy by: the version, and always the full commit SHA, which a revert falls back to. The deploy renders its compose config with `DEPLOY_TAG` set and warns when an app image doesn't end in `:`; such a service keeps whatever image the compose file names. -**What's running.** Restores never trust a tag name. The pre-deploy snapshot (§2.2, 0g) records each service's running image ID and tags it locally as `:flow-deploy-` (the full ID, so it can't collide), under both the new compose config's repo and the repo the container was started from. A revert deploys that alias, so it gets the exact image back even when the service was started from `:latest`, from a tag re-pushed since, from a digest, or untagged. If an alias can't be created the deploy stops before changing anything. Aliases are local only and are never pushed. +**What's running.** Restores are named by git: a release tag or a commit SHA. The pre-deploy snapshot (§2.2, 0g) records each service's running image ID and the tag it was started from. A revert uses that tag when it is a git ref, still names the running image locally, and isn't the tag being deployed (the deploy pulls that, which would move a re-pushed tag). Otherwise (started from `:latest`, from a tag re-pushed since, from a digest, untagged, or a redeploy of the same tag) it uses the full SHA of the commit checked out before the deploy, so CI must push every image under its full commit SHA. If that image isn't in the registry the restore fails and the deploy exits 3. Redeploying the commit that's already checked out leaves no other git name for the running build: if its image was rebuilt under the same tag, a revert restores the rebuild, and the deploy warns up front. flow-deploy creates no tags and writes nothing in the working tree. -**What's deployed.** `flow-deploy tag` (§4.7) answers "which tag is deployed here": the tag of the running app containers when they all agree; otherwise, when nothing is running, `.git/deploy-tag`. Mixed or untagged images are an error, never a guess. The record is written after every successful deploy of all app services, rewritten to the restored alias after a revert (running containers still take precedence: one that kept its old container shows its old tag), and cleared by a `--service` deploy that leaves some app services out (they're then on different tags). +**What's deployed.** `flow-deploy tag` (§4.7) answers "which tag is deployed here": the tag of the running app containers when they all agree; if they run one image under `:latest` and one other tag (after a revert from `:latest`), that other tag; otherwise, when nothing is running, `.git/deploy-tag`. Anything else mixed, or untagged, is an error, never a guess. The record is written after every successful deploy of all app services, rewritten to the restore tag after a revert, and cleared by a `--service` deploy that leaves some app services out (they're then on different tags). **Manual commands.** With `${DEPLOY_TAG:-latest}`, running ` up -d` on the host with `DEPLOY_TAG` unset would move every service to `:latest`. Use `flow-deploy compose ` (§4.8), which sets `DEPLOY_TAG` to the deployed tag, or have the wrapper default it (§3.1). @@ -419,7 +420,7 @@ Print the deployed tag (§2.8) to stdout, and nothing else, for scripts: DEPLOY_TAG=${DEPLOY_TAG:-$(flow-deploy tag)} ``` -Exits 1 with the reason on stderr when it can't tell (mixed or untagged images, or nothing running and no record). +Exits 1 with the reason on stderr when it can't tell (images that disagree or are untagged, as in §2.8, or nothing running and no record). ### 4.8 `flow-deploy compose` diff --git a/docs/github-actions.md b/docs/github-actions.md index e4a40d7..788cf90 100644 --- a/docs/github-actions.md +++ b/docs/github-actions.md @@ -14,7 +14,7 @@ The deploy pipeline: The deploy tag is both the git ref checked out on the server and the image tag pulled, so: -- **Push the image under every tag you deploy by.** Typically the version tag (`v1.4.0`) for releases and the full commit SHA for everything else. `:latest` is optional; flow-deploy never relies on it. +- **Push the image under every tag you deploy by, and always under the full commit SHA.** Typically the version tag (`v1.4.0`) for releases plus `${{ github.sha }}`. A failed deploy restores by the tag that was running when it's a git ref, else by the SHA of the commit that was checked out. `:latest` is optional; flow-deploy never relies on it. - **Name every app image with `DEPLOY_TAG`**, directly or through `.env`: ```yaml @@ -33,7 +33,7 @@ A bare `DOCKER_IMAGE=ghcr.io/yourorg/yourproject` (no tag) always runs `:latest` - **Use `flow-deploy compose` for manual commands on the server** (`flow-deploy compose up -d`, `flow-deploy compose run --rm web ...`). With `${DEPLOY_TAG:-latest}`, a plain `docker compose up -d` would move every service to `:latest`; `flow-deploy compose` sets `DEPLOY_TAG` to the deployed tag. Or have `script/prod` default it (see the README's Image Tags section). -Version tags can be lightweight or annotated, and a re-pushed tag is picked up: flow-deploy runs `git fetch --tags --force`. If a deploy fails, every service goes back to the exact image it was running, whatever it was tagged. +Version tags can be lightweight or annotated, and a re-pushed tag is picked up: flow-deploy runs `git fetch --tags --force`. If a deploy fails, every service goes back to the image it was running, named by its release tag or commit SHA. ## Prerequisites @@ -291,7 +291,7 @@ The rendered image doesn't end in `:`, so the deploy doesn't change what th CI didn't push the image under that tag. Push the version tag as well as the SHA, or deploy by SHA. **`can't tell which tag is deployed`** from `flow-deploy tag` or `flow-deploy compose`: -Services run different or untagged images, or nothing is running and no deploy is recorded. Set it explicitly: `DEPLOY_TAG=v1.4.0 flow-deploy compose up -d`. +Services run different or untagged images (one image under `:latest` plus one other tag is fine), or nothing is running and no deploy is recorded. Set it explicitly: `DEPLOY_TAG=v1.4.0 flow-deploy compose up -d`. **Health check timeout:** Increase the timeout via label: `deploy.healthcheck.timeout: 300`. Check that your app's health endpoint responds within the Docker healthcheck interval. diff --git a/src/flow_deploy/containers.py b/src/flow_deploy/containers.py index fb0ab41..0289467 100644 --- a/src/flow_deploy/containers.py +++ b/src/flow_deploy/containers.py @@ -41,10 +41,13 @@ def list_containers_for_service( return containers -def other_projects_here(project: str) -> set[str] | None: - """Compose projects other than ``project`` with running containers in this directory. +def other_projects_here(project: str, services: list[str]) -> set[str] | None: + """Other compose projects running any of ``services`` in this directory. - Read from compose's working_dir label. None if docker ps fails. + A release that renamed the project would show up this way: the old + project's containers run the same services. Another project that merely + shares the directory (different services) doesn't count. Read from + compose's working_dir and service labels. None if docker ps fails. """ cwd = os.getcwd() dirs = {cwd} @@ -62,12 +65,15 @@ def other_projects_here(project: str) -> set[str] | None: "--filter", f"label=com.docker.compose.project.working_dir={d}", "--format", - '{{.Label "com.docker.compose.project"}}', + '{{.Label "com.docker.compose.project"}} {{.Label "com.docker.compose.service"}}', ] ) if result.returncode != 0: return None - found |= {line.strip() for line in result.stdout.splitlines() if line.strip()} + for line in result.stdout.splitlines(): + parts = line.split() + if len(parts) == 2 and parts[1] in services: + found.add(parts[0]) return found - {project} @@ -172,6 +178,7 @@ def image_ids(container_ids: list[str]) -> dict[str, str] | None: return found -def tag_image(image_id: str, ref: str) -> bool: - """Point the local tag ``ref`` at ``image_id``. Returns True on success.""" - return process.run(["docker", "tag", image_id, ref]).returncode == 0 +def local_image_id(ref: str) -> str | None: + """The ID of the local image ``ref`` names (``repo:tag``), or None if there's none.""" + result = process.run(["docker", "image", "inspect", "--format", "{{.Id}}", ref]) + return result.stdout.strip() or None if result.returncode == 0 else None diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 774fd2a..26ec1d0 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -70,7 +70,7 @@ class Previous: replicas: int = 0 image_id: str = "" # the image its containers ran (the most common, if mixed) image_ref: str = "" # how docker named it: repo:tag, repo@digest, ... - restore_tag: str | None = None # a DEPLOY_TAG that brings image_id back + restore_tag: str | None = None # the git tag or SHA that brings image_id back @dataclass @@ -236,12 +236,12 @@ def _deploy_locked( # A release that renames the compose project would start a second stack # beside the running one, and snapshot (so revert) nothing. - others = containers.other_projects_here(project) + others = containers.other_projects_here(project, [s.name for s in app_services]) if others is None: log.error("could not list this directory's containers; nothing was changed") elif others: log.error( - f"containers from compose project(s) {', '.join(sorted(others))} are running " + f"compose project(s) {', '.join(sorted(others))} run this deploy's services " f"in this directory, but this commit's project is {project or '(unnamed)'}; " "a project rename can't be deployed in place. Nothing was changed." ) @@ -250,7 +250,7 @@ def _deploy_locked( # Before changing anything, record what each service is running, so any # failure can put back exactly that image. - if not _snapshot(run, app_services): + if not _snapshot(run, app_services, tag): return EXIT_FAILED if git.restore(run.previous_sha) else _degraded("git restore failed") # app_services is in deploy.order. Services start in that order and stop @@ -335,13 +335,12 @@ def _warn_untagged_images(services: list[config.ServiceConfig], tag: str) -> Non ) -def _snapshot(run: _Run, services: list[config.ServiceConfig]) -> bool: +def _snapshot(run: _Run, services: list[config.ServiceConfig], tag: str) -> bool: """Record what each service is running on ``run.previous``. False if Docker can't say. - Each running image gets a restore tag that names exactly it (see - _restore_tag); services sharing an image share one. + Each service gets the DEPLOY_TAG that brings its running image back: see + _restore_tag. """ - aliases: dict[tuple[tuple[str, ...], str], str | None] = {} for svc in services: ctrs = containers.list_containers_for_service( svc.name, project=run.project, statuses=("running", "restarting") @@ -360,40 +359,46 @@ def _snapshot(run: _Run, services: list[config.ServiceConfig]) -> bool: f"{svc.name} is running {len(counts)} different images; a revert " f"restores the most common, {prev.image_ref}" ) - # A revert renders the previous commit's compose file, whose image - # repo the running container's name records. The new config's repo - # covers a container whose tag has moved (docker ps shows an ID). - repos = {containers.image_repo(svc.image or "")} - if containers.image_tag(prev.image_ref) is not None or "@" in prev.image_ref: - repos.add(containers.image_repo(prev.image_ref)) - key = (tuple(sorted(repos)), prev.image_id) - if key not in aliases: - aliases[key] = _restore_tag(*key) - prev.restore_tag = aliases[key] - if prev.restore_tag is None: - # Never start a deploy that already can't be reverted exactly. - log.error( - f"could not tag {svc.name}'s running image ({prev.image_ref}) " - "for a revert; nothing was changed" - ) - return False + prev.restore_tag = _restore_tag(prev, run.previous_sha, tag) run.previous[svc.name] = prev return True -def _restore_tag(repos: tuple[str, ...], image_id: str) -> str | None: - """A DEPLOY_TAG that names exactly ``image_id``: a local alias of it. +def _restore_tag(prev: Previous, previous_sha: str | None, deploy_tag: str) -> str | None: + """The DEPLOY_TAG a revert brings ``prev.svc`` back with: a git tag or commit SHA. - ``repo:flow-deploy-`` in each of ``repos``, created now, before - anything changes. A revert then restores the image that was running, never - whatever ``:latest`` or a re-pushed tag has since come to mean, and it - works the same whether the container ran a version tag, a sha, ``:latest``, - a digest, or nothing nameable at all. + The tag the containers were started from, when it's a ref in this repo (a + release tag or a SHA) and still names the image they run. Not when it's + the tag being deployed: this deploy pulls that, which moves it if it was + re-pushed. Otherwise (``:latest``, a tag re-pushed since, a digest, no + tag, a redeploy of the same tag) the commit that was checked out before + the deploy, whose SHA CI pushes every image under. """ - alias = "flow-deploy-" + image_id.removeprefix("sha256:") - if all(repos) and all(containers.tag_image(image_id, f"{r}:{alias}") for r in repos): - return alias - return None + tag = containers.image_tag(prev.image_ref) + # Check repo:tag itself, which is what a revert renders: a ref like + # repo:v1@sha256:... names the digest, whatever repo:v1 says now. + named = f"{containers.image_repo(prev.image_ref)}:{tag}" + if ( + tag + and tag != deploy_tag + and git.is_ref(tag) + and containers.local_image_id(named) == prev.image_id + ): + return tag + if previous_sha == deploy_tag: + # Redeploying the commit that's running: git has no other name for the + # build running now, so a revert restores this commit as pulled now. + # (master didn't roll shipped services back at all.) + log.warning( + f"redeploying {deploy_tag}: if {prev.svc.name}'s image under it was rebuilt, " + "a revert restores the rebuild, not the build running now" + ) + elif previous_sha: + log.info( + f"note: {prev.svc.name} runs {prev.image_ref or prev.image_id[:19]}; a revert " + f"would restore it by the previous commit, {previous_sha[:12]}" + ) + return previous_sha def _degraded(problem: str) -> int: @@ -704,8 +709,8 @@ def _deploy_service( ) -> int: """Deploy a single service with a rolling cutover. - ``pull=False`` for a rollback to an image that's already local (and may - be a local alias the registry doesn't have). Returns SVC_OK, SVC_FAILED + ``pull=False`` for a rollback: the previous image is normally still + local, and compose pulls it if not. Returns SVC_OK, SVC_FAILED (old container still serving, nothing left behind), or SVC_DIRTY (failed, and cleaning up after itself failed too). """ diff --git a/src/flow_deploy/deployed.py b/src/flow_deploy/deployed.py index 5f49242..e8f2ac7 100644 --- a/src/flow_deploy/deployed.py +++ b/src/flow_deploy/deployed.py @@ -65,16 +65,15 @@ def current(compose_cmd: list[str] | None = None) -> tuple[str | None, str]: ids.append(ctr["ID"]) if len(tags) == 1 and None not in tags: return next(iter(tags)), "running containers" - if len(tags) > 1 and None not in tags: - # After a revert, a recreated service runs the flow-deploy- alias of - # the image a kept container still runs under its old tag: one image, - # two names. The alias names it exactly, so it answers. + if len(tags) > 1 and None not in tags and len(tags.keys() - {"latest"}) == 1: + # After a revert from :latest, a recreated service runs the previous + # commit's SHA while a kept container still says :latest. If they run + # one image, the SHA names it. images = containers.image_ids(ids) if images is None: raise RuntimeError("could not inspect the app containers (docker inspect failed)") - aliases = sorted(t for t in tags if t.startswith("flow-deploy-")) - if len(set(images.values())) == 1 and aliases: - return aliases[0], "running containers (one image under several tags)" + if len(set(images.values())) == 1: + return (tags.keys() - {"latest"}).pop(), "running containers (one image)" if tags: seen = ", ".join( f"{t or 'untagged'} ({', '.join(sorted(set(s)))})" for t, s in tags.items() diff --git a/src/flow_deploy/git.py b/src/flow_deploy/git.py index 27c0936..1d66c38 100644 --- a/src/flow_deploy/git.py +++ b/src/flow_deploy/git.py @@ -24,6 +24,12 @@ def current_sha() -> str: return result.stdout.strip() +def is_ref(ref: str) -> bool: + """True if ``ref`` names a commit in this repo: a tag, a branch, or a SHA.""" + result = process.run(["git", "rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"]) + return result.returncode == 0 + + def checkout_detached(sha: str) -> process.Result: """Checkout a specific SHA in detached HEAD mode.""" return process.run(["git", "checkout", "--detach", sha]) diff --git a/tests/fake_host.py b/tests/fake_host.py index 4d6cf31..0a421fc 100644 --- a/tests/fake_host.py +++ b/tests/fake_host.py @@ -57,13 +57,18 @@ def __init__(self, compose: dict, running: dict | None = None, project: str = "p self.sha = "prev123abc" self.dirty = False self.ctrs: list[Ctr] = [] - self.images: dict[str, str] = {} # tags known locally or in the registry -> image id + self.images: dict[str, str] = {} # local tags -> image id + # What the registry holds under tags not pulled yet (e.g. a commit SHA + # CI pushed); anything else pulls as image_id_for(tag). + self.registry: dict[str, str] = {} + self.not_refs: set[str] = {"latest"} # image tags that aren't git refs self.unpullable: set[str] = set() # tags compose pull can't fetch self.unhealthy: set[str] = set() # tags whose containers never become healthy self.unhealthy_services: set[tuple[str, str]] = set() # (service, tag) pairs self.stuck: set[str] = set() # services whose compose up succeeds but changes nothing self.same_created = False # docker ps shows one CreatedAt for every container - self.other_projects: list[str] = [] # other compose projects running in this dir + 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] self.hooks: list[tuple[str, object]] = [] # (substring, callback) run before a command self.calls: list[list[str]] = [] @@ -166,9 +171,9 @@ def run(self, args, env=None, cwd=None, new_session=False): return self._stop(args[-1]) if args[:2] == ["docker", "rm"]: return self._rm(args[-1]) - if args[:2] == ["docker", "tag"]: - self.images[args[3].rsplit(":", 1)[1]] = args[2] - return ok() + if args[:3] == ["docker", "image", "inspect"]: + image = self.images.get(args[-1].rsplit(":", 1)[-1]) + return ok(image + "\n") if image else fail("No such image") raise AssertionError(f"FakeHost: unexpected command {line!r}") def _git(self, args): @@ -176,6 +181,9 @@ def _git(self, args): return ok(" M file\n" if self.dirty else "") if args[:1] == ["fetch"]: return ok() + if args[:2] == ["rev-parse", "--verify"]: + ref = args[-1].removesuffix("^{commit}") + return fail() if ref in self.not_refs or ref.startswith("sha256") else ok(ref) if args[:1] == ["rev-parse"]: return ok(self.sha + "\n") if args[:2] == ["checkout", "--detach"]: @@ -189,7 +197,8 @@ def _compose(self, args, tag): if args[:1] == ["pull"]: if tag in self.unpullable: return fail(f"manifest for {REPO}:{tag} not found") - self.images.setdefault(tag, image_id_for(tag)) + # A pull fetches what the registry has now, moving a re-pushed tag. + self.images[tag] = self.registry.get(tag) or self.images.get(tag) or image_id_for(tag) return ok() if args[:1] == ["up"]: return self._up(args, tag) @@ -214,8 +223,10 @@ def _up(self, args, tag): replicas = 1 if "--scale" in args: replicas = int(args[args.index("--scale") + 1].split("=")[1]) - if tag not in self.images: - return fail(f"No such image: {REPO}:{tag}") + if tag not in self.images: # compose pulls a missing image + if tag in self.unpullable: + return fail(f"No such image: {REPO}:{tag}") + self.images[tag] = self.registry.get(tag, image_id_for(tag)) if service in self.stuck: return ok() live = self._live(service) @@ -241,8 +252,10 @@ def _up(self, args, tag): def _ps(self, args): if any(a.startswith("label=com.docker.compose.project.working_dir=") for a in args): # Compose project names of everything running in this directory. - projects = [self.project] * len(self.ctrs) + self.other_projects - return ok("".join(p + "\n" for p in projects)) + rows = [(self.project, c.service) for c in self.ctrs if c.state == "running"] + rows += [(p, c.service) for p in self.other_projects for c in self.ctrs] + rows += self.foreign_services + return ok("".join(f"{p} {s}\n" for p, s in rows)) service = None statuses = [] for flag, value in zip(args, args[1:]): diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index 80dfcd5..5063a91 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -5,7 +5,7 @@ import pytest -from tests.integration.conftest import SIGNALS, service, standard +from tests.integration.conftest import SIGNALS, run, service, standard ALL_V1 = {"web": ["v1"], "scheduler": ["v1"], "worker": ["v1"]} SERVICES = ("web", "scheduler", "worker") @@ -181,19 +181,21 @@ def test_lock_held_by_a_live_process_exits_2_and_changes_nothing(stack): assert lock.exists(), "another process's lock was released" -def test_digest_pinned_worker_is_restored_to_the_same_image(stack): - """A worker started from a digest (no tag at all) is restored by image ID.""" +def test_digest_pinned_worker_is_restored_by_the_previous_commit(stack): + """A worker started from a digest has no tag to go back to: it's restored + by the SHA of the commit that was checked out, which CI pushes.""" pinned_worker = service( 300, "drain-first", image="${WORKER_IMAGE:-${REGISTRY}/stub:${DEPLOY_TAG:-latest}}" ) - stack.commit("v1", standard(worker=pinned_worker)) + v1 = stack.commit("v1", standard(worker=pinned_worker)) + stack.push_image("v1", v1) stack.commit("unhealthy", standard(worker=pinned_worker)) stack.up("v1", extra={"WORKER_IMAGE": stack.digest("v1")}) result = stack.deploy("unhealthy") assert_reverted(stack, ALL_V1, result.returncode, result.stdout) - assert stack.image_refs("worker")[0].split(":")[-1].startswith("flow-deploy-") + assert stack.image_refs("worker") == [f"{stack.registry}/stub:{v1}"] def test_crash_looping_drain_first_worker_is_drained(stack): @@ -279,24 +281,26 @@ def test_failed_deploy_restores_the_version_that_was_running(stack): result.stdout, previous="v2", ) - # Restored by an alias of the exact image; the record follows it. The - # worker kept its v2 container, web was recreated on the alias: one image. - tag = stack.record()["tag"] - assert tag.startswith("flow-deploy-") - assert stack.flow("tag").stdout == f"{tag}\n" + # Restored by the release tag that was running; no tags made on the host. + assert stack.record()["tag"] == "v2" + assert stack.flow("tag").stdout == "v2\n" + assert stack.image_refs("web") == [f"{stack.registry}/stub:v2"] + local = run(["docker", "images", "--format", "{{.Tag}}", f"{stack.registry}/stub"]).stdout + assert "flow-deploy" not in local assert stack.flow("compose", "up", "-d", "--wait").returncode == 0 assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} -def test_first_deploy_from_latest_restores_that_image_after_latest_moves(stack): - """A host brought up by hand runs :latest. If :latest is re-pushed and - pulled before a failed deploy, the revert still restores the image that - was running, not what :latest names now.""" +def test_first_deploy_from_latest_restores_by_the_previous_commit(stack): + """A host brought up by hand runs :latest, which isn't a git ref and moves. + Even after it's re-pushed and pulled, the revert restores the image that + was running, by the SHA of the commit that was checked out.""" latest = f"latest-{os.getpid()}-{int(time.time())}" # don't move the shared :latest stack.push_image("v1", latest) image = f"${{REGISTRY}}/stub:${{DEPLOY_TAG:-{latest}}}" by_hand = standard(**{s: {**standard()["services"][s], "image": image} for s in SERVICES}) - stack.commit("v1", by_hand) + v1 = stack.commit("v1", by_hand) + stack.push_image("v1", v1) # CI pushes every build under its SHA bad = {**BAD_WORKER, "image": image} stack.commit("v3", {"services": {**by_hand["services"], "worker": bad}}) stack.up(None, ref="v1") @@ -373,8 +377,40 @@ def test_containers_of_another_project_name_here_are_refused(stack): result = stack.deploy("v2") assert result.returncode == 1, result.stdout + result.stderr - assert f"compose project(s) {other} are running" in result.stderr + assert f"compose project(s) {other} run this deploy's services" in result.stderr assert {svc: stack.container_ids(svc) for svc in SERVICES} == before assert stack.head() == stack.sha("v1") finally: stack.compose("-p", other, "down", "--timeout", "1", check=False) + + +def test_another_project_with_other_services_in_the_directory_is_fine(stack): + """A second compose project that shares the directory but runs different + services (say, an observability stack) isn't a rename: deploy proceeds.""" + stack.commit("v1", standard()) + stack.commit("v2", standard()) + stack.up("v1") + name = f"{stack.project}-obs" + run( + [ + "docker", + "run", + "-d", + "--name", + name, + "--label", + f"com.docker.compose.project={stack.project}obs", + "--label", + "com.docker.compose.service=grafana", + "--label", + f"com.docker.compose.project.working_dir={stack.repo}", + f"{stack.registry}/stub:v1", + ] + ) + try: + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} + finally: + run(["docker", "rm", "-f", name], check=False) diff --git a/tests/test_containers.py b/tests/test_containers.py index 93b0bb9..1562ef1 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -10,10 +10,10 @@ image_ids, image_repo, image_tag, + local_image_id, other_projects_here, remove_container, stop_container, - tag_image, ) @@ -179,19 +179,28 @@ def test_image_ids_missing_container(mock_process): assert image_ids(["aaa111", "ccc333"]) is None -def test_tag_image(mock_process): - mock_process.responses.append(process.Result(0, "", "")) - mock_process.responses.append(process.Result(1, "", "no such image")) - assert tag_image("sha256:one", "app:flow-deploy-one") is True - assert mock_process.calls[0][1] == ["docker", "tag", "sha256:one", "app:flow-deploy-one"] - assert tag_image("sha256:two", "app:flow-deploy-two") is False +def test_local_image_id(mock_process): + mock_process.responses.append(process.Result(0, "sha256:one\n", "")) + mock_process.responses.append(process.Result(1, "", "No such image")) + assert local_image_id("app:v1") == "sha256:one" + assert mock_process.calls[0][1] == [ + "docker", + "image", + "inspect", + "--format", + "{{.Id}}", + "app:v1", + ] + assert local_image_id("app:v9") is None def test_other_projects_here(mock_process, monkeypatch, tmp_path): monkeypatch.chdir(tmp_path) monkeypatch.setenv("PWD", str(tmp_path)) - mock_process.responses.append(process.Result(0, "proj\nproj\nold\n\n", "")) - assert other_projects_here("proj") == {"old"} + out = "proj web\nproj worker\nold web\nobs grafana\n\n" + mock_process.responses.append(process.Result(0, out, "")) + # obs shares the directory but runs none of these services: not a rename. + assert other_projects_here("proj", ["web", "worker"]) == {"old"} args = mock_process.calls[0][1] assert f"label=com.docker.compose.project.working_dir={tmp_path}" in args @@ -204,8 +213,8 @@ def test_other_projects_here_checks_the_shell_path_too(mock_process, monkeypatch monkeypatch.chdir(real) monkeypatch.setenv("PWD", str(tmp_path / "link")) mock_process.responses.append(process.Result(0, "", "")) - mock_process.responses.append(process.Result(0, "other\n", "")) - assert other_projects_here("proj") == {"other"} + mock_process.responses.append(process.Result(0, "other web\n", "")) + assert other_projects_here("proj", ["web"]) == {"other"} assert len(mock_process.calls) == 2 @@ -213,7 +222,7 @@ def test_other_projects_here_ignores_an_inherited_pwd(mock_process, monkeypatch, monkeypatch.chdir(tmp_path) monkeypatch.setenv("PWD", "/somewhere/else") mock_process.responses.append(process.Result(0, "", "")) - assert other_projects_here("proj") == set() + assert other_projects_here("proj", ["web"]) == set() assert len(mock_process.calls) == 1 @@ -221,4 +230,4 @@ def test_other_projects_here_failure(mock_process, monkeypatch, tmp_path): monkeypatch.chdir(tmp_path) monkeypatch.delenv("PWD", raising=False) mock_process.responses.append(process.Result(1, "", "daemon down")) - assert other_projects_here("proj") is None + assert other_projects_here("proj", ["web"]) is None diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 63db1a0..09fc372 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -153,12 +153,14 @@ def test_second_service_failing_rolls_the_first_back(host, tmp_path): assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 - # web had shipped v2; it's rolled back to the exact image it ran. + # web had shipped v2; it's rolled back by the release tag it ran. assert host.running_images() == before + assert host.running() == {"web": ["v1"], "worker": ["v1"]} assert host.sha == "prev123abc" - rollback = host.index("--scale web=2", "web") - assert host.calls[rollback] and host.commands().count("docker compose pull web") == 1 - assert record(tmp_path)["tag"].startswith("flow-deploy-") + scale_ups = [i for i, c in enumerate(host.commands()) if "--scale web=2 web" in c] + assert [host.envs[i] for i in scale_ups] == [{"DEPLOY_TAG": "v2"}, {"DEPLOY_TAG": "v1"}] + assert host.commands().count("docker compose pull web") == 1 + assert record(tmp_path)["tag"] == "v1" def test_rollback_failure_exits_3(host, capsys): @@ -168,14 +170,11 @@ def test_rollback_failure_exits_3(host, capsys): assert "web could not be rolled back" in capsys.readouterr().err -def test_no_restore_alias_means_no_deploy(host, capsys): - """A deploy that already couldn't be reverted exactly never starts.""" - host.fail("docker tag") - assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 - assert "could not tag web's running image" in capsys.readouterr().err - assert not any("compose pull" in c for c in host.commands()) - assert host.running() == {"web": ["v1"], "worker": ["v1"]} - assert host.sha == "prev123abc" +def test_no_local_tags_are_created(host): + """Restores go by git tags and SHAs: nothing is tagged on the host.""" + host.unhealthy_services.add(("worker", "v2")) + deploy(tag="v2", cmd=COMPOSE_CMD) + assert not any(c.startswith("docker tag") for c in host.commands()) def test_rollback_after_a_failed_cutover_cleanup_keeps_the_previous_container(host): @@ -254,7 +253,7 @@ def test_renamed_compose_project_is_refused(host, capsys): start a second stack beside it, and snapshot nothing to revert to.""" host.other_projects = ["oldname"] assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 - assert "compose project(s) oldname are running" in capsys.readouterr().err + assert "compose project(s) oldname run this deploy's services" in capsys.readouterr().err assert not any("compose pull" in c for c in host.commands()) assert host.sha == "prev123abc" @@ -289,33 +288,43 @@ def test_first_deploy_onto_an_empty_host(monkeypatch, tmp_path): # --------------------------------------------------------------------------- -def test_revert_from_latest_restores_the_exact_image_not_what_latest_became(monkeypatch, tmp_path): +def test_revert_from_latest_restores_by_the_previous_commit(monkeypatch, tmp_path): + """:latest isn't a git ref (and moves): the revert uses the SHA that was + checked out, which CI pushes every image under.""" chdir(monkeypatch, tmp_path) host = FakeHost(ROLLING, running={"web": ["latest"], "worker": ["latest"]}) host.install(monkeypatch) + host.registry["prev123abc"] = host.images["latest"] # CI pushed it by SHA too before = host.running_images() - # Something re-pulls :latest during the deploy: it now names a new build. - host.images["latest"] = "sha256:" + "f" * 64 + host.images["latest"] = "sha256:" + "f" * 64 # something re-pulled :latest host.unhealthy_services.add(("worker", "v2")) assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 assert host.running_images() == before + assert host.running()["web"] == ["prev123abc"] -def test_digest_pinned_container_is_restored_by_alias(monkeypatch, tmp_path): +def test_digest_pinned_container_is_restored_by_the_previous_commit(monkeypatch, tmp_path): chdir(monkeypatch, tmp_path) host = FakeHost(ROLLING, running={"worker": ["v1"]}).install(monkeypatch) host.add("web", "v1", ref="ghcr.io/myorg/myapp@sha256:abc") + host.registry["prev123abc"] = host.images["v1"] before = host.running_images() host.unhealthy_services.add(("worker", "v2")) assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 assert host.running_images() == before -def test_services_sharing_an_image_share_one_alias(host): - deploy(tag="v2", cmd=COMPOSE_CMD) - tags = [c for c in host.commands() if c.startswith("docker tag")] - assert len(tags) == 1 # web and worker both ran v1 +def test_a_moved_release_tag_restores_by_the_previous_commit(host, capsys): + """v1 now names a different image locally than the one running: trust + the commit SHA, not the tag.""" + host.registry["prev123abc"] = host.images["v1"] + before = host.running_images() + host.images["v1"] = "sha256:" + "e" * 64 # v1 re-pushed and pulled + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running_images() == before + assert "would restore it by the previous commit, prev123abc" in capsys.readouterr().out def test_mixed_images_warn_and_restore_the_most_common(monkeypatch, tmp_path, capsys): @@ -346,27 +355,57 @@ def test_snapshot_failure_with_failed_git_restore_exits_3(host): assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 -def test_alias_is_made_in_the_running_containers_repo_too(monkeypatch, tmp_path): - """A revert renders the previous commit's compose file: if the release - renamed the image repo, the alias must exist under the old name as well.""" +def test_another_project_sharing_the_directory_is_fine(host): + """A different project in the same directory (other services) isn't a rename.""" + host.other_projects = [] + host.foreign_services = [("obs", "grafana")] + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + + +def test_tag_and_digest_ref_checks_the_tag_not_the_digest(monkeypatch, tmp_path): + """repo:v1@sha256:... runs the digest's image even after repo:v1 moved; the + revert renders repo:v1, so v1 only counts if it still names that image.""" chdir(monkeypatch, tmp_path) host = FakeHost(stack(web=app()), running={}).install(monkeypatch) - host.add("web", "v1", ref="ghcr.io/oldorg/myapp:v1") + ctr = host.add("web", "v1", ref="ghcr.io/myorg/myapp:v1@sha256:abc") + host.registry["prev123abc"] = ctr.image_id + host.images["v1"] = "sha256:" + "e" * 64 # repo:v1 moved + host.unhealthy_services.add(("web", "v2")) deploy(tag="v2", cmd=COMPOSE_CMD) - tagged = sorted(c.split()[-1] for c in host.commands() if c.startswith("docker tag")) - alias = tagged[0].split(":")[-1] - assert tagged == [f"ghcr.io/myorg/myapp:{alias}", f"ghcr.io/oldorg/myapp:{alias}"] + assert "docker image inspect --format {{.Id}} ghcr.io/myorg/myapp:v1" in host.commands() + assert host.running_images() == {"web": [ctr.image_id]} + + +def test_redeploying_the_running_tag_restores_by_the_previous_commit(host): + """v1 was re-pushed and is deployed again: this deploy's pull moves local + v1 to the new build, so a revert can't go by v1. It uses the SHA.""" + old = host.images["v1"] + host.registry["prev123abc"] = old + host.registry["v1"] = "sha256:" + "d" * 64 # the re-pushed build + host.unhealthy_services.add(("worker", "v1")) + assert deploy(tag="v1", cmd=COMPOSE_CMD) == 1 + assert host.running_images() == {"web": [old], "worker": [old]} + assert host.running()["web"] == ["prev123abc"] -def test_container_shown_by_image_id_is_aliased_in_the_config_repo(monkeypatch, tmp_path): +def test_redeploying_the_running_commit_warns_that_a_rebuild_cant_be_undone(host, capsys): + """Deploying the SHA that's checked out: no other git name exists for the + running build, so a revert can only restore that commit as pulled now.""" + host.sha = "v1" # HEAD is the commit the containers run + deploy(tag="v1", cmd=COMPOSE_CMD) + assert "redeploying v1: if web's image under it was rebuilt" in capsys.readouterr().err + + +def test_container_shown_by_image_id_restores_by_the_previous_commit(monkeypatch, tmp_path): """docker ps shows a bare image ID once the container's tag has moved.""" chdir(monkeypatch, tmp_path) host = FakeHost(stack(web=app()), running={}).install(monkeypatch) ctr = host.add("web", "v1") ctr.ref = ctr.image_id.removeprefix("sha256:")[:12] - deploy(tag="v2", cmd=COMPOSE_CMD) - tagged = [c.split()[-1] for c in host.commands() if c.startswith("docker tag")] - assert len(tagged) == 1 and tagged[0].startswith("ghcr.io/myorg/myapp:flow-deploy-") + host.registry["prev123abc"] = ctr.image_id + host.unhealthy_services.add(("web", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert host.running_images() == {"web": [ctr.image_id]} def test_image_that_ignores_deploy_tag_warns(monkeypatch, tmp_path, capsys): diff --git a/tests/test_deployed.py b/tests/test_deployed.py index 878d00c..d27c2c1 100644 --- a/tests/test_deployed.py +++ b/tests/test_deployed.py @@ -84,20 +84,17 @@ def test_current_refuses_mixed_tags(host): assert "different or untagged images" in why and "v2 (web)" in why and "v1 (worker)" in why -def test_current_after_a_revert_names_the_one_image_by_its_alias(host): - """A revert recreates shipped services on the alias, while the failed one - keeps its old container and tag: the same image under two names.""" - host.add("web", "flow-deploy-abc") - worker = host.add("worker", "v2") - host.ctrs[0].image_id = worker.image_id - assert deployed.current() == ( - "flow-deploy-abc", - "running containers (one image under several tags)", - ) - - -def test_current_refuses_different_tags_without_an_alias(host): - """Same image, but no alias among the tags: no exact name to pick.""" +def test_current_after_a_revert_from_latest_names_the_sha(host): + """A revert from :latest recreates services on the previous commit's SHA, + while a kept container still says :latest: one image, the SHA names it.""" + web = host.add("web", "abc123sha") + worker = host.add("worker", "latest") + web.image_id = worker.image_id + assert deployed.current() == ("abc123sha", "running containers (one image)") + + +def test_current_refuses_two_real_tags_for_one_image(host): + """Two release tags on one image: no single answer, so no guess.""" web = host.add("web", "v2") worker = host.add("worker", "v2-again") worker.image_id = web.image_id @@ -106,8 +103,8 @@ def test_current_refuses_different_tags_without_an_alias(host): def test_current_raises_when_docker_inspect_fails(host): - host.add("web", "flow-deploy-abc") - host.add("worker", "v2") + host.add("web", "abc123sha") + host.add("worker", "latest") host.fail("docker inspect") with pytest.raises(RuntimeError, match="could not inspect the app containers"): deployed.current() diff --git a/tests/test_drain_first.py b/tests/test_drain_first.py index 5a9989a..e90843b 100644 --- a/tests/test_drain_first.py +++ b/tests/test_drain_first.py @@ -102,12 +102,12 @@ def test_phase_3_failure_reverts_everything(host, tmp_path): assert host.running_images() == before assert host.sha == "prev123abc" - assert record(tmp_path)["tag"].startswith("flow-deploy-") + assert record(tmp_path)["tag"] == "v1" # Undo order: web rolled back before the drain-first services come back. aliased = [ i for i, env in enumerate(host.envs) - if (env or {}).get("DEPLOY_TAG", "").startswith("flow-deploy-") + if (env or {}).get("DEPLOY_TAG") == "v1" and host.calls[i][2] == "up" ] rollback = next(i for i in aliased if "web=2" in host.calls[i]) restore = next(i for i in aliased if "scheduler=1" in host.calls[i]) @@ -170,12 +170,16 @@ def test_restore_cannot_inspect_exits_3(host): assert deploy(tag="v2", cmd=COMPOSE_CMD) == 3 -def test_no_restore_alias_means_nothing_is_drained(host, capsys): - host.fail("docker tag") +def test_restore_from_latest_uses_the_previous_commit(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["latest"], "worker": ["latest"]}) + host.install(monkeypatch) + host.registry["prev123abc"] = host.images["latest"] + before = host.running_images() + host.unhealthy_services.add(("web", "v2")) assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 - assert "for a revert; nothing was changed" in capsys.readouterr().err - assert not any(c.startswith("docker stop") for c in host.commands()) - assert host.running() == V1 + assert host.running_images() == before + assert host.running()["worker"] == ["prev123abc"] def test_new_containers_that_cannot_be_drained_on_revert_exit_3(host): diff --git a/tests/test_git.py b/tests/test_git.py index ee12459..b8abe92 100644 --- a/tests/test_git.py +++ b/tests/test_git.py @@ -6,6 +6,7 @@ current_sha, fetch, is_dirty, + is_ref, preflight_and_checkout, restore, ) @@ -123,3 +124,17 @@ def test_restore_success(mock_process, capsys): def test_restore_failure(mock_process): mock_process.responses.append(_err("checkout error")) assert restore("prev123") is False + + +def test_is_ref(mock_process): + mock_process.responses.append(_ok()) + mock_process.responses.append(process.Result(1, "", "")) + assert is_ref("v1.4.0") is True + assert mock_process.calls[0][1] == [ + "git", + "rev-parse", + "--verify", + "--quiet", + "v1.4.0^{commit}", + ] + assert is_ref("latest") is False diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py index 96f4d48..081b30f 100644 --- a/tests/test_rolling_parity.py +++ b/tests/test_rolling_parity.py @@ -31,13 +31,13 @@ def is_snapshot(args): - """The pre-deploy checks: what each app service runs, aliased by image ID, - and that no other compose project runs in this directory. Plus a revert's - look for stopped leftovers that compose would otherwise restart. + """The pre-deploy checks: what each app service runs and the git tag or + SHA that restores it, and that no other compose project runs these + services in this directory. Plus a revert's look for stopped leftovers + that compose would otherwise restart. New on this branch, issued before anything changes, so a failure can - restore the exact image each service ran whatever tag it was started - from (a version, a sha, a moved :latest, or none). + restore what each service ran rather than what HEAD or :latest says. """ line = " ".join(args) return ( @@ -45,7 +45,8 @@ def is_snapshot(args): or (args[:2] == ["docker", "ps"] and "project.working_dir=" in line) or (args[:2] == ["docker", "ps"] and "status=created" in line) or args[:4] == ["docker", "inspect", "--format", "{{.Id}} {{.Image}}"] - or args[:2] == ["docker", "tag"] + or args[:3] == ["docker", "image", "inspect"] + or args[:3] == ["git", "rev-parse", "--verify"] ) @@ -117,7 +118,7 @@ def test_rolling_deploy_matches_master(name, monkeypatch, tmp_path): rollback = calls[len(expected_calls) :] calls = calls[: len(expected_calls)] composes = [env for args, env in rollback if args[:2] == ["docker", "compose"]] - assert composes and all(env["DEPLOY_TAG"].startswith("flow-deploy-") for env in composes) + assert composes and all(env["DEPLOY_TAG"] == "v1" for env in composes) assert any(args[-1] == "web" and "--scale" in args for args, _ in rollback) assert by_appearance(calls) == by_appearance(expected_calls), f"{name}: commands differ" From 78f5e62882c239bddf422d052ad0d8611a271606 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 11:04:07 -0600 Subject: [PATCH 14/19] Report kills and drift, log every run, and verify restores Fixes from a host rehearsal, so an operator can see what a deploy did and what it left pending: - A container that had to be killed is reported. After a drain or a cutover stop, a container that exited 137 or used the whole timeout gets a warning that its PID 1 isn't handling SIGTERM. The deploy still succeeds. - Accessory drift is reported, never acted on. A deploy and status warn when an accessory's `compose config --hash` no longer matches its running containers' config-hash label, meaning the next manual `up -d` will recreate it. One-off containers are ignored. - Every run is recorded in .git/flow-deploy.log (header, output, exit code; last 20 runs). It's written only while the lock is held, so a locked-out deploy can't touch it. status shows how the last run ended, including one that never recorded an exit. - .git/deploy-tag records the deployed commit. - A revert waits for what it restored. Each restored service must reach its previous replica count and pass its health check, or the deploy exits 3. - `flow-deploy config` doesn't need the app's env. If compose config fails (CI has no .env), it retries with --no-interpolate and warns on stderr, naming the unset variables. It keeps stdout pure JSON for deploy-action and always sets DEPLOY_TAG, so a wrapper that defaults it never asks. Two failure paths found in review are fixed: - A signal in the middle of a rolling service (its health wait, the cutover) now reverts that service too, instead of leaving old and new side by side. - lock.acquire() no longer has a check-then-write race between deploys started together. Acquirers take an flock on .git/deploy-lock.guard, which the kernel releases if the holder dies. Docs: - the fail-closed script/prod snippet - keep accessories off the app's .env (list their variables under environment:), and scope manual changes with `flow-deploy compose up -d --no-deps ` - troubleshooting for each new warning Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 68 ++++++- SPEC.md | 41 ++-- docs/github-actions.md | 12 ++ src/flow_deploy/cli.py | 32 ++- src/flow_deploy/compose.py | 36 +++- src/flow_deploy/containers.py | 30 +++ src/flow_deploy/deploy.py | 124 ++++++++++-- src/flow_deploy/lock.py | 10 + src/flow_deploy/log.py | 85 +++++++- tests/fake_host.py | 18 ++ tests/integration/test_deploys.py | 113 +++++++++++ tests/test_cli.py | 4 +- tests/test_compose.py | 20 ++ tests/test_containers.py | 28 +++ tests/test_deploy_failures.py | 22 ++- tests/test_lock.py | 32 +++ tests/test_operability.py | 314 ++++++++++++++++++++++++++++++ tests/test_rolling_parity.py | 11 +- 18 files changed, 952 insertions(+), 48 deletions(-) create mode 100644 tests/test_operability.py diff --git a/README.md b/README.md index 1ee24d9..b0c460a 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,11 @@ phases: pulls its new image, then stops its running containers. Stopping is `docker stop --time `: SIGTERM first, so Celery-style workers finish their current tasks and stop taking new ones, then SIGKILL when the - drain expires. Nothing rolls until every drain has finished. + drain expires. Nothing rolls until every drain has finished. A container + that had to be killed (exit 137, or the whole drain used up) gets a + warning: its PID 1 probably isn't handling SIGTERM, typically a shell-form + `CMD` or an entrypoint script that doesn't `exec` the server. The same + warning covers a rolling service's old container. 2. **Roll.** Rolling services deploy in `deploy.order`, as usual. 3. **Start.** Drain-first services start in `deploy.order` on the new tag, and each must pass its health check. @@ -172,14 +176,16 @@ sshd sends the remote process no signal when the client disconnects. `tests/integration/test_ci_cancel.py` checks this against a real sshd. The deploy runs to completion, or reverts on its own failure, exactly as if the job were still watching. Its output to the closed session is discarded rather than -crashing it. Check the host afterwards (`flow-deploy status`) to see how it -ended. +crashing it. Every run is also written to `.git/flow-deploy.log` on the host +(inside `.git`, so the tree stays clean; the last 20 runs are kept), and +`flow-deploy status` shows how the last one ended. The deploy exits `1` when it failed and everything was put back. It exits `3` only when something couldn't be put back: - the git restore failed -- a rollback or restore failed +- a rollback or restore failed, including a restored service that doesn't + pass its health check (a revert waits for what it put back) - a *failed* service's own cleanup failed, such as an aborted new container that won't stop or be removed @@ -264,19 +270,56 @@ while recreated ones run the previous SHA; when they all run one image, the SHA is the answer. If the project has a compose wrapper (`script/prod`), make the wrapper default -`DEPLOY_TAG` the same way, so `script/prod up -d` is safe too: +`DEPLOY_TAG` the same way, so `script/prod up -d` is safe too. It must fail +closed: when `flow-deploy tag` can't tell, stop rather than fall through to +`:latest`. ```sh -if [ -z "${DEPLOY_TAG:-}" ] && command -v flow-deploy >/dev/null; then - DEPLOY_TAG=$(flow-deploy tag 2>/dev/null) && export DEPLOY_TAG +if [ -z "${DEPLOY_TAG:-}" ]; then + DEPLOY_TAG=$(flow-deploy tag) || { + echo "script/prod: set DEPLOY_TAG (flow-deploy tag couldn't tell)" >&2 + exit 1 + } + export DEPLOY_TAG fi ``` -flow-deploy calls the wrapper itself; while it looks up the tag it sets -`DEPLOY_TAG` to a placeholder, so the wrapper never recurses. A `--service` +flow-deploy sets `DEPLOY_TAG` itself on every compose call it makes (to a +placeholder while it looks up the tag, and in `flow-deploy config` in CI), so +the wrapper never asks it and never recurses. On a fresh host with nothing +running, pass the tag: `DEPLOY_TAG=v1.4.0 script/prod up -d`. A `--service` deploy that leaves some app services out leaves them on different tags, so it clears the record and warns. +### Accessories and `.env` + +flow-deploy never touches accessories (`deploy.role=accessory`): no pulls, no +restarts. A change to one lands on the next manual `up -d`, which recreates +it. So a deploy and `flow-deploy status` warn when an accessory's compose +config no longer matches the running container's (its config hash): plan that +recreate (data, downtime) instead of discovering it. + +The common cause is `.env`: compose recreates every service that reads an +`env_file` when the file changes, postgres and redis included. Keep +accessories off the app's `.env`: drop `env_file` and list the few variables +they need under `environment:`, interpolated from `.env` so the values still +live in one place: + +```yaml +services: + postgres: + image: postgres:16 + environment: + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + labels: + deploy.role: accessory +``` + +Then an app-env edit changes only the services that use those variables. For a +manual change, scope it to the service you mean: `flow-deploy compose up -d +--no-deps `. + ## Host Discovery For CI/CD orchestration across multiple hosts, declare topology in your compose file: @@ -300,6 +343,13 @@ services: Resolution order: GitHub Actions variable > per-service label > `x-deploy` default. +`flow-deploy config` (what `deploy-action` runs in CI) doesn't need the app's +environment. If compose rejects the project with CI's empty `.env` (an +`image: ${DOCKER_IMAGE}` with the variable unset, say), it retries without +interpolation and warns, naming the unset variables. `${VARS}` in `x-deploy` +or `deploy.*` labels then stay literal, so set those in CI or use the +`HOST_NAME`/`HOST_USER`/`SSH_PORT` overrides. + See [GitHub Actions Setup](docs/github-actions.md) for CI/CD integration. ## CLI Commands diff --git a/SPEC.md b/SPEC.md index 4e80cea..7de1282 100644 --- a/SPEC.md +++ b/SPEC.md @@ -90,7 +90,9 @@ R3. Restore drain-first for each drained service, in deploy order: remove its stopped leftovers on other images, stop + remove containers not on its previous image, DEPLOY_TAG= up -d --no-deps - --no-recreate --scale = + --no-recreate --scale =, + then wait for its health check (unless skipped); + unhealthy → not reverted (exit 3) (left stopped if it wasn't running before) R4. Record .git/deploy-tag = the restore tag (cleared if services differ) R5. Release the lock always @@ -110,6 +112,8 @@ When stopping the old container, the tool sends SIGTERM and waits for in-flight This maps directly to `docker stop --time `. Traefik removes the container from its pool when it stops, so the drain period gives in-flight requests time to complete. Applications should handle SIGTERM gracefully (stop accepting new connections, finish existing ones). +After each drain and cutover stop, the tool checks the stopped container: if it exited 137 (SIGKILL) or the stop used the whole timeout, it warns that the container didn't exit on SIGTERM. The usual cause is PID 1 being a shell that doesn't forward signals (a shell-form `CMD`, or an entrypoint that doesn't `exec`). It's a warning, never a failure; the tool doesn't inspect PID 1 itself. + ### 2.4 Health Checks The tool relies entirely on Docker's native health check mechanism as declared in `docker-compose.yml`. The tool does not define, override, or interpret health checks — it simply polls `docker inspect` for the container's health status. @@ -289,7 +293,7 @@ The tool expects a project directory containing a checked-out Git repository wit └── (application source) ``` -The tool writes no state files to the working tree. The deploy lock is stored at `.git/deploy-lock` and the deployed tag at `.git/deploy-tag` (both invisible to `git status`). The current deployed commit is always `git rev-parse HEAD`. +The tool writes no state files to the working tree. The deploy lock is stored at `.git/deploy-lock`, the deployed tag and commit at `.git/deploy-tag`, and a log of the last 20 deploys at `.git/flow-deploy.log` (all invisible to `git status`). The current deployed commit is always `git rev-parse HEAD`. ### 3.1 Compose Command Wrapper @@ -314,13 +318,17 @@ A wrapper that keeps manual commands on the deployed tag (§2.8): ```bash #!/usr/bin/env bash -if [ -z "${DEPLOY_TAG:-}" ] && command -v flow-deploy >/dev/null; then - DEPLOY_TAG=$(flow-deploy tag 2>/dev/null) && export DEPLOY_TAG +if [ -z "${DEPLOY_TAG:-}" ]; then + DEPLOY_TAG=$(flow-deploy tag) || { + echo "script/prod: set DEPLOY_TAG (flow-deploy tag couldn't tell)" >&2 + exit 1 + } + export DEPLOY_TAG fi docker compose -f docker-compose.yml -f docker-compose.prod.yml "$@" ``` -`flow-deploy` always sets `DEPLOY_TAG` when it calls the wrapper (to a placeholder while looking up the tag), so the default never recurses. +It fails closed: when `flow-deploy tag` can't tell, the wrapper stops rather than run compose on `:latest`. `flow-deploy` always sets `DEPLOY_TAG` when it calls the wrapper (to a placeholder while looking up the tag, and in `flow-deploy config`), so the default never asks it and never recurses. On a host with nothing running, pass `DEPLOY_TAG` explicitly. This pattern means the tool is completely agnostic about which compose files exist or how they're layered. The project defines its own composition strategy, and the tool just calls the wrapper with the appropriate subcommand arguments (`pull`, `up`, `stop`, etc.). @@ -334,6 +342,8 @@ Secrets are managed via `.env` files, which Docker Compose reads natively. The t The `.env` file should be excluded from version control and provisioned separately (via Ansible, manual setup, or a secrets manager). The tool only requires that the file exists if the compose file references it. +**Accessories and `.env`.** Compose recreates every service that reads an `env_file` when the file changes. The tool never touches accessories, so that recreate happens on the next manual `up -d`. Keep accessories off the app's `.env`: drop `env_file` and list the variables they need under `environment:` (interpolated from `.env`). Scope manual changes: `flow-deploy compose up -d --no-deps `. Each deploy, and `flow-deploy status`, warns when an accessory's compose config hash (` config --hash=`) no longer matches its running container's `com.docker.compose.config-hash` label: a recreate is pending. Warn only. + --- ## 4. CLI Interface @@ -358,7 +368,9 @@ Exit codes: - `0` — all services deployed successfully - `1` — deploy failed (dirty tree, git error, unhealthy service, etc.) and everything it touched was put back - `2` — deploy lock held by another process -- `3` — deploy failed and could not be fully reverted (the git restore, a rollback or restore, or a failed service's own cleanup failed); the lock is still released +- `3` — deploy failed and could not be fully reverted (the git restore, a rollback or restore, a restored service's health check, or a failed service's own cleanup failed); the lock is still released + +Every run is recorded in `.git/flow-deploy.log` with a header (time, PID, arguments) and its exit code, keeping the last 20 runs, so a deploy nobody is watching (a cancelled CI job, §7.1) still leaves a record. To deploy a previous version, run `flow-deploy deploy --tag ` (or its SHA). Find it in your CI history, `git tag` on the server, or `flow-deploy status` before deploying. @@ -370,7 +382,7 @@ Show the current state of all managed services. flow-deploy status ``` -Output includes: current HEAD SHA, the deployed tag and where it came from (§2.8), and per container: service name, role, container ID, image, health status. +Output includes: current HEAD SHA, the deployed tag and where it came from (§2.8), the last deploy from `.git/flow-deploy.log` and how it ended (or that it never recorded an exit: still running, or killed), accessories whose config changed since they started (§3.2), and per container: service name, role, container ID, image, health status. ### 4.3 `flow-deploy exec` @@ -402,6 +414,8 @@ flow-deploy config [--command COMMAND] Reads `COMPOSE_COMMAND` env var (same as all other commands), runs ` config`, parses host discovery, and emits a JSON array of host groups to stdout. Errors go to stderr with exit code 1. +It sets `DEPLOY_TAG` to a placeholder, so a wrapper that defaults it (§3.1) doesn't ask. Discovery doesn't need the app's environment: if compose rejects the project (CI has no `.env`, so an `image: ${DOCKER_IMAGE}` is empty), it retries with `config --no-interpolate` and warns on stderr, naming the unset variables. `${VARS}` in `x-deploy` and `deploy.*` labels then stay literal. Stdout stays pure JSON even on GitHub Actions; the `::warning::` goes to stderr. + ### 4.6 `flow-deploy upgrade` Update the tool to the latest release. @@ -448,7 +462,7 @@ Only one deploy may run at a time per project directory. The tool uses a lock fi ## 6. Logging and Output -All output goes to stdout. The format is human-readable and designed for both terminal use and GitHub Actions log rendering. +Progress goes to stdout; warnings and errors go to stderr. The format is human-readable and designed for both terminal use and GitHub Actions log rendering. Commands whose stdout is data (`flow-deploy config`, `flow-deploy tag`) keep it to that data alone, GitHub annotations included. Every deploy's output is also recorded in `.git/flow-deploy.log` (§4.1). ``` [12:34:56] ── deploy ────────────────────────────── @@ -516,11 +530,10 @@ Since the tool runs over SSH, output naturally appears in Actions logs. For rich For multi-host deploys or when you want host discovery from compose labels, use the GitHub Action. The action: 1. Checks out the repo (already done by the workflow) -2. Runs ` config` to get the fully merged compose YAML -3. Parses `x-deploy` and `deploy.*` labels to discover hosts -4. Groups services by host -5. SSHes to each host: `flow-deploy deploy --tag ` -6. Streams logs back to GitHub Actions +2. Runs `flow-deploy config` (§4.5): it renders ` config`, parses `x-deploy` and `deploy.*` labels, and prints the host groups as JSON on stdout. The action reads only that JSON, never compose's output. +3. Groups services by host (in that JSON) +4. SSHes to each host: `flow-deploy deploy --tag ` +5. Streams logs back to GitHub Actions **Cancelling the workflow does not cancel the remote deploy.** The action runs ssh without a pty, so sshd sends the remote `flow-deploy` no signal when the connection drops; `tests/integration/test_ci_cancel.py` verifies this against a real sshd. The deploy runs to completion, or reverts on its own failure, and its output to the closed session is discarded. Running ssh with `-tt` would deliver SIGHUP and make a cancel revert, but every dropped connection would then revert a deploy too. @@ -737,7 +750,7 @@ All v1 design decisions are made with the v2 roadmap in mind. Specifically: - The single-command `flow-deploy deploy` is a convenience that runs prepare + health check + cutover in one shot. v2 splits this into discrete phases without breaking the v1 interface. - The `deploy.role` label convention is extensible — v2 adds behavior, not new classification schemes. - The compose command wrapper (§3.1) means the tool never makes assumptions about compose file structure, which keeps it compatible with arbitrarily complex service topologies. -- The tool writes no state to the working tree. The deploy lock lives in `.git/deploy-lock`, the deployed tag in `.git/deploy-tag`, and the current deployed commit is always `git rev-parse HEAD`. v2 adds `.git/deploy-prepare` for two-phase state tracking. +- The tool writes no state to the working tree. The deploy lock lives in `.git/deploy-lock`, the deployed tag and commit in `.git/deploy-tag`, the last 20 deploys' output in `.git/flow-deploy.log`, and the current deployed commit is always `git rev-parse HEAD`. v2 adds `.git/deploy-prepare` for two-phase state tracking. - Host discovery via `x-deploy` and `deploy.host` labels (§2.6) gives the GitHub Action enough information to orchestrate multi-host deploys in v1 (sequential) and v2 (two-phase coordinated). --- diff --git a/docs/github-actions.md b/docs/github-actions.md index 788cf90..3b066bf 100644 --- a/docs/github-actions.md +++ b/docs/github-actions.md @@ -293,5 +293,17 @@ CI didn't push the image under that tag. Push the version tag as well as the SHA **`can't tell which tag is deployed`** from `flow-deploy tag` or `flow-deploy compose`: Services run different or untagged images (one image under `:latest` plus one other tag is fine), or nothing is running and no deploy is recorded. Set it explicitly: `DEPLOY_TAG=v1.4.0 flow-deploy compose up -d`. +**`WARNING: compose config failed with this environment ... (unset: DOCKER_IMAGE)`** from host discovery: +CI has no `.env`, so variables only set there are empty. Discovery retries without interpolation and carries on; the warning names the variables. It only matters if `x-deploy` or a `deploy.*` label uses them: set those in CI, or use the `HOST_NAME`/`HOST_USER`/`SSH_PORT` overrides. + +**`didn't exit on SIGTERM ... and was killed`:** +The container's PID 1 isn't handling SIGTERM, so every deploy waits out the drain and kills it mid-request. Use an exec-form `CMD` (`["gunicorn", ...]`), or `exec` the server at the end of the entrypoint script. + +**`accessory postgres's config changed since it started`:** +The next manual `up -d` will recreate it. Usually an `.env` edit: keep accessories off `env_file` and list their variables under `environment:` (see the README's "Accessories and `.env`"). + +**How did a deploy end, when CI was cancelled?** +On the host: `flow-deploy status` (last run and exit code), or `.git/flow-deploy.log`. + **Health check timeout:** Increase the timeout via label: `deploy.healthcheck.timeout: 300`. Check that your app's health endpoint responds within the Docker healthcheck interval. diff --git a/src/flow_deploy/cli.py b/src/flow_deploy/cli.py index 632ad8f..26064a5 100644 --- a/src/flow_deploy/cli.py +++ b/src/flow_deploy/cli.py @@ -1,6 +1,7 @@ """Click entry point — all commands.""" import json +import re import sys import click @@ -44,6 +45,14 @@ def status(): log.info(f"Current SHA: {current_sha[:7] if current_sha else '(none)'}") log.info(f"Deployed tag: {tag} (from {how})" if tag else f"Deployed tag: unknown ({how})") + last = log.last_run() + if last: + header, code = last + ended = f"exit {code}" if code is not None else "no exit recorded (running, or killed)" + log.info(f"Last deploy: {header}: {ended} (log: {log.RUN_LOG})") + project = compose_dict.get("name", "") + for name in deploy_mod.accessory_drift(compose_dict, None, project, {"DEPLOY_TAG": tag or ""}): + log.info(f"Accessory {name}: config changed since it started; next `up -d` recreates it") log.info("") for svc in all_services: @@ -143,11 +152,28 @@ def logs(service, follow, tail): def config(command): """Show resolved deploy configuration as JSON.""" cmd = command.split() if command else None + # DEPLOY_TAG is set so a wrapper that defaults it from `flow-deploy tag` + # never has to ask (there's nothing deployed in CI to ask about). + env = {"DEPLOY_TAG": deployed.LOOKUP_PLACEHOLDER} try: - compose_dict = compose.compose_config(cmd=cmd) + compose_dict = compose.compose_config(cmd=cmd, env=env) except RuntimeError as e: - log.error(str(e)) - sys.exit(1) + # Discovery only needs x-deploy and labels, not the app's env (CI + # has no .env): retry without interpolation rather than fail. + try: + compose_dict = compose.compose_config(cmd=cmd, env=env, no_interpolate=True) + except RuntimeError: + log.error(str(e)) + sys.exit(1) + # compose logs these as: msg="The \"VAR\" variable is not set. ..." + unset = sorted(set(re.findall(r'The \\?"(\w+)\\?" variable is not set', str(e)))) + missing = f" (unset: {', '.join(unset)})" if unset else "" + log.warning( + f"compose config failed with this environment{missing}; discovered hosts " + "from the uninterpolated config. ${VARS} in x-deploy or deploy.* labels " + "stay literal: set them, or use the HOST_NAME/HOST_USER/SSH_PORT overrides.", + stdout_clean=True, + ) try: overrides = discovery.env_overrides() diff --git a/src/flow_deploy/compose.py b/src/flow_deploy/compose.py index 5878972..534f23b 100644 --- a/src/flow_deploy/compose.py +++ b/src/flow_deploy/compose.py @@ -32,17 +32,43 @@ def compose_run( return process.run(command + args, env=env) -def compose_config(cmd: list[str] | None = None, env: dict[str, str] | None = None) -> dict: +def compose_config( + cmd: list[str] | None = None, + env: dict[str, str] | None = None, + no_interpolate: bool = False, +) -> dict: """Run config and parse YAML output. ``env`` (e.g. DEPLOY_TAG) applies while compose interpolates, so the - rendered images show what a deploy with it would run. + rendered images show what a deploy with it would run. ``no_interpolate`` + leaves ${VARS} as written, so a project whose env isn't present (CI + discovery) still parses. """ - command = cmd or resolve_command() + command = (cmd or resolve_command()) + ["config"] + if no_interpolate: + command.append("--no-interpolate") if env: - result = process.run(command + ["config"], env=env) + result = process.run(command, env=env) else: - result = process.run(command + ["config"]) + result = process.run(command) if result.returncode != 0: raise RuntimeError(f"compose config failed: {result.stderr}") return yaml.safe_load(result.stdout) + + +def config_hashes( + services: list[str], cmd: list[str] | None = None, env: dict[str, str] | None = None +) -> dict[str, str] | None: + """The config hash compose would label each service's containers with. + + What `up` compares to decide whether to recreate. None if compose can't + say (an older compose without --hash, or an error). + """ + if not services: + return {} + command = (cmd or resolve_command()) + ["config", f"--hash={','.join(services)}"] + result = process.run(command, env=env) if env else process.run(command) + if result.returncode != 0: + return None + pairs = (line.split() for line in result.stdout.splitlines()) + return {p[0]: p[1] for p in pairs if len(p) == 2} diff --git a/src/flow_deploy/containers.py b/src/flow_deploy/containers.py index 0289467..74598a6 100644 --- a/src/flow_deploy/containers.py +++ b/src/flow_deploy/containers.py @@ -133,6 +133,36 @@ def stop_container(container_id: str, timeout: int = 30, isolate: bool = False) return result.returncode == 0 +def exit_code(container_id: str) -> int | None: + """A stopped container's exit code, or None if docker can't say.""" + result = process.run(["docker", "inspect", "--format", "{{.State.ExitCode}}", container_id]) + try: + return int(result.stdout.strip()) if result.returncode == 0 else None + except ValueError: + return None + + +def running_config_hashes(service: str, project: str = "") -> set[str] | None: + """The compose config hashes of a service's running containers. None if docker ps fails. + + One-off containers (`compose run`) are left out: they aren't what `up` recreates. + """ + filters = [ + "--filter", + f"label=com.docker.compose.service={service}", + "--filter", + "label=com.docker.compose.oneoff=False", + ] + if project: + filters += ["--filter", f"label=com.docker.compose.project={project}"] + result = process.run( + ["docker", "ps", *filters, "--format", '{{.Label "com.docker.compose.config-hash"}}'] + ) + if result.returncode != 0: + return None + return {line.strip() for line in result.stdout.splitlines() if line.strip()} + + def remove_container(container_id: str) -> bool: """Remove a container. Returns True on success.""" result = process.run(["docker", "rm", container_id]) diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 26ec1d0..fbe94f7 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -82,7 +82,7 @@ class _Run: previous_sha: str | None = None previous: dict[str, Previous] = field(default_factory=dict) drained: list[str] = field(default_factory=list) # drain-first services touched - shipped: list[str] = field(default_factory=list) # rolling services deployed + shipped: list[str] = field(default_factory=list) # rolling services deployed or deploying aborted: str | None = None # the rolling service whose own abort kept its old container whole_project: bool = True # every app service is in this deploy @@ -155,6 +155,17 @@ def deploy( _dry_run(tag, app_services) return EXIT_OK + return _deploy_guarded(compose_cmd, tag, tag_provided, services_filter) + + +def _deploy_guarded( + compose_cmd: list[str], tag: str, tag_provided: bool, services_filter: list[str] | None +) -> int: + """The deploy under its lock and signal handlers; always reverts on failure. + + The run is logged to .git/flow-deploy.log while the lock is held, so a + deploy that's locked out never touches the log of the one running. + """ # A signal (Ctrl-C, a timeout, a hung-up terminal) reverts like any other # failure. Handlers go in before the lock is taken, so no # signal can land between the two and skip cleanup. @@ -168,6 +179,7 @@ def _interrupt(signum, frame): run = _Run(compose_cmd) locked = False + code = EXIT_FAILED try: # Acquire lock before any mutations (git checkout, container changes) locked = lock.acquire() @@ -176,14 +188,19 @@ def _interrupt(signum, frame): pid = lock_info["pid"] if lock_info else "unknown" log.error(f"Deploy lock held by PID {pid}") return EXIT_LOCKED - return _deploy_locked(run, tag, tag_provided, services_filter) + log.open_run( + f"deploy --tag {tag}" + "".join(f" --service {s}" for s in services_filter or []) + ) + code = _deploy_locked(run, tag, tag_provided, services_filter) + return code except (Exception, Interrupted) as exc: if isinstance(exc, Interrupted): reason = f"interrupted by signal {exc.signum}" else: reason = f"unexpected error: {exc!r}" log.error(f"{reason}; reverting") - return run.revert(reason) + code = run.revert(reason) + return code finally: # Ignore signals first, so one landing here can't skip the rest. for signum in HANDLED_SIGNALS: @@ -191,6 +208,7 @@ def _interrupt(signum, frame): # Always released: a failed deploy puts things back rather than # leaving state for someone to clean up by hand. if locked: + log.close_run(code) lock.release() for signum, handler in originals.items(): signal.signal(signum, handler) @@ -233,6 +251,7 @@ def _deploy_locked( project = run.project compose_cmd = run.compose_cmd start_time = time.time() + _warn_accessory_drift(compose_dict, compose_cmd, project, {"DEPLOY_TAG": tag}) # A release that renames the compose project would start a second stack # beside the running one, and snapshot (so revert) nothing. @@ -274,13 +293,17 @@ def failed(reason: str) -> int: # Phase 2: rolling services, in deploy order, as before. for svc in rolling: + # Recorded before it's touched: a signal mid-service (during the + # 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 result == SVC_DIRTY: dirty.append(svc.name) if result != SVC_OK and run.previous[svc.name].replicas: + run.shipped.pop() run.aborted = svc.name return failed("deploy aborted") # its abort left the old container serving - run.shipped.append(svc.name) if result != SVC_OK: # Nothing ran before, so whatever the failed rollout left goes too. return failed("deploy aborted") @@ -302,7 +325,7 @@ def failed(reason: str) -> int: return failed(f"{', '.join(failures)} failed to start") if run.whole_project: - deployed.write(tag) + deployed.write(tag, git.current_sha()) else: # Services now run different tags; no one tag describes the host. deployed.clear() @@ -401,6 +424,57 @@ def _restore_tag(prev: Previous, previous_sha: str | None, deploy_tag: str) -> s return previous_sha +def _stop_reporting(name: str, ctr_id: str, timeout: int, isolate: bool = False) -> bool: + """docker stop, then warn if the container had to be killed. + + A container that ignores SIGTERM waits out the whole timeout and is + SIGKILLed (exit 137), dropping whatever it was doing. Usually PID 1 is + a shell that doesn't forward signals. Reported, never fatal. + """ + started = time.time() + if not containers.stop_container(ctr_id, timeout=timeout, isolate=isolate): + return False + took = time.time() - started + code = containers.exit_code(ctr_id) + if code == 137 or (timeout > 0 and took >= timeout): + log.warning( + f"{name} ({ctr_id[:7]}) didn't exit on SIGTERM within {timeout}s and was " + "killed; make sure its PID 1 handles SIGTERM (an exec-form CMD, or exec " + "in its entrypoint script)" + ) + return True + + +def _warn_accessory_drift( + compose_dict: dict, compose_cmd: list[str], project: str, env: dict[str, str] +) -> None: + """Warn about accessories whose config changed since they were started. + + flow-deploy never touches accessories, so the change lands on the next + manual `up -d`, which recreates them: plan it (data, downtime). Only a + warning; any trouble working it out is ignored. + """ + for name in accessory_drift(compose_dict, compose_cmd, project, env): + log.warning( + f"accessory {name}'s config changed since it started; the next `up -d` " + "will recreate it. flow-deploy leaves it alone: plan that change." + ) + + +def accessory_drift( + compose_dict: dict, compose_cmd: list[str] | None, project: str, env: dict[str, str] +) -> list[str]: + """Running accessories whose compose config hash no longer matches.""" + names = [s.name for s in config.parse_services(compose_dict) if s.role == "accessory"] + wanted = compose.config_hashes(names, cmd=compose_cmd, env=env) or {} + drifted = [] + for name in names: + running = containers.running_config_hashes(name, project=project) + if running and name in wanted and running != {wanted[name]}: + drifted.append(name) + return drifted + + def _degraded(problem: str) -> int: log.error( f"Deploy failed and could not be fully reverted ({problem}). " @@ -509,7 +583,7 @@ def _drain_service( # The docker stop runs in its own session, so a terminal Ctrl-C (sent # to the whole foreground group) can't cut it short either. with _signals_deferred(f"finishing the drain of {ctr_id[:7]} first"): - stopped = containers.stop_container(ctr_id, timeout=svc.drain, isolate=True) + stopped = _stop_reporting(svc.name, ctr_id, svc.drain, isolate=True) removed = stopped and containers.remove_container(ctr_id) if not stopped: log.failure(f"could not stop {ctr_id[:7]}; it may still be running") @@ -641,7 +715,9 @@ def _roll_back(prev: Previous, compose_cmd: list[str], project: str) -> bool: # The cutover's cleanup failed, so the previous image still runs beside # the new one. A rolling deploy can't tell them apart by tag here. log.step(f"{svc.name} still runs its previous image; removing the new container(s)") - return _remove_all(newer, timeout=svc.drain) and _scale_to_previous(prev, compose_cmd) + return _remove_all(newer, timeout=svc.drain) and _scale_to_previous( + prev, compose_cmd, project + ) log.step(f"rolling {svc.name} back to {prev.restore_tag}...") return ( _deploy_service(svc, prev.restore_tag, compose_cmd, project=project, pull=False) == SVC_OK @@ -679,11 +755,11 @@ def _restore_drained(previous: list[Previous], compose_cmd: list[str], project: log.step(f"{svc.name} was not running before the deploy; leaving it stopped") continue log.step(f"restoring {svc.name} on {prev.restore_tag} ({prev.replicas} replica(s))...") - ok = _scale_to_previous(prev, compose_cmd) and ok + ok = _scale_to_previous(prev, compose_cmd, project) and ok return ok -def _scale_to_previous(prev: Previous, compose_cmd: list[str]) -> bool: +def _scale_to_previous(prev: Previous, compose_cmd: list[str], project: str) -> bool: """Bring ``prev.svc`` to its previous replica count on its previous image. --no-recreate: containers already on that image are kept, never replaced. @@ -697,7 +773,33 @@ def _scale_to_previous(prev: Previous, compose_cmd: list[str]) -> bool: ) if result.returncode != 0: log.failure(f"could not restore {svc.name}: {result.stderr.strip()}") - return result.returncode == 0 + return False + return _restored_healthy(svc, project, prev.replicas) + + +def _restored_healthy(svc: config.ServiceConfig, project: str, replicas: int) -> bool: + """Check a restored service is back at ``replicas`` and passing its health check. + + A revert isn't done until what it put back is serving: exit 3 if not, + including when a restored container exited straight away. + """ + ctrs = containers.list_containers_for_service( + svc.name, project=project, statuses=("running", "restarting") + ) + if ctrs is None: + log.failure(f"restored {svc.name} but can't list its containers to check health") + return False + if len(ctrs) < replicas: + log.failure(f"restored {svc.name} but only {len(ctrs)} of {replicas} containers are up") + return False + if svc.healthcheck_skip: + return True + log.step(f"waiting for restored {svc.name} to be healthy...") + for ctr in ctrs: + if not _wait_for_healthy(ctr["ID"], svc.healthcheck_timeout, svc.healthcheck_poll): + log.failure(f"restored {svc.name} but it isn't healthy ({ctr['ID'][:7]})") + return False + return True def _deploy_service( @@ -773,7 +875,7 @@ def end(code: int) -> int: # 5a. Cutover: stop old, remove old, scale back log.step(f"draining old container ({old_id[:7]}, {svc.drain}s timeout)...") - clean = containers.stop_container(old_id, timeout=svc.drain) + clean = _stop_reporting(svc.name, old_id, svc.drain) clean = containers.remove_container(old_id) and clean # Scale back only once the old container is gone: with two left, it # can only remove one, and compose might pick the new one. diff --git a/src/flow_deploy/lock.py b/src/flow_deploy/lock.py index e57adf5..c221240 100644 --- a/src/flow_deploy/lock.py +++ b/src/flow_deploy/lock.py @@ -3,6 +3,7 @@ Lock file lives in .git/ to avoid dirtying the working tree. """ +import fcntl import json import os import time @@ -27,9 +28,18 @@ def acquire() -> bool: """Acquire the deploy lock. Returns True if acquired, False if held by another process. Automatically breaks stale locks (holding PID no longer running). + + Acquirers take an flock on a guard file while they check and write the + lock, so two deploys starting together can't both see it free. The + kernel drops an flock when its holder exits, so the guard can't go stale. """ path = _lock_path() + with open(path + ".guard", "a") as guard: + fcntl.flock(guard, fcntl.LOCK_EX) + return _acquire(path) + +def _acquire(path: str) -> bool: if os.path.exists(path): try: with open(path) as f: diff --git a/src/flow_deploy/log.py b/src/flow_deploy/log.py index 285d64e..059f73f 100644 --- a/src/flow_deploy/log.py +++ b/src/flow_deploy/log.py @@ -13,16 +13,95 @@ def _is_github_actions() -> bool: return os.environ.get("GITHUB_ACTIONS") == "true" +RUN_LOG = ".git/flow-deploy.log" +RUN_MARK = "===== flow-deploy run " +_run_log = None # the open run log while a deploy runs + + def _write(text: str, stream=None) -> None: """Print, but never raise. When a remote deploy's ssh session drops, its stdout and stderr go with it. Logging must not then crash the revert that's putting things back. + Every line also goes to the run log, if one is open, so a deploy whose + CI job was cancelled (and so has no one watching) still leaves a record. """ try: print(text, file=stream or sys.stdout, flush=True) except (OSError, ValueError): pass + if _run_log is not None and not text.startswith("::"): + try: + _run_log.write(text + "\n") + _run_log.flush() + except (OSError, ValueError): + pass + + +def open_run(title: str, path: str = RUN_LOG, keep: int = 20) -> None: + """Start a run in the host-side log, keeping the last ``keep`` runs. + + Lives in .git, so it never dirties the tree. Never raises: a deploy + goes ahead without its log rather than fail over it. + """ + global _run_log + close_run(None) + try: + if not os.path.isdir(os.path.dirname(path) or "."): + return + runs = _runs(path)[-(keep - 1) :] if keep > 1 else [] + stamp = datetime.now().isoformat(timespec="seconds") + with open(path, "w") as f: + f.writelines(runs) + f.write(f"{RUN_MARK}{stamp} pid {os.getpid()}: {title} =====\n") + _run_log = open(path, "a") + except OSError: + _run_log = None + + +def close_run(code: int | None) -> None: + """End the current run in the log with its exit code.""" + global _run_log + if _run_log is None: + return + try: + if code is not None: + _run_log.write(f"===== exit {code} =====\n") + _run_log.close() + except (OSError, ValueError): + pass + _run_log = None + + +def _runs(path: str) -> list[str]: + """The log's runs, oldest first, each as one string.""" + try: + with open(path) as f: + text = f.read() + except OSError: + return [] + runs: list[str] = [] + for line in text.splitlines(keepends=True): + if line.startswith(RUN_MARK) or not runs: + runs.append("") + runs[-1] += line + return runs + + +def last_run(path: str = RUN_LOG) -> tuple[str, int | None] | None: + """(header, exit code or None if it never finished) of the last run, or None.""" + runs = _runs(path) + if not runs or not runs[-1].startswith(RUN_MARK): + return None + lines = runs[-1].splitlines() + header = lines[0][len(RUN_MARK) :].removesuffix(" =====") + end = lines[-1] + if end.startswith("===== exit ") and end.endswith(" ====="): + try: + return header, int(end[len("===== exit ") : -len(" =====")]) + except ValueError: + pass # a damaged line: treat it like no exit recorded + return header, None def info(msg: str) -> None: @@ -68,9 +147,11 @@ def failure(msg: str) -> None: info(f" ✗ {msg}") -def warning(msg: str) -> None: +def warning(msg: str, stdout_clean: bool = False) -> None: + """``stdout_clean`` keeps even the GitHub annotation off stdout, for + commands whose stdout is data (flow-deploy config, flow-deploy tag).""" if _is_github_actions(): - _write(f"::warning::{msg}") + _write(f"::warning::{msg}", stream=sys.stderr if stdout_clean else None) _write(f"[{_timestamp()}] WARNING: {msg}", stream=sys.stderr) diff --git a/tests/fake_host.py b/tests/fake_host.py index 0a421fc..bcb6fe0 100644 --- a/tests/fake_host.py +++ b/tests/fake_host.py @@ -40,6 +40,8 @@ class Ctr: created: int state: str = "running" ref: str = "" # what docker ps shows as Image; defaults to REPO:tag + config_hash: str = "" # compose's config-hash label when it was created + exit_code: int | None = None def ok(out: str = "") -> process.Result: @@ -67,6 +69,8 @@ def __init__(self, compose: dict, running: dict | None = None, project: str = "p self.unhealthy_services: set[tuple[str, str]] = set() # (service, tag) pairs self.stuck: set[str] = set() # services whose compose up succeeds but changes nothing self.same_created = False # docker ps shows one CreatedAt for every container + self.hashes: dict[str, str] = {} # service -> config hash now (default hash-) + self.ignores_sigterm: set[str] = set() # services docker stop has to SIGKILL 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] @@ -92,10 +96,14 @@ def add(self, service: str, tag: str, ref: str | None = None, state: str = "runn created=next(self._clock), state=state, ref=ref or f"{REPO}:{tag}", + config_hash=self.config_hash(service), ) self.ctrs.append(ctr) return ctr + def config_hash(self, service: str) -> str: + return self.hashes.get(service, f"hash-{service}") + def fail(self, substring: str, times: int | None = None, skip: int = 0) -> None: """Fail commands containing ``substring``: after ``skip`` matches, ``times`` times.""" self.failures.append([substring, skip, times]) @@ -192,6 +200,9 @@ def _git(self, args): raise AssertionError(f"FakeHost: unexpected git {args}") def _compose(self, args, tag): + if args[:1] == ["config"] and any(a.startswith("--hash=") for a in args): + names = next(a for a in args if a.startswith("--hash="))[7:].split(",") + return ok("".join(f"{n} {self.config_hash(n)}\n" for n in names)) if args[:1] == ["config"]: return ok(yaml.safe_dump(self._rendered(tag))) if args[:1] == ["pull"]: @@ -264,6 +275,9 @@ def _ps(self, args): if flag == "--filter" and value.startswith("status="): statuses.append(value.split("=", 1)[1]) statuses = statuses or ["running"] + if "config-hash" in args[-1]: + matched = [c for c in self.ctrs if c.service == service and c.state in statuses] + return ok("".join(c.config_hash + "\n" for c in matched)) lines = [ json.dumps( { @@ -283,6 +297,9 @@ def _inspect(self, args): fmt = args[args.index("--format") + 1] ids = args[args.index("--format") + 2 :] by_id = {c.id: c for c in self.ctrs} + if fmt == "{{.State.ExitCode}}": + ctr = by_id.get(ids[0]) + return ok(f"{ctr.exit_code}\n") if ctr else fail("No such container") if fmt == "{{.State.Health.Status}}": ctr = by_id.get(ids[0]) if ctr is None: @@ -297,6 +314,7 @@ def _stop(self, ctr_id): for ctr in self.ctrs: if ctr.id == ctr_id: ctr.state = "exited" + ctr.exit_code = 137 if ctr.service in self.ignores_sigterm else 0 return ok() return fail("No such container") diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index 5063a91..c397f09 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -1,5 +1,6 @@ """flow-deploy against real containers: drain-first, rolling, and every revert path.""" +import json import os import time @@ -132,6 +133,8 @@ def test_drain_that_hits_its_timeout_is_killed_and_the_deploy_continues(stack): assert stack.running()["worker"] == ["v2"] assert "(3s timeout)" in result.stdout assert time.time() - started >= 3 + # The kill is reported: PID 1 should handle SIGTERM. + assert "didn't exit on SIGTERM within 3s and was killed" in result.stderr @pytest.mark.parametrize( @@ -414,3 +417,113 @@ def test_another_project_with_other_services_in_the_directory_is_fine(stack): assert stack.running() == {"web": ["v2"], "scheduler": ["v2"], "worker": ["v2"]} finally: run(["docker", "rm", "-f", name], check=False) + + +# --------------------------------------------------------------------------- +# What an operator sees: kills, accessory drift, the run log, restore health, +# and discovery without the app's env +# --------------------------------------------------------------------------- + +ACCESSORY_LABELS = {"deploy.role": "accessory"} + + +def accessory(value): + return { + "image": "${REGISTRY}/stub:v1", + "environment": {"SETTING": value}, + "labels": ACCESSORY_LABELS, + } + + +def test_rolling_cutover_that_has_to_kill_warns(stack): + stubborn = service(100, drain=2, env={"STUB_IGNORE_SIGTERM": "1"}) + stack.commit("v1", standard(web=stubborn, scheduler=None, worker=None)) + stack.commit("v2", standard(web=stubborn, scheduler=None, worker=None)) + stack.up("v1") + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert "web (" in result.stderr and "didn't exit on SIGTERM within 2s" in result.stderr + + +def test_a_clean_deploy_warns_about_nothing(stack): + stack.commit("v1", standard(cache=accessory("a"))) + stack.commit("v2", standard(cache=accessory("a"))) + stack.up("v1") + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert "WARNING" not in result.stderr, result.stderr + + +def test_accessory_config_drift_is_reported_and_left_alone(stack): + stack.commit("v1", standard(cache=accessory("a"))) + stack.commit("v2", standard(cache=accessory("b"))) + stack.up("v1") + cache = stack.container_ids("cache") + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert "accessory cache's config changed since it started" in result.stderr + assert stack.container_ids("cache") == cache, "flow-deploy recreated an accessory" + status = stack.flow("status").stdout + assert "Accessory cache: config changed since it started" in status + + +def test_every_deploy_leaves_a_host_side_log(stack): + stack.commit("v1", standard()) + stack.commit("v2", standard()) + stack.commit("v3", standard(worker=BAD_WORKER)) + stack.up("v1") + assert stack.deploy("v2").returncode == 0 + assert stack.deploy("v3").returncode == 1 + + text = (stack.repo / ".git" / "flow-deploy.log").read_text() + runs = text.split("===== flow-deploy run ")[1:] + assert len(runs) == 2 + assert ": deploy --tag v2 =====" in runs[0] and runs[0].rstrip().endswith("exit 0 =====") + assert "worker failed to start" in runs[1] and runs[1].rstrip().endswith("exit 1 =====") + assert stack.git("status", "--porcelain") == "", "the log dirtied the tree" + assert ": deploy --tag v3: exit 1 (log: .git/flow-deploy.log)" in stack.flow("status").stdout + assert stack.record()["sha"] == stack.sha("v2") + + +def test_a_revert_waits_for_restored_services_and_exits_3_if_unhealthy(stack): + """The worker was already failing its health check before the deploy; the + revert puts it back, waits, and says so rather than exiting 1.""" + sick = service(300, "drain-first", env={"STUB_HEALTH": "fail"}, health_timeout=5) + stack.commit("v1", standard(worker=sick)) + stack.commit("unhealthy", standard(worker=sick)) + stack.up("v1", wait=False) + + result = stack.deploy("unhealthy") + + assert result.returncode == 3, result.stdout + result.stderr + assert "waiting for restored worker to be healthy" in result.stdout + assert "restored worker but it isn't healthy" in result.stdout + assert stack.head() == stack.sha("v1") + assert not stack.lock_exists() + + +def test_discovery_works_without_the_apps_env(stack): + """CI has no .env: an image named only by an unset variable used to fail + compose config outright, and with it host discovery.""" + compose = standard(scheduler=None, worker=None) + compose["services"]["worker"] = { + "image": "${APP_IMAGE_NOT_SET_IN_CI}", + "labels": {"deploy.role": "app", "deploy.order": "300"}, + } + compose["x-deploy"] = {"host": "app-1.example.com", "user": "deploy", "dir": "/srv/app"} + stack.commit("v1", compose) + stack.git("checkout", "-q", "--detach", "v1") + + result = stack.flow("config") + + assert result.returncode == 0, result.stderr + hosts = json.loads(result.stdout) + assert hosts[0]["host"] == "app-1.example.com" + assert sorted(hosts[0]["services"]) == ["web", "worker"] + assert "(unset: APP_IMAGE_NOT_SET_IN_CI)" in result.stderr diff --git a/tests/test_cli.py b/tests/test_cli.py index fa7fcff..96ca291 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -145,7 +145,9 @@ def test_config_with_command(mock_config, mock_env, mock_discover): runner = CliRunner() result = runner.invoke(main, ["config", "--command", "docker compose"]) assert result.exit_code == 0 - mock_config.assert_called_once_with(cmd=["docker", "compose"]) + mock_config.assert_called_once_with( + cmd=["docker", "compose"], env={"DEPLOY_TAG": "flow-deploy-lookup"} + ) # Status with containers and the deployed tag: tests/test_deployed.py. diff --git a/tests/test_compose.py b/tests/test_compose.py index d75dab9..f1859a3 100644 --- a/tests/test_compose.py +++ b/tests/test_compose.py @@ -62,3 +62,23 @@ def test_compose_config_raises_on_failure(mock_process): raise AssertionError("Should have raised") except RuntimeError as e: assert "compose config failed" in str(e) + + +def test_compose_config_without_interpolation(mock_process): + mock_process.responses.append(process.Result(0, "services: {}\n", "")) + compose_config(cmd=["docker", "compose"], no_interpolate=True) + assert mock_process.calls[0][1] == ["docker", "compose", "config", "--no-interpolate"] + + +def test_config_hashes(mock_process): + from flow_deploy.compose import config_hashes + + mock_process.responses.append(process.Result(0, "db abc\ncache def\n\n", "")) + mock_process.responses.append(process.Result(1, "", "unknown flag: --hash")) + assert config_hashes(["db", "cache"], cmd=["docker", "compose"]) == { + "db": "abc", + "cache": "def", + } + assert mock_process.calls[0][1] == ["docker", "compose", "config", "--hash=db,cache"] + assert config_hashes(["db"], cmd=["docker", "compose"]) is None # an older compose + assert config_hashes([]) == {} diff --git a/tests/test_containers.py b/tests/test_containers.py index 1562ef1..1cdb8d5 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -4,6 +4,7 @@ from flow_deploy import process from flow_deploy.containers import ( + exit_code, get_container_health, get_containers_for_service, identify_old_new, @@ -13,6 +14,7 @@ local_image_id, other_projects_here, remove_container, + running_config_hashes, stop_container, ) @@ -231,3 +233,29 @@ def test_other_projects_here_failure(mock_process, monkeypatch, tmp_path): monkeypatch.delenv("PWD", raising=False) mock_process.responses.append(process.Result(1, "", "daemon down")) assert other_projects_here("proj", ["web"]) is None + + +def test_exit_code(mock_process): + mock_process.responses += [ + process.Result(0, "137\n", ""), + process.Result(1, "", "No such container"), + process.Result(0, "\n", ""), + ] + assert exit_code("abc") == 137 + assert mock_process.calls[0][1] == [ + "docker", + "inspect", + "--format", + "{{.State.ExitCode}}", + "abc", + ] + assert exit_code("gone") is None + assert exit_code("odd") is None + + +def test_running_config_hashes(mock_process): + mock_process.responses += [process.Result(0, "h1\nh1\n\n", ""), process.Result(1, "", "")] + assert running_config_hashes("db", project="proj") == {"h1"} + assert "label=com.docker.compose.project=proj" in mock_process.calls[0][1] + assert "label=com.docker.compose.oneoff=False" in mock_process.calls[0][1] + assert running_config_hashes("db") is None diff --git a/tests/test_deploy_failures.py b/tests/test_deploy_failures.py index c0bee51..c00f512 100644 --- a/tests/test_deploy_failures.py +++ b/tests/test_deploy_failures.py @@ -52,6 +52,24 @@ def test_signal_mid_roll_reverts_everything(drain_host, tmp_path, signum): assert signal.getsignal(signum) is original +@pytest.mark.parametrize( + "moment", + [ + "{{.State.Health.Status}} web003", # waiting for the new container's health + "docker stop --time 30 web001", # the cutover is stopping the old one + "docker rm web001", # ... or removing it + "--scale web=1 web", # ... or scaling back + ], +) +def test_signal_mid_rolling_service_reverts_it(rolling_host, moment): + """The service being rolled is reverted too: no old and new left side by side.""" + before = rolling_host.running_images() + rolling_host.before(moment, send(signal.SIGTERM)) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + assert rolling_host.running_images() == before + assert rolling_host.sha == "prev123abc" + + def test_signal_while_a_drain_is_stopping_waits_for_it_then_reverts(drain_host, capsys): """Held until the container has stopped and been removed, then reverted.""" drain_host.before("docker stop --time 3660 worker", send(signal.SIGINT)) @@ -59,7 +77,9 @@ def test_signal_while_a_drain_is_stopping_waits_for_it_then_reverts(drain_host, assert "finishing the drain of worker0" in capsys.readouterr().out cmds = drain_host.commands() stop = drain_host.index("docker stop --time 3660 worker") - assert cmds[stop + 1].startswith("docker rm worker") # the stop and rm finished + # The stop, its exit-code check, and the rm all finished first. + assert cmds[stop + 1].startswith("docker inspect --format {{.State.ExitCode}} worker") + assert cmds[stop + 2].startswith("docker rm worker") assert drain_host.running_images() == v1(drain_host, "web", "scheduler", "worker") diff --git a/tests/test_lock.py b/tests/test_lock.py index 3c008a7..2987929 100644 --- a/tests/test_lock.py +++ b/tests/test_lock.py @@ -59,3 +59,35 @@ def test_read_lock_corrupt_returns_none(): with open(".git/deploy-lock", "w") as f: f.write("{not json") assert read_lock() is None + + +def _contend(path, barrier, results, hold): + os.chdir(path) + barrier.wait() + results.put(acquire()) + hold.wait(5) # stay alive, so a held lock isn't mistaken for a stale one + + +def test_concurrent_acquires_have_exactly_one_winner(tmp_path): + """Deploys started together: only one may get the lock. (With the guard's + flock stubbed out, the old check-then-write race let several through.)""" + import multiprocessing + + (tmp_path / ".git").mkdir(exist_ok=True) + ctx = multiprocessing.get_context("fork") + for _ in range(5): + lock_file = tmp_path / ".git" / "deploy-lock" + if lock_file.exists(): + lock_file.unlink() + barrier, results, hold = ctx.Barrier(8), ctx.Queue(), ctx.Event() + procs = [ + ctx.Process(target=_contend, args=(str(tmp_path), barrier, results, hold)) + for _ in range(8) + ] + for proc in procs: + proc.start() + wins = [results.get(timeout=10) for _ in procs] + hold.set() + for proc in procs: + proc.join(10) + assert wins.count(True) == 1 diff --git a/tests/test_operability.py b/tests/test_operability.py new file mode 100644 index 0000000..d813318 --- /dev/null +++ b/tests/test_operability.py @@ -0,0 +1,314 @@ +"""What a host operator sees: SIGKILL warnings, accessory drift, the run log, +the deploy record, health after a restore, and discovery without app env.""" + +import json +from unittest.mock import patch + +import pytest +from click.testing import CliRunner + +from flow_deploy import compose +from flow_deploy import deploy as deploy_mod +from flow_deploy import log +from flow_deploy.cli import main +from flow_deploy.deploy import EXIT_DEGRADED, deploy +from tests.fake_host import COMPOSE_CMD, FakeHost +from tests.helpers import DRAIN, ROLLING, app, chdir, record, stack + +POSTGRES = {"image": "postgres:16", "labels": {"deploy.role": "accessory"}} +WITH_DB = stack(web=app(100), worker=app(200), postgres=POSTGRES) + + +@pytest.fixture +def host(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + monkeypatch.setattr(compose, "resolve_command", lambda: list(COMPOSE_CMD)) + running = {"web": ["v1"], "worker": ["v1"], "postgres": ["16"]} + return FakeHost(WITH_DB, running=running).install(monkeypatch) + + +# --------------------------------------------------------------------------- +# 2. A container that had to be killed is reported +# --------------------------------------------------------------------------- + + +def test_a_drain_that_had_to_sigkill_warns(monkeypatch, tmp_path, capsys): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + host.ignores_sigterm.add("worker") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 # a warning, not a failure + err = capsys.readouterr().err + assert "worker (worker0" in err and "didn't exit on SIGTERM within 3660s" in err + assert "exec-form CMD" in err + + +def test_a_rolling_cutover_that_had_to_sigkill_warns(host, capsys): + host.ignores_sigterm.add("web") + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + err = capsys.readouterr().err + assert "web (web001) didn't exit on SIGTERM within 30s and was killed" in err + assert "worker (" not in err + + +def test_a_stop_that_took_the_whole_timeout_warns(host, monkeypatch, capsys): + """Exit code aside, using up the whole drain means it was killed.""" + clock = iter(range(0, 10_000, 40)) + monkeypatch.setattr(deploy_mod.time, "time", lambda: next(clock)) + assert deploy(tag="v2", services_filter=["web"], cmd=COMPOSE_CMD) == 0 + assert "web (web001) didn't exit on SIGTERM within 30s" in capsys.readouterr().err + + +def test_a_clean_stop_warns_about_nothing(host, capsys): + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert "SIGTERM" not in capsys.readouterr().err + + +# --------------------------------------------------------------------------- +# 3. Accessory config drift is reported, never acted on +# --------------------------------------------------------------------------- + + +def test_accessory_config_drift_warns_and_leaves_it_alone(host, capsys): + db = next(c for c in host.ctrs if c.service == "postgres") + host.hashes["postgres"] = "hash-after-env-change" + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert "accessory postgres's config changed since it started" in capsys.readouterr().err + assert db in host.ctrs and db.state == "running" + assert not any("postgres" in c and "up" in c for c in host.commands()) + + +def test_unchanged_accessory_warns_about_nothing(host, capsys): + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert "accessory" not in capsys.readouterr().err + + +def test_drift_check_failures_are_ignored(host, capsys): + host.fail("--hash=") + host.fail('{{.Label "com.docker.compose.config-hash"}}') + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert "accessory" not in capsys.readouterr().err + + +def test_status_shows_accessory_drift(host): + host.hashes["postgres"] = "changed" + result = CliRunner().invoke(main, ["status"]) + assert "Accessory postgres: config changed since it started" in result.stdout + + +# --------------------------------------------------------------------------- +# 6. The record holds the deployed commit +# --------------------------------------------------------------------------- + + +def test_record_holds_the_deployed_commit(host, tmp_path): + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert record(tmp_path)["sha"] == host.sha == "v2" + + +# --------------------------------------------------------------------------- +# 7. The host-side run log +# --------------------------------------------------------------------------- + + +def run_log(tmp_path): + return (tmp_path / ".git" / "flow-deploy.log").read_text() + + +def test_every_deploy_is_logged_on_the_host(host, tmp_path, monkeypatch): + monkeypatch.setenv("GITHUB_ACTIONS", "true") + assert deploy(tag="v2", services_filter=["web"], cmd=COMPOSE_CMD) == 0 + text = run_log(tmp_path) + assert text.startswith(f"{log.RUN_MARK}") + assert ": deploy --tag v2 --service web =====" in text.splitlines()[0] + assert "✓ web deployed" in text + assert "::group::" not in text # annotations are for CI, not the log + assert text.rstrip().endswith("===== exit 0 =====") + + +def test_a_failed_deploy_logs_its_exit_code(host, tmp_path): + host.unhealthy_services.add(("worker", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert run_log(tmp_path).rstrip().endswith("===== exit 1 =====") + + +def test_the_log_keeps_the_last_20_runs(host, tmp_path): + old = "".join(f"{log.RUN_MARK}old{i} =====\nline\n===== exit 0 =====\n" for i in range(25)) + (tmp_path / ".git" / "flow-deploy.log").write_text(old) + deploy(tag="v2", cmd=COMPOSE_CMD) + text = run_log(tmp_path) + assert text.count(log.RUN_MARK) == 20 + assert f"{log.RUN_MARK}old6 " in text and f"{log.RUN_MARK}old5 " not in text + assert ": deploy --tag v2 =====" in text + + +def test_a_dry_run_isnt_logged(host, tmp_path): + deploy(tag="v2", dry_run=True, cmd=COMPOSE_CMD) + assert not (tmp_path / ".git" / "flow-deploy.log").exists() + + +def test_a_locked_out_deploy_leaves_the_log_alone(host, tmp_path): + from flow_deploy import lock + + deploy(tag="v2", cmd=COMPOSE_CMD) + before = run_log(tmp_path) + lock.acquire() + try: + assert deploy(tag="v3", cmd=COMPOSE_CMD) == 2 + finally: + lock.release() + assert run_log(tmp_path) == before + + +def test_a_signal_mid_deploy_logs_the_reverts_exit(monkeypatch, tmp_path): + import signal + + chdir(monkeypatch, tmp_path) + host = FakeHost(ROLLING, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + host.before("--scale web=2", lambda: signal.getsignal(signal.SIGTERM)(signal.SIGTERM, None)) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + text = run_log(tmp_path) + assert "interrupted by signal" in text and text.rstrip().endswith("===== exit 1 =====") + + +def test_status_shows_the_last_deploy(host): + deploy(tag="v2", cmd=COMPOSE_CMD) + out = CliRunner().invoke(main, ["status"]).stdout + assert "Last deploy: " in out and ": deploy --tag v2: exit 0 (log: .git/flow-deploy.log)" in out + + +def test_status_shows_a_deploy_that_never_finished(host, tmp_path): + (tmp_path / ".git" / "flow-deploy.log").write_text(f"{log.RUN_MARK}x pid 1: deploy =====\n") + out = CliRunner().invoke(main, ["status"]).stdout + assert "Last deploy: x pid 1: deploy: no exit recorded (running, or killed)" in out + + +def test_no_git_dir_means_no_log(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + log.open_run("deploy") + log.info("hello") + log.close_run(0) + assert not (tmp_path / ".git").exists() + + +def test_a_log_that_cannot_be_written_is_skipped(host, tmp_path): + (tmp_path / ".git" / "flow-deploy.log").mkdir() # can't open a directory + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + + +def test_log_write_and_close_errors_never_raise(host, tmp_path): + log.open_run("deploy") + log._run_log.close() # the file goes away under us + log.info("still fine") + log.close_run(0) + assert log._run_log is None + + +@pytest.mark.parametrize( + "content, expected", + [ + ("", None), + ("garbage\n", None), + (f"{log.RUN_MARK}a =====\n===== exit 3 =====\n", ("a", 3)), + (f"{log.RUN_MARK}a =====\nline\n", ("a", None)), + (f"{log.RUN_MARK}a =====\n===== exit ?? =====\n", ("a", None)), + ], +) +def test_last_run(tmp_path, content, expected): + path = tmp_path / "log" + path.write_text(content) + assert log.last_run(str(path)) == expected + + +def test_last_run_without_a_file(tmp_path): + assert log.last_run(str(tmp_path / "missing")) is None + + +# --------------------------------------------------------------------------- +# 8. A revert waits for what it restored to be healthy +# --------------------------------------------------------------------------- + + +def test_a_restored_service_that_isnt_healthy_exits_3(monkeypatch, tmp_path, capsys): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + host.unhealthy_services |= {("web", "v2"), ("worker", "v1")} + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_DEGRADED + out = capsys.readouterr().out + assert "waiting for restored worker to be healthy" in out + assert "restored worker but it isn't healthy" in out + + +def test_a_healthy_restore_still_exits_1(monkeypatch, tmp_path, capsys): + chdir(monkeypatch, tmp_path) + host = FakeHost(DRAIN, running={"web": ["v1"], "worker": ["v1"]}).install(monkeypatch) + host.unhealthy_services.add(("web", "v2")) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + assert "waiting for restored worker to be healthy" in capsys.readouterr().out + + +def test_a_restored_service_that_skips_healthchecks_isnt_waited_on(monkeypatch, tmp_path): + chdir(monkeypatch, tmp_path) + beat = app(200, "drain-first", skip=True, healthcheck=False) + host = FakeHost(stack(web=app(), beat=beat), running={"web": ["v1"], "beat": ["v1"]}) + host.install(monkeypatch) + host.unhealthy_services |= {("web", "v2"), ("beat", "v1")} + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + + +def test_restore_health_check_that_cannot_list_containers(monkeypatch): + svc = deploy_mod.config.parse_services({"services": {"worker": app()}})[0] + monkeypatch.setattr(deploy_mod.containers, "list_containers_for_service", lambda *a, **k: None) + assert deploy_mod._restored_healthy(svc, "proj", 1) is False + + +def test_a_restored_container_that_exits_straight_away_exits_3(monkeypatch, capsys): + """compose up succeeded, but nothing stayed up: not restored.""" + svc = deploy_mod.config.parse_services({"services": {"worker": app(skip=True)}})[0] + monkeypatch.setattr(deploy_mod.containers, "list_containers_for_service", lambda *a, **k: []) + assert deploy_mod._restored_healthy(svc, "proj", 2) is False + assert "restored worker but only 0 of 2 containers are up" in capsys.readouterr().out + + +# --------------------------------------------------------------------------- +# 1. Discovery doesn't need the app's env +# --------------------------------------------------------------------------- + +UNSET = ( + 'compose config failed: level=warning msg="The \\"DOCKER_IMAGE\\" variable is not set. ' + 'Defaulting to a blank string."\nservice "worker" has neither an image nor a build context' +) +DISCOVERED = { + "x-deploy": {"host": "h1", "user": "deploy", "dir": "/srv"}, + "services": {"worker": {"image": "$DOCKER_IMAGE", "labels": {"deploy.role": "app"}}}, +} + + +@patch("flow_deploy.compose.compose_config") +def test_discovery_falls_back_to_the_uninterpolated_config(mock_config, monkeypatch): + monkeypatch.setenv("GITHUB_ACTIONS", "true") + mock_config.side_effect = [RuntimeError(UNSET), DISCOVERED] # as compose escapes it + result = CliRunner().invoke(main, ["config"]) + assert result.exit_code == 0 + assert json.loads(result.stdout)[0]["host"] == "h1" # stdout stays pure JSON + assert "::warning::" in result.stderr and "(unset: DOCKER_IMAGE)" in result.stderr + assert mock_config.call_args_list[1].kwargs == { + "cmd": None, + "env": {"DEPLOY_TAG": "flow-deploy-lookup"}, + "no_interpolate": True, + } + + +@patch("flow_deploy.compose.compose_config") +def test_discovery_warning_without_named_vars(mock_config): + mock_config.side_effect = [RuntimeError("compose config failed: other"), DISCOVERED] + result = CliRunner().invoke(main, ["config"]) + assert result.exit_code == 0 + assert "compose config failed with this environment; discovered" in result.stderr + + +@patch("flow_deploy.compose.compose_config") +def test_discovery_fails_if_even_uninterpolated_config_fails(mock_config): + mock_config.side_effect = [RuntimeError("compose config failed: bad"), RuntimeError("worse")] + result = CliRunner().invoke(main, ["config"]) + assert result.exit_code == 1 + assert "compose config failed: bad" in result.stderr diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py index 081b30f..eb40f3f 100644 --- a/tests/test_rolling_parity.py +++ b/tests/test_rolling_parity.py @@ -33,8 +33,9 @@ def is_snapshot(args): """The pre-deploy checks: what each app service runs and the git tag or SHA that restores it, and that no other compose project runs these - services in this directory. Plus a revert's look for stopped leftovers - that compose would otherwise restart. + services in this directory, and accessory config drift. Plus a revert's + look for stopped leftovers that compose would otherwise restart, and the + exit code of each stopped container (to warn about a SIGKILL). New on this branch, issued before anything changes, so a failure can restore what each service ran rather than what HEAD or :latest says. @@ -47,6 +48,9 @@ def is_snapshot(args): or args[:4] == ["docker", "inspect", "--format", "{{.Id}} {{.Image}}"] or args[:3] == ["docker", "image", "inspect"] or args[:3] == ["git", "rev-parse", "--verify"] + or args[:4] == ["docker", "inspect", "--format", "{{.State.ExitCode}}"] + or (args[:2] == ["docker", "ps"] and "config-hash" in line) + or any(a.startswith("--hash=") for a in args) ) @@ -104,6 +108,9 @@ def test_rolling_deploy_matches_master(name, monkeypatch, tmp_path): observed = record(deploy_mod, process, name, str(tmp_path)) calls = [[args, env] for args, env in observed["calls"] if not is_snapshot(args)] + if observed["code"] == 0 and calls[-1][0] == ["git", "rev-parse", "HEAD"]: + # Deliberate: a successful deploy records the commit it deployed. + calls.pop() tag = SCENARIOS[name][2].get("tag", "v2") or "prev123abc" expected_calls = as_on_this_branch(MASTER[name]["calls"], tag) if name == "cutover_stop_fail": From c23ca4210bb3f761e590aec738f618e006f1feba Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 11:51:07 -0600 Subject: [PATCH 15/19] Check accessory drift with compose's own recreate decision On a real host the accessory drift warning was a false positive for any service with an env_file. It compared `compose config --hash=` with the running container's config-hash label, but on Compose v5 `config --hash` hashes env_file services differently from `up`. The warning fired right after a fresh `up -d` that compose itself reported as Running. Ask compose instead. `up -d --dry-run --no-deps ` changes nothing and reports `Recreate` exactly when the next `up -d` would recreate the container. It runs with COMPOSE_PROGRESS=plain and COMPOSE_ANSI=never, because an operator's progress settings change or hide those lines. If compose can't answer (an older compose without --dry-run), no warning is given. The config-hash helpers are removed. The new integration test uses an env_file accessory. It gets no warning when unchanged and a warning after an env edit, and is never recreated. It fails on the previous code. SPEC states the compose wrapper's contract: pass arguments through, do nothing else. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 3 ++- SPEC.md | 4 +++- src/flow_deploy/compose.py | 27 +++++++++++++++------------ src/flow_deploy/containers.py | 21 --------------------- src/flow_deploy/deploy.py | 10 ++-------- tests/fake_host.py | 16 ++++++++-------- tests/integration/test_deploys.py | 30 ++++++++++++++++++++++++++++++ tests/test_compose.py | 27 +++++++++++++++------------ tests/test_containers.py | 9 --------- tests/test_operability.py | 7 ++++--- tests/test_rolling_parity.py | 3 +-- 11 files changed, 80 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index b0c460a..86325ce 100644 --- a/README.md +++ b/README.md @@ -296,7 +296,8 @@ clears the record and warns. flow-deploy never touches accessories (`deploy.role=accessory`): no pulls, no restarts. A change to one lands on the next manual `up -d`, which recreates it. So a deploy and `flow-deploy status` warn when an accessory's compose -config no longer matches the running container's (its config hash): plan that +config changed so that compose would recreate it (compose's own decision, from +`up --dry-run`): plan that recreate (data, downtime) instead of discovering it. The common cause is `.env`: compose recreates every service that reads an diff --git a/SPEC.md b/SPEC.md index 7de1282..9302010 100644 --- a/SPEC.md +++ b/SPEC.md @@ -330,6 +330,8 @@ docker compose -f docker-compose.yml -f docker-compose.prod.yml "$@" It fails closed: when `flow-deploy tag` can't tell, the wrapper stops rather than run compose on `:latest`. `flow-deploy` always sets `DEPLOY_TAG` when it calls the wrapper (to a placeholder while looking up the tag, and in `flow-deploy config`), so the default never asks it and never recurses. On a host with nothing running, pass `DEPLOY_TAG` explicitly. +The wrapper must pass its arguments to compose unchanged and do nothing else: the tool runs `config`, `pull` and `up` (including `up --dry-run` to check accessories, §3.2) through it, and `exec`, `logs` and `flow-deploy compose` pass through it too, so a wrapper with side effects of its own would run them on every one. + This pattern means the tool is completely agnostic about which compose files exist or how they're layered. The project defines its own composition strategy, and the tool just calls the wrapper with the appropriate subcommand arguments (`pull`, `up`, `stop`, etc.). **All examples in this spec that reference `` refer to whatever this wrapper resolves to.** @@ -342,7 +344,7 @@ Secrets are managed via `.env` files, which Docker Compose reads natively. The t The `.env` file should be excluded from version control and provisioned separately (via Ansible, manual setup, or a secrets manager). The tool only requires that the file exists if the compose file references it. -**Accessories and `.env`.** Compose recreates every service that reads an `env_file` when the file changes. The tool never touches accessories, so that recreate happens on the next manual `up -d`. Keep accessories off the app's `.env`: drop `env_file` and list the variables they need under `environment:` (interpolated from `.env`). Scope manual changes: `flow-deploy compose up -d --no-deps `. Each deploy, and `flow-deploy status`, warns when an accessory's compose config hash (` config --hash=`) no longer matches its running container's `com.docker.compose.config-hash` label: a recreate is pending. Warn only. +**Accessories and `.env`.** Compose recreates every service that reads an `env_file` when the file changes. The tool never touches accessories, so that recreate happens on the next manual `up -d`. Keep accessories off the app's `.env`: drop `env_file` and list the variables they need under `environment:` (interpolated from `.env`). Scope manual changes: `flow-deploy compose up -d --no-deps `. Each deploy, and `flow-deploy status`, warns when compose would recreate an accessory's running container: ` up -d --dry-run --no-deps ` reports `Recreate` (run with `COMPOSE_PROGRESS=plain`; it changes nothing). That's compose's own decision, so it matches what the next `up -d` will do, `env_file` services included (`config --hash` hashes those differently from `up`). Warn only. --- diff --git a/src/flow_deploy/compose.py b/src/flow_deploy/compose.py index 534f23b..20bcdcd 100644 --- a/src/flow_deploy/compose.py +++ b/src/flow_deploy/compose.py @@ -1,6 +1,7 @@ """Compose command resolution + execution.""" import os +import re import yaml @@ -56,19 +57,21 @@ def compose_config( return yaml.safe_load(result.stdout) -def config_hashes( - services: list[str], cmd: list[str] | None = None, env: dict[str, str] | None = None -) -> dict[str, str] | None: - """The config hash compose would label each service's containers with. +def would_recreate( + service: str, cmd: list[str] | None = None, env: dict[str, str] | None = None +) -> bool | None: + """Whether `up` would recreate ``service``'s running containers now. - What `up` compares to decide whether to recreate. None if compose can't - say (an older compose without --hash, or an error). + Asks compose itself (`up --dry-run`), so it matches compose's own + decision exactly: `config --hash` doesn't hash env_file services the way + `up` does. Changes nothing. None if compose can't say. """ - if not services: - return {} - command = (cmd or resolve_command()) + ["config", f"--hash={','.join(services)}"] - result = process.run(command, env=env) if env else process.run(command) + command = (cmd or resolve_command()) + ["up", "-d", "--dry-run", "--no-deps", service] + # Plain progress lines, whatever the operator's COMPOSE_PROGRESS says. + result = process.run( + command, env={**(env or {}), "COMPOSE_PROGRESS": "plain", "COMPOSE_ANSI": "never"} + ) if result.returncode != 0: return None - pairs = (line.split() for line in result.stdout.splitlines()) - return {p[0]: p[1] for p in pairs if len(p) == 2} + lines = (result.stdout + "\n" + result.stderr).splitlines() + return any(re.match(r"\s*Container\s+\S+\s+Recreate\b", line) for line in lines) diff --git a/src/flow_deploy/containers.py b/src/flow_deploy/containers.py index 74598a6..747f772 100644 --- a/src/flow_deploy/containers.py +++ b/src/flow_deploy/containers.py @@ -142,27 +142,6 @@ def exit_code(container_id: str) -> int | None: return None -def running_config_hashes(service: str, project: str = "") -> set[str] | None: - """The compose config hashes of a service's running containers. None if docker ps fails. - - One-off containers (`compose run`) are left out: they aren't what `up` recreates. - """ - filters = [ - "--filter", - f"label=com.docker.compose.service={service}", - "--filter", - "label=com.docker.compose.oneoff=False", - ] - if project: - filters += ["--filter", f"label=com.docker.compose.project={project}"] - result = process.run( - ["docker", "ps", *filters, "--format", '{{.Label "com.docker.compose.config-hash"}}'] - ) - if result.returncode != 0: - return None - return {line.strip() for line in result.stdout.splitlines() if line.strip()} - - def remove_container(container_id: str) -> bool: """Remove a container. Returns True on success.""" result = process.run(["docker", "rm", container_id]) diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index fbe94f7..4f4530f 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -464,15 +464,9 @@ def _warn_accessory_drift( def accessory_drift( compose_dict: dict, compose_cmd: list[str] | None, project: str, env: dict[str, str] ) -> list[str]: - """Running accessories whose compose config hash no longer matches.""" + """Running accessories that the next `up` would recreate (compose's own call).""" names = [s.name for s in config.parse_services(compose_dict) if s.role == "accessory"] - wanted = compose.config_hashes(names, cmd=compose_cmd, env=env) or {} - drifted = [] - for name in names: - running = containers.running_config_hashes(name, project=project) - if running and name in wanted and running != {wanted[name]}: - drifted.append(name) - return drifted + return [n for n in names if compose.would_recreate(n, cmd=compose_cmd, env=env)] def _degraded(problem: str) -> int: diff --git a/tests/fake_host.py b/tests/fake_host.py index bcb6fe0..86da72c 100644 --- a/tests/fake_host.py +++ b/tests/fake_host.py @@ -40,7 +40,7 @@ class Ctr: created: int state: str = "running" ref: str = "" # what docker ps shows as Image; defaults to REPO:tag - config_hash: str = "" # compose's config-hash label when it was created + config_hash: str = "" # its config when created; `up` recreates it once that changes exit_code: int | None = None @@ -69,7 +69,7 @@ def __init__(self, compose: dict, running: dict | None = None, project: str = "p self.unhealthy_services: set[tuple[str, str]] = set() # (service, tag) pairs self.stuck: set[str] = set() # services whose compose up succeeds but changes nothing self.same_created = False # docker ps shows one CreatedAt for every container - self.hashes: dict[str, str] = {} # service -> config hash now (default hash-) + self.hashes: dict[str, str] = {} # service -> its config now (default hash-) self.ignores_sigterm: set[str] = set() # services docker stop has to SIGKILL self.other_projects: list[str] = [] # other projects running these services here self.foreign_services: list[tuple[str, str]] = [] # (project, service) running here @@ -200,9 +200,6 @@ def _git(self, args): raise AssertionError(f"FakeHost: unexpected git {args}") def _compose(self, args, tag): - if args[:1] == ["config"] and any(a.startswith("--hash=") for a in args): - names = next(a for a in args if a.startswith("--hash="))[7:].split(",") - return ok("".join(f"{n} {self.config_hash(n)}\n" for n in names)) if args[:1] == ["config"]: return ok(yaml.safe_dump(self._rendered(tag))) if args[:1] == ["pull"]: @@ -231,6 +228,12 @@ def _live(self, service): def _up(self, args, tag): service = args[-1] + if "--dry-run" in args: # compose's recreate decision, changing nothing + states = [ + "Recreate" if c.config_hash != self.config_hash(service) else "Running" + for c in self._live(service) + ] + return process.Result(0, "", "".join(f" Container x {s} \n" for s in states)) replicas = 1 if "--scale" in args: replicas = int(args[args.index("--scale") + 1].split("=")[1]) @@ -275,9 +278,6 @@ def _ps(self, args): if flag == "--filter" and value.startswith("status="): statuses.append(value.split("=", 1)[1]) statuses = statuses or ["running"] - if "config-hash" in args[-1]: - matched = [c for c in self.ctrs if c.service == service and c.state in statuses] - return ok("".join(c.config_hash + "\n" for c in matched)) lines = [ json.dumps( { diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index c397f09..ded498f 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -527,3 +527,33 @@ def test_discovery_works_without_the_apps_env(stack): assert hosts[0]["host"] == "app-1.example.com" assert sorted(hosts[0]["services"]) == ["web", "worker"] assert "(unset: APP_IMAGE_NOT_SET_IN_CI)" in result.stderr + + +def test_env_file_accessory_drift_matches_composes_own_decision(stack): + """An accessory reading an env_file: no warning when compose wouldn't + recreate it (config --hash disagreed with up here), a warning once an + env edit means it would.""" + (stack.repo / ".gitignore").write_text("accessory.env\n") # like a real .env + stack.git("add", ".gitignore") + stack.git("commit", "-q", "-m", "ignore the env file") + db = {"image": "${REGISTRY}/stub:v1", "env_file": "./accessory.env", "labels": ACCESSORY_LABELS} + stack.commit("v1", standard(db=db)) + stack.commit("v2", standard(db=db)) + stack.commit("v3", standard(db=db)) + (stack.repo / "accessory.env").write_text("SETTING=a\n") + stack.up("v1") + db_ids = stack.container_ids("db") + + unchanged = stack.deploy("v2") + + assert unchanged.returncode == 0, unchanged.stdout + unchanged.stderr + assert "accessory" not in unchanged.stderr, unchanged.stderr + assert "Accessory db" not in stack.flow("status").stdout + + (stack.repo / "accessory.env").write_text("SETTING=b\n") + edited = stack.deploy("v3") + + assert edited.returncode == 0, edited.stdout + edited.stderr + assert "accessory db's config changed since it started" in edited.stderr + assert "Accessory db: config changed" in stack.flow("status").stdout + assert stack.container_ids("db") == db_ids, "flow-deploy recreated an accessory" diff --git a/tests/test_compose.py b/tests/test_compose.py index f1859a3..b3b4f41 100644 --- a/tests/test_compose.py +++ b/tests/test_compose.py @@ -70,15 +70,18 @@ def test_compose_config_without_interpolation(mock_process): assert mock_process.calls[0][1] == ["docker", "compose", "config", "--no-interpolate"] -def test_config_hashes(mock_process): - from flow_deploy.compose import config_hashes - - mock_process.responses.append(process.Result(0, "db abc\ncache def\n\n", "")) - mock_process.responses.append(process.Result(1, "", "unknown flag: --hash")) - assert config_hashes(["db", "cache"], cmd=["docker", "compose"]) == { - "db": "abc", - "cache": "def", - } - assert mock_process.calls[0][1] == ["docker", "compose", "config", "--hash=db,cache"] - assert config_hashes(["db"], cmd=["docker", "compose"]) is None # an older compose - assert config_hashes([]) == {} +def test_would_recreate_asks_compose_with_plain_progress(mock_process): + from flow_deploy.compose import would_recreate + + recreate = " Container proj-db-1 Recreate \n Container proj-db-1 Recreated \n" + mock_process.responses += [ + process.Result(0, "", recreate), + process.Result(0, "", " Container proj-db-1 Running \n"), + process.Result(1, "", "unknown flag: --dry-run"), + ] + assert would_recreate("db", cmd=["docker", "compose"], env={"DEPLOY_TAG": "v1"}) is True + _, args, env, _ = mock_process.calls[0] + assert args == ["docker", "compose", "up", "-d", "--dry-run", "--no-deps", "db"] + assert env == {"DEPLOY_TAG": "v1", "COMPOSE_PROGRESS": "plain", "COMPOSE_ANSI": "never"} + assert would_recreate("db", cmd=["docker", "compose"]) is False + assert would_recreate("db", cmd=["docker", "compose"]) is None # an older compose diff --git a/tests/test_containers.py b/tests/test_containers.py index 1cdb8d5..3735100 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -14,7 +14,6 @@ local_image_id, other_projects_here, remove_container, - running_config_hashes, stop_container, ) @@ -251,11 +250,3 @@ def test_exit_code(mock_process): ] assert exit_code("gone") is None assert exit_code("odd") is None - - -def test_running_config_hashes(mock_process): - mock_process.responses += [process.Result(0, "h1\nh1\n\n", ""), process.Result(1, "", "")] - assert running_config_hashes("db", project="proj") == {"h1"} - assert "label=com.docker.compose.project=proj" in mock_process.calls[0][1] - assert "label=com.docker.compose.oneoff=False" in mock_process.calls[0][1] - assert running_config_hashes("db") is None diff --git a/tests/test_operability.py b/tests/test_operability.py index d813318..2b1b01b 100644 --- a/tests/test_operability.py +++ b/tests/test_operability.py @@ -74,7 +74,9 @@ def test_accessory_config_drift_warns_and_leaves_it_alone(host, capsys): assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 assert "accessory postgres's config changed since it started" in capsys.readouterr().err assert db in host.ctrs and db.state == "running" - assert not any("postgres" in c and "up" in c for c in host.commands()) + # Only compose's dry run ever names it: nothing real is done to it. + ups = [c for c in host.commands() if "postgres" in c and " up " in c] + assert ups and all("--dry-run" in c for c in ups) def test_unchanged_accessory_warns_about_nothing(host, capsys): @@ -83,8 +85,7 @@ def test_unchanged_accessory_warns_about_nothing(host, capsys): def test_drift_check_failures_are_ignored(host, capsys): - host.fail("--hash=") - host.fail('{{.Label "com.docker.compose.config-hash"}}') + host.fail("--dry-run") assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 assert "accessory" not in capsys.readouterr().err diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py index eb40f3f..7d4fbe7 100644 --- a/tests/test_rolling_parity.py +++ b/tests/test_rolling_parity.py @@ -49,8 +49,7 @@ def is_snapshot(args): or args[:3] == ["docker", "image", "inspect"] or args[:3] == ["git", "rev-parse", "--verify"] or args[:4] == ["docker", "inspect", "--format", "{{.State.ExitCode}}"] - or (args[:2] == ["docker", "ps"] and "config-hash" in line) - or any(a.startswith("--hash=") for a in args) + or "--dry-run" in args ) From ec2a541d7ddfd1fbc83eb9240cea9af94f6100e7 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 12:01:17 -0600 Subject: [PATCH 16/19] Read Compose v2's dry-run lines too Compose v2 prefixes every dry-run line with " DRY-RUN MODE - ", and would_recreate anchored its match at the start of the line. On the GitHub runner (Compose v2), drift was never detected and the drift integration tests failed. The fix searches within each line. Tests now cover both formats, including "Recreated" and "Running", which must not match. Checked end to end against Compose v2.29.7 and v5.3.1: an unchanged env_file accessory is not flagged, and an edited one is. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- src/flow_deploy/compose.py | 3 ++- tests/test_compose.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/flow_deploy/compose.py b/src/flow_deploy/compose.py index 20bcdcd..2bfb183 100644 --- a/src/flow_deploy/compose.py +++ b/src/flow_deploy/compose.py @@ -74,4 +74,5 @@ def would_recreate( if result.returncode != 0: return None lines = (result.stdout + "\n" + result.stderr).splitlines() - return any(re.match(r"\s*Container\s+\S+\s+Recreate\b", line) for line in lines) + # " Container proj-db-1 Recreate" on Compose v5; v2 prefixes " DRY-RUN MODE - ". + return any(re.search(r"\bContainer\s+\S+\s+Recreate\b", line) for line in lines) diff --git a/tests/test_compose.py b/tests/test_compose.py index b3b4f41..a875f5e 100644 --- a/tests/test_compose.py +++ b/tests/test_compose.py @@ -1,5 +1,7 @@ """Tests for compose.py — command resolution + execution.""" +import pytest + from flow_deploy import process from flow_deploy.compose import compose_config, compose_run, resolve_command @@ -85,3 +87,20 @@ def test_would_recreate_asks_compose_with_plain_progress(mock_process): assert env == {"DEPLOY_TAG": "v1", "COMPOSE_PROGRESS": "plain", "COMPOSE_ANSI": "never"} assert would_recreate("db", cmd=["docker", "compose"]) is False assert would_recreate("db", cmd=["docker", "compose"]) is None # an older compose + + +@pytest.mark.parametrize( + "line, recreates", + [ + (" Container proj-db-1 Recreate ", True), # Compose v5 + (" DRY-RUN MODE - Container proj-db-1 Recreate", True), # Compose v2 + (" DRY-RUN MODE - Container proj-db-1 Recreated", False), # the simulated result + (" DRY-RUN MODE - Container proj-db-1 Running", False), + (" Container proj-db-1 Running ", False), + ], +) +def test_would_recreate_reads_both_compose_formats(mock_process, line, recreates): + from flow_deploy.compose import would_recreate + + mock_process.responses.append(process.Result(0, "", line + "\n")) + assert would_recreate("db", cmd=["docker", "compose"]) is recreates From 84013e5c65665284d59b4d555c58d19ad53c4229 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 12:19:12 -0600 Subject: [PATCH 17/19] Pass DEPLOY_TAG on every compose call, and state the wrapper contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A fail-closed compose wrapper (script/prod exits 1 when DEPLOY_TAG is unset and `flow-deploy tag` can't tell) must never run its own lookup from inside flow-deploy, or a check built on that call silently gives no answer. Three paths could hit it: - status's accessory drift check passed DEPLOY_TAG="" when the deployed tag was unknown, so no drift warning would show. It now passes the lookup placeholder. - exec and logs passed no DEPLOY_TAG. They now pass an explicit DEPLOY_TAG if one is set, else the placeholder. The FakeHost now behaves like a fail-closed wrapper by default: any compose call without DEPLOY_TAG fails. Every unit test enforces the contract, and no other path lacked it. A new integration test commits a wrapper that refuses outright without DEPLOY_TAG and drives deploy, status (with drift), config, exec and logs through it. SPEC §3.1 now states the wrapper contract. Environment setup is allowed. The wrapper must pass its arguments through unchanged, print nothing extra on stdout, exit with compose's status, and never prompt or change files. SPEC also states that flow-deploy always passes DEPLOY_TAG. The README matches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 10 ++++--- SPEC.md | 9 ++++++- src/flow_deploy/cli.py | 20 +++++++++++--- tests/fake_host.py | 16 ++++++++++- tests/integration/test_deploys.py | 44 +++++++++++++++++++++++++++++++ tests/rolling_scenarios.py | 1 + tests/test_cli.py | 10 ++++--- tests/test_operability.py | 29 ++++++++++++++++++++ 8 files changed, 128 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 86325ce..79f0a49 100644 --- a/README.md +++ b/README.md @@ -284,9 +284,13 @@ if [ -z "${DEPLOY_TAG:-}" ]; then fi ``` -flow-deploy sets `DEPLOY_TAG` itself on every compose call it makes (to a -placeholder while it looks up the tag, and in `flow-deploy config` in CI), so -the wrapper never asks it and never recurses. On a fresh host with nothing +flow-deploy sets `DEPLOY_TAG` itself on every compose call it makes: the +deploy tag, or a placeholder where the image doesn't matter or the tag isn't +known (`flow-deploy tag` itself, `config` in CI, `status`, `exec`, `logs`). So the wrapper never asks it, +never recurses, and never exits underneath it. Beyond that, a wrapper may set up +the environment, but must pass its arguments through unchanged, print nothing +extra on stdout, exit with compose's status, and never prompt or change files +(SPEC §3.1). On a fresh host with nothing running, pass the tag: `DEPLOY_TAG=v1.4.0 script/prod up -d`. A `--service` deploy that leaves some app services out leaves them on different tags, so it clears the record and warns. diff --git a/SPEC.md b/SPEC.md index 9302010..0596dfb 100644 --- a/SPEC.md +++ b/SPEC.md @@ -330,7 +330,14 @@ docker compose -f docker-compose.yml -f docker-compose.prod.yml "$@" It fails closed: when `flow-deploy tag` can't tell, the wrapper stops rather than run compose on `:latest`. `flow-deploy` always sets `DEPLOY_TAG` when it calls the wrapper (to a placeholder while looking up the tag, and in `flow-deploy config`), so the default never asks it and never recurses. On a host with nothing running, pass `DEPLOY_TAG` explicitly. -The wrapper must pass its arguments to compose unchanged and do nothing else: the tool runs `config`, `pull` and `up` (including `up --dry-run` to check accessories, §3.2) through it, and `exec`, `logs` and `flow-deploy compose` pass through it too, so a wrapper with side effects of its own would run them on every one. +**The wrapper contract.** flow-deploy runs `config`, `pull`, `up`, and `up --dry-run` (the accessory check, §3.2) through the wrapper, and `exec`, `logs` and `flow-deploy compose` pass through it too. A wrapper may set up the environment (sourcing `.env`, defaulting `DEPLOY_TAG` as below), as long as it: + +- passes its arguments to compose unchanged +- prints nothing extra on stdout (`config`'s output is parsed) +- exits with compose's exit status +- never prompts, and never changes the project or any files + +flow-deploy passes `DEPLOY_TAG` on every compose call it makes: the deploy tag, the deployed tag, or a lookup placeholder when it doesn't matter or isn't known (`config`, `status`, `exec`, `logs`). So a wrapper's own `DEPLOY_TAG` lookup never runs from inside flow-deploy. That matters for a fail-closed wrapper: a call without `DEPLOY_TAG` would exit 1, and a check built on it, like the accessory drift warning, would quietly give no answer. This pattern means the tool is completely agnostic about which compose files exist or how they're layered. The project defines its own composition strategy, and the tool just calls the wrapper with the appropriate subcommand arguments (`pull`, `up`, `stop`, etc.). diff --git a/src/flow_deploy/cli.py b/src/flow_deploy/cli.py index 26064a5..deb4ebe 100644 --- a/src/flow_deploy/cli.py +++ b/src/flow_deploy/cli.py @@ -51,7 +51,10 @@ def status(): ended = f"exit {code}" if code is not None else "no exit recorded (running, or killed)" log.info(f"Last deploy: {header}: {ended} (log: {log.RUN_LOG})") project = compose_dict.get("name", "") - for name in deploy_mod.accessory_drift(compose_dict, None, project, {"DEPLOY_TAG": tag or ""}): + # The deployed tag, or the placeholder when it's unknown: never empty, or a + # fail-closed wrapper would exit and the check would quietly say nothing. + drift_env = {"DEPLOY_TAG": tag or deployed.LOOKUP_PLACEHOLDER} + for name in deploy_mod.accessory_drift(compose_dict, None, project, drift_env): log.info(f"Accessory {name}: config changed since it started; next `up -d` recreates it") log.info("") @@ -126,10 +129,21 @@ def exec_cmd(service, command): click.echo("Error: No command specified", err=True) sys.exit(1) compose_cmd = compose.resolve_command() - code = process.run_streaming(compose_cmd + ["exec", service] + list(command)) + code = process.run_streaming(compose_cmd + ["exec", service] + list(command), env=_tag_env()) sys.exit(code) +def _tag_env() -> dict[str, str]: + """DEPLOY_TAG for compose calls whose image doesn't matter (exec, logs). + + An explicit DEPLOY_TAG wins; otherwise the lookup placeholder, so a + wrapper that defaults DEPLOY_TAG from `flow-deploy tag` never has to ask. + """ + import os + + return {"DEPLOY_TAG": os.environ.get("DEPLOY_TAG") or deployed.LOOKUP_PLACEHOLDER} + + @main.command() @click.argument("service") @click.option("--follow", "-f", is_flag=True, help="Follow log output") @@ -143,7 +157,7 @@ def logs(service, follow, tail): if tail is not None: args.extend(["--tail", str(tail)]) args.append(service) - code = process.run_streaming(compose_cmd + args) + code = process.run_streaming(compose_cmd + args, env=_tag_env()) sys.exit(code) diff --git a/tests/fake_host.py b/tests/fake_host.py index 86da72c..a5fd828 100644 --- a/tests/fake_host.py +++ b/tests/fake_host.py @@ -71,6 +71,9 @@ def __init__(self, compose: dict, running: dict | None = None, project: str = "p self.same_created = False # docker ps shows one CreatedAt for every container self.hashes: dict[str, str] = {} # service -> its config now (default hash-) self.ignores_sigterm: set[str] = set() # services docker stop has to SIGKILL + # 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.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] @@ -114,7 +117,7 @@ def before(self, substring: str, callback) -> None: def install(self, monkeypatch) -> "FakeHost": monkeypatch.setattr(process, "run", self.run) - monkeypatch.setattr(process, "run_streaming", lambda args, env=None, cwd=None: 0) + monkeypatch.setattr(process, "run_streaming", self.run_streaming) monkeypatch.setattr("flow_deploy.deploy.time.sleep", lambda _s: None) return self @@ -146,6 +149,15 @@ def index(self, *needles: str) -> int: # -- the fake ---------------------------------------------------------- + def _untagged(self, args, env) -> bool: + """A compose call a fail-closed wrapper would refuse: no DEPLOY_TAG.""" + is_compose = args[: len(COMPOSE_CMD)] == COMPOSE_CMD + return self.wrapper_requires_tag and is_compose and not (env or {}).get("DEPLOY_TAG") + + def run_streaming(self, args, env=None, cwd=None): + self.streamed.append((list(args), env)) + return 1 if self._untagged(args, env) else 0 + def run(self, args, env=None, cwd=None, new_session=False): self.calls.append(list(args)) self.envs.append(env) @@ -166,6 +178,8 @@ def run(self, args, env=None, cwd=None, new_session=False): if times is not None: rule[2] -= 1 return fail() + if self._untagged(args, env): + return fail("script/prod: set DEPLOY_TAG (flow-deploy tag couldn't tell)") tag = (env or {}).get("DEPLOY_TAG", "latest") if args[:1] == ["git"]: return self._git(args[1:]) diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index ded498f..0f60f8f 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -557,3 +557,47 @@ def test_env_file_accessory_drift_matches_composes_own_decision(stack): assert "accessory db's config changed since it started" in edited.stderr assert "Accessory db: config changed" in stack.flow("status").stdout assert stack.container_ids("db") == db_ids, "flow-deploy recreated an accessory" + + +# Stricter than the documented fail-closed snippet: it refuses outright when +# DEPLOY_TAG is unset, so a lookup that happens to succeed can't hide a call +# flow-deploy made without it. +STRICT_WRAPPER = """#!/bin/sh +if [ -z "${DEPLOY_TAG:-}" ]; then + echo "script/prod: set DEPLOY_TAG" >&2 + exit 1 +fi +exec docker compose "$@" +""" + + +def test_flow_deploy_never_leaves_the_wrapper_to_find_deploy_tag(stack): + """deploy, status (drift included), config, exec and logs all pass DEPLOY_TAG + through the project's compose wrapper, so a fail-closed wrapper never + exits underneath them and silently empties an answer.""" + wrapper = stack.repo / "script" / "prod" + wrapper.parent.mkdir() + wrapper.write_text(STRICT_WRAPPER) + wrapper.chmod(0o755) + stack.git("add", "script/prod") + stack.git("commit", "-q", "-m", "fail-closed wrapper") + x_deploy = {"host": "app-1.example.com", "user": "deploy", "dir": "/srv/app"} + stack.commit("v1", {**standard(cache=accessory("a")), "x-deploy": x_deploy}) + stack.commit("v2", {**standard(cache=accessory("b")), "x-deploy": x_deploy}) + stack.up("v1") + + result = stack.deploy("v2") + + assert result.returncode == 0, result.stdout + result.stderr + assert "script/prod: set DEPLOY_TAG" not in result.stderr + assert "accessory cache's config changed since it started" in result.stderr + status = stack.flow("status") + assert status.returncode == 0, status.stderr + assert "Accessory cache: config changed since it started" in status.stdout + config = stack.flow("config") + assert config.returncode == 0, config.stderr + assert json.loads(config.stdout)[0]["host"] == "app-1.example.com" + for args in (["exec", "-T", "web", "true"], ["logs", "--tail", "1", "web"]): + ran = stack.flow(*args) + assert ran.returncode == 0, (args, ran.stderr) + assert "script/prod: set DEPLOY_TAG" not in ran.stderr diff --git a/tests/rolling_scenarios.py b/tests/rolling_scenarios.py index 99627d4..061697f 100644 --- a/tests/rolling_scenarios.py +++ b/tests/rolling_scenarios.py @@ -86,6 +86,7 @@ def record(deploy_module, process_module, name, workdir): if transform: config = transform(config) host = FakeHost(config, running=running) + host.wrapper_requires_tag = False # master's config call didn't pass DEPLOY_TAG if setup: setup(host) process_module.run = host.run diff --git a/tests/test_cli.py b/tests/test_cli.py index 96ca291..99d2622 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -60,7 +60,8 @@ def test_exec(mock_resolve, mock_streaming): result = runner.invoke(main, ["exec", "web", "bash", "-c", "echo hi"]) assert result.exit_code == 0 mock_streaming.assert_called_once_with( - ["docker", "compose", "exec", "web", "bash", "-c", "echo hi"] + ["docker", "compose", "exec", "web", "bash", "-c", "echo hi"], + env={"DEPLOY_TAG": "flow-deploy-lookup"}, ) @@ -82,7 +83,8 @@ def test_logs(mock_resolve, mock_streaming): result = runner.invoke(main, ["logs", "web", "--follow", "--tail", "100"]) assert result.exit_code == 0 mock_streaming.assert_called_once_with( - ["docker", "compose", "logs", "--follow", "--tail", "100", "web"] + ["docker", "compose", "logs", "--follow", "--tail", "100", "web"], + env={"DEPLOY_TAG": "flow-deploy-lookup"}, ) @@ -94,7 +96,9 @@ def test_logs_basic(mock_resolve, mock_streaming): runner = CliRunner() result = runner.invoke(main, ["logs", "web"]) assert result.exit_code == 0 - mock_streaming.assert_called_once_with(["docker", "compose", "logs", "web"]) + mock_streaming.assert_called_once_with( + ["docker", "compose", "logs", "web"], env={"DEPLOY_TAG": "flow-deploy-lookup"} + ) @patch("flow_deploy.discovery.discover_hosts") diff --git a/tests/test_operability.py b/tests/test_operability.py index 2b1b01b..fe48920 100644 --- a/tests/test_operability.py +++ b/tests/test_operability.py @@ -96,6 +96,35 @@ def test_status_shows_accessory_drift(host): assert "Accessory postgres: config changed since it started" in result.stdout +def test_status_drift_check_passes_deploy_tag_when_the_tag_is_unknown(host): + """Services on different tags: the deployed tag is unknown. The drift + check still passes DEPLOY_TAG, so a fail-closed wrapper answers.""" + host.ctrs = [c for c in host.ctrs if c.service != "worker"] + host.add("worker", "v2") + host.hashes["postgres"] = "changed" + out = CliRunner().invoke(main, ["status"]).stdout + assert "Deployed tag: unknown" in out + assert "Accessory postgres: config changed since it started" in out + + +@pytest.mark.parametrize("args", [["exec", "web", "ls"], ["logs", "web"]]) +def test_exec_and_logs_pass_deploy_tag(host, args): + assert CliRunner().invoke(main, args).exit_code == 0 + assert host.streamed[-1][1] == {"DEPLOY_TAG": "flow-deploy-lookup"} + + +def test_exec_keeps_an_explicit_deploy_tag(host, monkeypatch): + monkeypatch.setenv("DEPLOY_TAG", "v9") + assert CliRunner().invoke(main, ["exec", "web", "ls"]).exit_code == 0 + assert host.streamed[-1][1] == {"DEPLOY_TAG": "v9"} + + +def test_the_fake_wrapper_refuses_an_untagged_compose_call(host): + """The strict FakeHost is what makes every test above check the contract.""" + assert host.run(list(COMPOSE_CMD) + ["config"]).returncode == 1 + assert host.run_streaming(list(COMPOSE_CMD) + ["ps"]) == 1 + + # --------------------------------------------------------------------------- # 6. The record holds the deployed commit # --------------------------------------------------------------------------- From c788babc6cf9cbae384d44fcee1fa713b5730c5e Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 14:48:55 -0600 Subject: [PATCH 18/19] Make flow-deploy upgrade check what it installs The next release is the first real `flow-deploy upgrade` on a production host, and this is the code every later upgrade runs: - A directory the user can't write is reported with what to do. 0.3.0 failed there with an UnboundLocalError traceback, because tmp_path was unset in its except block. - The downloaded binary must run (`--version` printing "flow-deploy") before it replaces the old one. A wrong-libc build or a bad download can no longer leave the host without a working flow-deploy. The replace itself is still an atomic rename beside the old binary. README gains an Upgrading section: - installs are per user, so deploy-action's `upgrade: true` upgrades only the binary of the user it deploys as - 0.3.0's upgrade risks: no check on the download, and a traceback on an unwritable directory, either of which stops the deploy - the first deploy after upgrading needs no migration Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 19 +++++++++++ src/flow_deploy/upgrade.py | 34 +++++++++++++++--- tests/test_upgrade.py | 70 ++++++++++++++++++++++++++++++++++++-- 3 files changed, 117 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 79f0a49..9253826 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,25 @@ curl -fsSL https://deploy.flowcanon.com/install | sh This installs the `flow-deploy` binary to `~/.local/bin`. Start a new login shell if it's not in your `PATH`. +### Upgrading + +`flow-deploy upgrade` replaces the running binary with the latest release. It +downloads the new binary next to the old one, checks that it runs, then renames +it over the old one, so a failed or bad download leaves the old binary in place. +It needs write access to the binary's directory. + +The install is per user: each SSH user has its own `~/.local/bin/flow-deploy`. +`deploy-action`'s `upgrade: true` upgrades the binary of the user it deploys +as, and no one else's. Projects deployed as other users, or without +`upgrade: true`, keep their version until upgraded. + +Upgrading from 0.3.0 runs 0.3.0's upgrade code, which doesn't check that the +download runs, and exits with a traceback if the binary's directory isn't +writable. Either failure makes `deploy-action`'s upgrade step fail, so the +deploy doesn't run. The first deploy after upgrading needs no migration: +`.git/deploy-tag` is written by that deploy, and containers an older version +started are restored by the tag they were started from. + ## Quick Start **1. Label your services** in `docker-compose.yml`: diff --git a/src/flow_deploy/upgrade.py b/src/flow_deploy/upgrade.py index 9978bed..6821be1 100644 --- a/src/flow_deploy/upgrade.py +++ b/src/flow_deploy/upgrade.py @@ -43,6 +43,20 @@ def _download(url: str, dest: str) -> None: raise RuntimeError("curl or wget required") +def _verify(path: str) -> str | None: + """The downloaded binary's ``--version`` line, or None if it doesn't run. + + Checked before it replaces the working binary, so a wrong-libc build or + a bad download can't leave the host without a flow-deploy that runs. + """ + try: + result = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=60) + except (OSError, subprocess.TimeoutExpired): + return None + out = result.stdout.strip() + return out if result.returncode == 0 and "flow-deploy" in out else None + + def _latest_version() -> str | None: """Fetch the latest release tag from GitHub.""" import json @@ -90,20 +104,32 @@ def upgrade() -> int: log.info(f"Detected libc: {libc}") log.info(f"Downloading latest from {url}...") - # Download to temp file in the same directory, then atomic rename + # Download to a temp file in the same directory, check it runs, then + # rename it over the old one: atomic, so the binary is never half-written. target_dir = os.path.dirname(current_path) + if not os.access(target_dir, os.W_OK): + log.error( + f"Can't upgrade {current_path}: {target_dir} isn't writable by this user. " + "Install flow-deploy where this user can write (the installer uses " + "~/.local/bin), or upgrade as the binary's owner." + ) + return 1 + tmp_path = None try: fd, tmp_path = tempfile.mkstemp(dir=target_dir, prefix=".flow-deploy-") os.close(fd) _download(url, tmp_path) os.chmod(tmp_path, os.stat(tmp_path).st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH) + new_version = _verify(tmp_path) + if new_version is None: + raise RuntimeError("the downloaded binary doesn't run (wrong libc, or a bad download)") os.replace(tmp_path, current_path) except Exception as e: - # Clean up temp file on failure - if os.path.exists(tmp_path): + # The old binary is untouched; just remove the temp file. + if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) log.error(f"Upgrade failed: {e}") return 1 - log.success("Upgraded successfully. Run 'flow-deploy --version' to verify.") + log.success(f"Upgraded: {new_version}") return 0 diff --git a/tests/test_upgrade.py b/tests/test_upgrade.py index aaf3066..51e1684 100644 --- a/tests/test_upgrade.py +++ b/tests/test_upgrade.py @@ -101,11 +101,12 @@ def test_latest_version_failure(mock_dl): assert upgrade._latest_version() is None +@patch("flow_deploy.upgrade._verify", return_value="flow-deploy, version 99.99.99") @patch("flow_deploy.upgrade._latest_version") @patch("flow_deploy.upgrade._download") @patch("flow_deploy.upgrade._binary_path") @patch("flow_deploy.upgrade._detect_libc") -def test_upgrade_success(mock_libc, mock_path, mock_dl, mock_latest, tmp_path): +def test_upgrade_success(mock_libc, mock_path, mock_dl, mock_latest, mock_verify, tmp_path): """Full upgrade succeeds: downloads, replaces binary.""" binary = tmp_path / "flow-deploy" binary.write_text("old") @@ -119,6 +120,8 @@ def test_upgrade_success(mock_libc, mock_path, mock_dl, mock_latest, tmp_path): assert result == 0 mock_dl.assert_called_once() assert "latest/download/flow-deploy-linux-glibc" in mock_dl.call_args[0][0] + assert binary.read_text() == "new" + assert not [p for p in tmp_path.iterdir() if p.name.startswith(".flow-deploy-")] @patch("flow_deploy.upgrade._latest_version") @@ -159,11 +162,12 @@ def test_upgrade_no_binary(mock_path, mock_latest): assert result == 1 +@patch("flow_deploy.upgrade._verify", return_value="flow-deploy, version 99.99.99") @patch("flow_deploy.upgrade._latest_version") @patch("flow_deploy.upgrade._download") @patch("flow_deploy.upgrade._binary_path") @patch("flow_deploy.upgrade._detect_libc") -def test_upgrade_cli(mock_libc, mock_path, mock_dl, mock_latest, tmp_path): +def test_upgrade_cli(mock_libc, mock_path, mock_dl, mock_latest, mock_verify, tmp_path): """Upgrade command via CLI.""" from click.testing import CliRunner @@ -179,3 +183,65 @@ def test_upgrade_cli(mock_libc, mock_path, mock_dl, mock_latest, tmp_path): runner = CliRunner() result = runner.invoke(main, ["upgrade"]) assert result.exit_code == 0 + + +@patch("flow_deploy.upgrade._latest_version", return_value="99.99.99") +@patch("flow_deploy.upgrade._download") +@patch("flow_deploy.upgrade._binary_path") +@patch("flow_deploy.upgrade._detect_libc", return_value="glibc") +def test_upgrade_keeps_the_old_binary_if_the_new_one_doesnt_run( + mock_libc, mock_path, mock_dl, mock_latest, tmp_path, capsys +): + """A download that isn't a working binary never replaces the one that works.""" + binary = tmp_path / "flow-deploy" + binary.write_text("old") + mock_path.return_value = str(binary) + mock_dl.side_effect = lambda url, dest: open(dest, "w").write("not a binary") + assert upgrade.upgrade() == 1 + assert binary.read_text() == "old" + assert "the downloaded binary doesn't run" in capsys.readouterr().err + assert [p.name for p in tmp_path.iterdir()] == ["flow-deploy"] # temp file removed + + +@patch("flow_deploy.upgrade._latest_version", return_value="99.99.99") +@patch("flow_deploy.upgrade._binary_path") +@patch("flow_deploy.upgrade._detect_libc", return_value="glibc") +def test_upgrade_of_an_unwritable_binary_says_so( + mock_libc, mock_path, mock_latest, tmp_path, capsys +): + """v0.3.0 crashed with a traceback here; this says what to do.""" + locked = tmp_path / "bin" + locked.mkdir() + (locked / "flow-deploy").write_text("old") + mock_path.return_value = str(locked / "flow-deploy") + locked.chmod(0o555) + try: + assert upgrade.upgrade() == 1 + finally: + locked.chmod(0o755) + assert "isn't writable by this user" in capsys.readouterr().err + assert (locked / "flow-deploy").read_text() == "old" + + +def test_verify_runs_the_binary(tmp_path): + good = tmp_path / "good" + good.write_text("#!/bin/sh\necho 'flow-deploy, version 1.2.3'\n") + good.chmod(0o755) + bad = tmp_path / "bad" + bad.write_text("#!/bin/sh\nexit 1\n") + bad.chmod(0o755) + other = tmp_path / "other" + other.write_text("#!/bin/sh\necho something else\n") + other.chmod(0o755) + assert upgrade._verify(str(good)) == "flow-deploy, version 1.2.3" + assert upgrade._verify(str(bad)) is None + assert upgrade._verify(str(other)) is None + assert upgrade._verify(str(tmp_path / "missing")) is None + + +@patch( + "flow_deploy.upgrade.subprocess.run", + side_effect=__import__("subprocess").TimeoutExpired("x", 60), +) +def test_verify_times_out(mock_run): + assert upgrade._verify("/x") is None From 927f078debe0d9258ba313531ec8fe315ab226b0 Mon Sep 17 00:00:00 2001 From: Wade Williams Date: Sun, 11 Oct 2026 15:31:14 -0600 Subject: [PATCH 19/19] Cut the accessory drift check before merge From the adversarial pre-merge review. The drift warning was warn-only, its output parsing depended on the Compose version (v2's "DRY-RUN MODE -" prefix versus v5), it added a dry-run call per accessory on every deploy, and an earlier form had false positives. The root cause it targeted, .env edits recreating accessories, is handled by the documented pattern: accessories drop env_file and list their variables under environment:. Removed: compose.would_recreate, the deploy-time warning, the status line, the FakeHost dry-run model, and their unit and integration tests. Kept, deliberately: the "one image under :latest plus one other tag" case in deployed.current(). Without it, after a failed first deploy from an all-:latest host, the failed service keeps its :latest container while restored services run the previous SHA. `flow-deploy tag` would then refuse, and a project's fail-closed script/prod would refuse every manual and scripted compose call until the next deploy. A new test pins that scenario end to end. Docs no longer promise more than the code does: - no drift warning - files are written in .git - a failure restores or exits 3 - a build: service is rebuilt when its full-SHA image is missing Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Be6ghMqRxW6R4WS3vJY1Yv --- README.md | 7 +-- SPEC.md | 12 ++--- docs/github-actions.md | 3 -- src/flow_deploy/cli.py | 6 --- src/flow_deploy/compose.py | 22 -------- src/flow_deploy/deploy.py | 25 ---------- src/flow_deploy/deployed.py | 8 +-- tests/fake_host.py | 12 ----- tests/integration/test_deploys.py | 55 ++------------------ tests/test_compose.py | 36 -------------- tests/test_operability.py | 83 +++++++++++++++---------------- tests/test_rolling_parity.py | 7 ++- 12 files changed, 60 insertions(+), 216 deletions(-) diff --git a/README.md b/README.md index 9253826..ed0d6d9 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ One case has no git name for the previous build: redeploying the commit that's already running. If its image was rebuilt and re-pushed under the same tag, a revert restores that commit as pulled now; the deploy warns when it sees this. (Before this release, shipped services weren't rolled back at all.) -Nothing is tagged or written on the host. If another compose project runs this +Nothing is tagged on the host, and nothing is written outside `.git`. If another compose project runs this deploy's services in the same directory (a release that renamed the project would start a second stack beside the first), the deploy stops before changing anything. @@ -318,10 +318,7 @@ clears the record and warns. flow-deploy never touches accessories (`deploy.role=accessory`): no pulls, no restarts. A change to one lands on the next manual `up -d`, which recreates -it. So a deploy and `flow-deploy status` warn when an accessory's compose -config changed so that compose would recreate it (compose's own decision, from -`up --dry-run`): plan that -recreate (data, downtime) instead of discovering it. +it, so plan such changes (data, downtime). The common cause is `.env`: compose recreates every service that reads an `env_file` when the file changes, postgres and redis included. Keep diff --git a/SPEC.md b/SPEC.md index 0596dfb..539020b 100644 --- a/SPEC.md +++ b/SPEC.md @@ -10,7 +10,7 @@ A minimal, opinionated deployment tool for Docker Compose + Traefik stacks. Repl - **Two layers, clean split.** A server-side CLI (`flow-deploy`) handles the single-node deploy lifecycle — pull, scale, health check, cutover. A GitHub Action (`flow-deploy-action`) handles host discovery, fleet orchestration, and SSH fan-out. Single-host projects can skip the action entirely. - **Accessories are left alone.** Databases, caches, and other stateful services are never restarted during a deploy unless explicitly requested. - **Builds happen in CI.** The tool does not build images. GitHub Actions builds and pushes to GHCR. The tool pulls and swaps. -- **Failure is a no-op.** If a new container fails its health check, the old container continues serving traffic untouched. Any failure puts every app service back on the exact image it ran before the deploy, and the deploy exits nonzero. +- **Failure is a no-op.** If a new container fails its health check, the old container continues serving traffic untouched. Any failure puts every app service back on the image it ran before the deploy and exits 1, or exits 3 naming what it couldn't put back. - **Logging is the interface.** All output is structured, human-readable, and designed to flow through an SSH session back into GitHub Actions logs. --- @@ -267,7 +267,7 @@ services: CI must push the image under every tag it may deploy by: the version, and always the full commit SHA, which a revert falls back to. The deploy renders its compose config with `DEPLOY_TAG` set and warns when an app image doesn't end in `:`; such a service keeps whatever image the compose file names. -**What's running.** Restores are named by git: a release tag or a commit SHA. The pre-deploy snapshot (§2.2, 0g) records each service's running image ID and the tag it was started from. A revert uses that tag when it is a git ref, still names the running image locally, and isn't the tag being deployed (the deploy pulls that, which would move a re-pushed tag). Otherwise (started from `:latest`, from a tag re-pushed since, from a digest, untagged, or a redeploy of the same tag) it uses the full SHA of the commit checked out before the deploy, so CI must push every image under its full commit SHA. If that image isn't in the registry the restore fails and the deploy exits 3. Redeploying the commit that's already checked out leaves no other git name for the running build: if its image was rebuilt under the same tag, a revert restores the rebuild, and the deploy warns up front. flow-deploy creates no tags and writes nothing in the working tree. +**What's running.** Restores are named by git: a release tag or a commit SHA. The pre-deploy snapshot (§2.2, 0g) records each service's running image ID and the tag it was started from. A revert uses that tag when it is a git ref, still names the running image locally, and isn't the tag being deployed (the deploy pulls that, which would move a re-pushed tag). Otherwise (started from `:latest`, from a tag re-pushed since, from a digest, untagged, or a redeploy of the same tag) it uses the full SHA of the commit checked out before the deploy, so CI must push every image under its full commit SHA. If that image isn't in the registry, the restore fails and the deploy exits 3 (for a service with `build:`, compose builds it from the restored checkout instead). Redeploying the commit that's already checked out leaves no other git name for the running build: if its image was rebuilt under the same tag, a revert restores the rebuild, and the deploy warns up front. flow-deploy creates no tags and writes nothing in the working tree. **What's deployed.** `flow-deploy tag` (§4.7) answers "which tag is deployed here": the tag of the running app containers when they all agree; if they run one image under `:latest` and one other tag (after a revert from `:latest`), that other tag; otherwise, when nothing is running, `.git/deploy-tag`. Anything else mixed, or untagged, is an error, never a guess. The record is written after every successful deploy of all app services, rewritten to the restore tag after a revert, and cleared by a `--service` deploy that leaves some app services out (they're then on different tags). @@ -330,14 +330,14 @@ docker compose -f docker-compose.yml -f docker-compose.prod.yml "$@" It fails closed: when `flow-deploy tag` can't tell, the wrapper stops rather than run compose on `:latest`. `flow-deploy` always sets `DEPLOY_TAG` when it calls the wrapper (to a placeholder while looking up the tag, and in `flow-deploy config`), so the default never asks it and never recurses. On a host with nothing running, pass `DEPLOY_TAG` explicitly. -**The wrapper contract.** flow-deploy runs `config`, `pull`, `up`, and `up --dry-run` (the accessory check, §3.2) through the wrapper, and `exec`, `logs` and `flow-deploy compose` pass through it too. A wrapper may set up the environment (sourcing `.env`, defaulting `DEPLOY_TAG` as below), as long as it: +**The wrapper contract.** flow-deploy runs `config`, `pull` and `up` through the wrapper, and `exec`, `logs` and `flow-deploy compose` pass through it too. A wrapper may set up the environment (sourcing `.env`, defaulting `DEPLOY_TAG` as below), as long as it: - passes its arguments to compose unchanged - prints nothing extra on stdout (`config`'s output is parsed) - exits with compose's exit status - never prompts, and never changes the project or any files -flow-deploy passes `DEPLOY_TAG` on every compose call it makes: the deploy tag, the deployed tag, or a lookup placeholder when it doesn't matter or isn't known (`config`, `status`, `exec`, `logs`). So a wrapper's own `DEPLOY_TAG` lookup never runs from inside flow-deploy. That matters for a fail-closed wrapper: a call without `DEPLOY_TAG` would exit 1, and a check built on it, like the accessory drift warning, would quietly give no answer. +flow-deploy passes `DEPLOY_TAG` on every compose call it makes: the deploy tag, the deployed tag, or a lookup placeholder when it doesn't matter or isn't known (`config`, `status`, `exec`, `logs`). So a wrapper's own `DEPLOY_TAG` lookup never runs from inside flow-deploy. That matters for a fail-closed wrapper: a call without `DEPLOY_TAG` would exit 1, failing whatever flow-deploy was doing. This pattern means the tool is completely agnostic about which compose files exist or how they're layered. The project defines its own composition strategy, and the tool just calls the wrapper with the appropriate subcommand arguments (`pull`, `up`, `stop`, etc.). @@ -351,7 +351,7 @@ Secrets are managed via `.env` files, which Docker Compose reads natively. The t The `.env` file should be excluded from version control and provisioned separately (via Ansible, manual setup, or a secrets manager). The tool only requires that the file exists if the compose file references it. -**Accessories and `.env`.** Compose recreates every service that reads an `env_file` when the file changes. The tool never touches accessories, so that recreate happens on the next manual `up -d`. Keep accessories off the app's `.env`: drop `env_file` and list the variables they need under `environment:` (interpolated from `.env`). Scope manual changes: `flow-deploy compose up -d --no-deps `. Each deploy, and `flow-deploy status`, warns when compose would recreate an accessory's running container: ` up -d --dry-run --no-deps ` reports `Recreate` (run with `COMPOSE_PROGRESS=plain`; it changes nothing). That's compose's own decision, so it matches what the next `up -d` will do, `env_file` services included (`config --hash` hashes those differently from `up`). Warn only. +**Accessories and `.env`.** Compose recreates every service that reads an `env_file` when the file changes. The tool never touches accessories, so that recreate happens on the next manual `up -d`. Keep accessories off the app's `.env`: drop `env_file` and list the variables they need under `environment:` (interpolated from `.env`). Scope manual changes: `flow-deploy compose up -d --no-deps `. --- @@ -391,7 +391,7 @@ Show the current state of all managed services. flow-deploy status ``` -Output includes: current HEAD SHA, the deployed tag and where it came from (§2.8), the last deploy from `.git/flow-deploy.log` and how it ended (or that it never recorded an exit: still running, or killed), accessories whose config changed since they started (§3.2), and per container: service name, role, container ID, image, health status. +Output includes: current HEAD SHA, the deployed tag and where it came from (§2.8), the last deploy from `.git/flow-deploy.log` and how it ended (or that it never recorded an exit: still running, or killed), and per container: service name, role, container ID, image, health status. ### 4.3 `flow-deploy exec` diff --git a/docs/github-actions.md b/docs/github-actions.md index 3b066bf..e1a693d 100644 --- a/docs/github-actions.md +++ b/docs/github-actions.md @@ -299,9 +299,6 @@ CI has no `.env`, so variables only set there are empty. Discovery retries witho **`didn't exit on SIGTERM ... and was killed`:** The container's PID 1 isn't handling SIGTERM, so every deploy waits out the drain and kills it mid-request. Use an exec-form `CMD` (`["gunicorn", ...]`), or `exec` the server at the end of the entrypoint script. -**`accessory postgres's config changed since it started`:** -The next manual `up -d` will recreate it. Usually an `.env` edit: keep accessories off `env_file` and list their variables under `environment:` (see the README's "Accessories and `.env`"). - **How did a deploy end, when CI was cancelled?** On the host: `flow-deploy status` (last run and exit code), or `.git/flow-deploy.log`. diff --git a/src/flow_deploy/cli.py b/src/flow_deploy/cli.py index deb4ebe..6a01464 100644 --- a/src/flow_deploy/cli.py +++ b/src/flow_deploy/cli.py @@ -50,12 +50,6 @@ def status(): header, code = last ended = f"exit {code}" if code is not None else "no exit recorded (running, or killed)" log.info(f"Last deploy: {header}: {ended} (log: {log.RUN_LOG})") - project = compose_dict.get("name", "") - # The deployed tag, or the placeholder when it's unknown: never empty, or a - # fail-closed wrapper would exit and the check would quietly say nothing. - drift_env = {"DEPLOY_TAG": tag or deployed.LOOKUP_PLACEHOLDER} - for name in deploy_mod.accessory_drift(compose_dict, None, project, drift_env): - log.info(f"Accessory {name}: config changed since it started; next `up -d` recreates it") log.info("") for svc in all_services: diff --git a/src/flow_deploy/compose.py b/src/flow_deploy/compose.py index 2bfb183..045a230 100644 --- a/src/flow_deploy/compose.py +++ b/src/flow_deploy/compose.py @@ -1,7 +1,6 @@ """Compose command resolution + execution.""" import os -import re import yaml @@ -55,24 +54,3 @@ def compose_config( if result.returncode != 0: raise RuntimeError(f"compose config failed: {result.stderr}") return yaml.safe_load(result.stdout) - - -def would_recreate( - service: str, cmd: list[str] | None = None, env: dict[str, str] | None = None -) -> bool | None: - """Whether `up` would recreate ``service``'s running containers now. - - Asks compose itself (`up --dry-run`), so it matches compose's own - decision exactly: `config --hash` doesn't hash env_file services the way - `up` does. Changes nothing. None if compose can't say. - """ - command = (cmd or resolve_command()) + ["up", "-d", "--dry-run", "--no-deps", service] - # Plain progress lines, whatever the operator's COMPOSE_PROGRESS says. - result = process.run( - command, env={**(env or {}), "COMPOSE_PROGRESS": "plain", "COMPOSE_ANSI": "never"} - ) - if result.returncode != 0: - return None - lines = (result.stdout + "\n" + result.stderr).splitlines() - # " Container proj-db-1 Recreate" on Compose v5; v2 prefixes " DRY-RUN MODE - ". - return any(re.search(r"\bContainer\s+\S+\s+Recreate\b", line) for line in lines) diff --git a/src/flow_deploy/deploy.py b/src/flow_deploy/deploy.py index 4f4530f..32c2b76 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -251,7 +251,6 @@ def _deploy_locked( project = run.project compose_cmd = run.compose_cmd start_time = time.time() - _warn_accessory_drift(compose_dict, compose_cmd, project, {"DEPLOY_TAG": tag}) # A release that renames the compose project would start a second stack # beside the running one, and snapshot (so revert) nothing. @@ -445,30 +444,6 @@ def _stop_reporting(name: str, ctr_id: str, timeout: int, isolate: bool = False) return True -def _warn_accessory_drift( - compose_dict: dict, compose_cmd: list[str], project: str, env: dict[str, str] -) -> None: - """Warn about accessories whose config changed since they were started. - - flow-deploy never touches accessories, so the change lands on the next - manual `up -d`, which recreates them: plan it (data, downtime). Only a - warning; any trouble working it out is ignored. - """ - for name in accessory_drift(compose_dict, compose_cmd, project, env): - log.warning( - f"accessory {name}'s config changed since it started; the next `up -d` " - "will recreate it. flow-deploy leaves it alone: plan that change." - ) - - -def accessory_drift( - compose_dict: dict, compose_cmd: list[str] | None, project: str, env: dict[str, str] -) -> list[str]: - """Running accessories that the next `up` would recreate (compose's own call).""" - names = [s.name for s in config.parse_services(compose_dict) if s.role == "accessory"] - return [n for n in names if compose.would_recreate(n, cmd=compose_cmd, env=env)] - - def _degraded(problem: str) -> int: log.error( f"Deploy failed and could not be fully reverted ({problem}). " diff --git a/src/flow_deploy/deployed.py b/src/flow_deploy/deployed.py index e8f2ac7..14dcaf0 100644 --- a/src/flow_deploy/deployed.py +++ b/src/flow_deploy/deployed.py @@ -66,9 +66,11 @@ def current(compose_cmd: list[str] | None = None) -> tuple[str | None, str]: if len(tags) == 1 and None not in tags: return next(iter(tags)), "running containers" if len(tags) > 1 and None not in tags and len(tags.keys() - {"latest"}) == 1: - # After a revert from :latest, a recreated service runs the previous - # commit's SHA while a kept container still says :latest. If they run - # one image, the SHA names it. + # After a failed deploy from :latest, recreated services run the + # previous commit's SHA while the failed service's kept container still + # says :latest. If they run one image, the SHA names it. Refusing here + # would make a fail-closed wrapper refuse every compose call until the + # next deploy. images = containers.image_ids(ids) if images is None: raise RuntimeError("could not inspect the app containers (docker inspect failed)") diff --git a/tests/fake_host.py b/tests/fake_host.py index a5fd828..b7a1ad7 100644 --- a/tests/fake_host.py +++ b/tests/fake_host.py @@ -40,7 +40,6 @@ class Ctr: created: int state: str = "running" ref: str = "" # what docker ps shows as Image; defaults to REPO:tag - config_hash: str = "" # its config when created; `up` recreates it once that changes exit_code: int | None = None @@ -69,7 +68,6 @@ def __init__(self, compose: dict, running: dict | None = None, project: str = "p self.unhealthy_services: set[tuple[str, str]] = set() # (service, tag) pairs self.stuck: set[str] = set() # services whose compose up succeeds but changes nothing self.same_created = False # docker ps shows one CreatedAt for every container - self.hashes: dict[str, str] = {} # service -> its config now (default hash-) self.ignores_sigterm: set[str] = set() # services docker stop has to SIGKILL # Like a fail-closed script/prod: a compose call without DEPLOY_TAG fails. self.wrapper_requires_tag = True @@ -99,14 +97,10 @@ def add(self, service: str, tag: str, ref: str | None = None, state: str = "runn created=next(self._clock), state=state, ref=ref or f"{REPO}:{tag}", - config_hash=self.config_hash(service), ) self.ctrs.append(ctr) return ctr - def config_hash(self, service: str) -> str: - return self.hashes.get(service, f"hash-{service}") - def fail(self, substring: str, times: int | None = None, skip: int = 0) -> None: """Fail commands containing ``substring``: after ``skip`` matches, ``times`` times.""" self.failures.append([substring, skip, times]) @@ -242,12 +236,6 @@ def _live(self, service): def _up(self, args, tag): service = args[-1] - if "--dry-run" in args: # compose's recreate decision, changing nothing - states = [ - "Recreate" if c.config_hash != self.config_hash(service) else "Running" - for c in self._live(service) - ] - return process.Result(0, "", "".join(f" Container x {s} \n" for s in states)) replicas = 1 if "--scale" in args: replicas = int(args[args.index("--scale") + 1].split("=")[1]) diff --git a/tests/integration/test_deploys.py b/tests/integration/test_deploys.py index 0f60f8f..be41034 100644 --- a/tests/integration/test_deploys.py +++ b/tests/integration/test_deploys.py @@ -420,7 +420,7 @@ def test_another_project_with_other_services_in_the_directory_is_fine(stack): # --------------------------------------------------------------------------- -# What an operator sees: kills, accessory drift, the run log, restore health, +# What an operator sees: kills, the run log, restore health, # and discovery without the app's env # --------------------------------------------------------------------------- @@ -458,21 +458,6 @@ def test_a_clean_deploy_warns_about_nothing(stack): assert "WARNING" not in result.stderr, result.stderr -def test_accessory_config_drift_is_reported_and_left_alone(stack): - stack.commit("v1", standard(cache=accessory("a"))) - stack.commit("v2", standard(cache=accessory("b"))) - stack.up("v1") - cache = stack.container_ids("cache") - - result = stack.deploy("v2") - - assert result.returncode == 0, result.stdout + result.stderr - assert "accessory cache's config changed since it started" in result.stderr - assert stack.container_ids("cache") == cache, "flow-deploy recreated an accessory" - status = stack.flow("status").stdout - assert "Accessory cache: config changed since it started" in status - - def test_every_deploy_leaves_a_host_side_log(stack): stack.commit("v1", standard()) stack.commit("v2", standard()) @@ -529,39 +514,6 @@ def test_discovery_works_without_the_apps_env(stack): assert "(unset: APP_IMAGE_NOT_SET_IN_CI)" in result.stderr -def test_env_file_accessory_drift_matches_composes_own_decision(stack): - """An accessory reading an env_file: no warning when compose wouldn't - recreate it (config --hash disagreed with up here), a warning once an - env edit means it would.""" - (stack.repo / ".gitignore").write_text("accessory.env\n") # like a real .env - stack.git("add", ".gitignore") - stack.git("commit", "-q", "-m", "ignore the env file") - db = {"image": "${REGISTRY}/stub:v1", "env_file": "./accessory.env", "labels": ACCESSORY_LABELS} - stack.commit("v1", standard(db=db)) - stack.commit("v2", standard(db=db)) - stack.commit("v3", standard(db=db)) - (stack.repo / "accessory.env").write_text("SETTING=a\n") - stack.up("v1") - db_ids = stack.container_ids("db") - - unchanged = stack.deploy("v2") - - assert unchanged.returncode == 0, unchanged.stdout + unchanged.stderr - assert "accessory" not in unchanged.stderr, unchanged.stderr - assert "Accessory db" not in stack.flow("status").stdout - - (stack.repo / "accessory.env").write_text("SETTING=b\n") - edited = stack.deploy("v3") - - assert edited.returncode == 0, edited.stdout + edited.stderr - assert "accessory db's config changed since it started" in edited.stderr - assert "Accessory db: config changed" in stack.flow("status").stdout - assert stack.container_ids("db") == db_ids, "flow-deploy recreated an accessory" - - -# Stricter than the documented fail-closed snippet: it refuses outright when -# DEPLOY_TAG is unset, so a lookup that happens to succeed can't hide a call -# flow-deploy made without it. STRICT_WRAPPER = """#!/bin/sh if [ -z "${DEPLOY_TAG:-}" ]; then echo "script/prod: set DEPLOY_TAG" >&2 @@ -572,7 +524,7 @@ def test_env_file_accessory_drift_matches_composes_own_decision(stack): def test_flow_deploy_never_leaves_the_wrapper_to_find_deploy_tag(stack): - """deploy, status (drift included), config, exec and logs all pass DEPLOY_TAG + """deploy, status, config, exec and logs all pass DEPLOY_TAG through the project's compose wrapper, so a fail-closed wrapper never exits underneath them and silently empties an answer.""" wrapper = stack.repo / "script" / "prod" @@ -590,10 +542,9 @@ def test_flow_deploy_never_leaves_the_wrapper_to_find_deploy_tag(stack): assert result.returncode == 0, result.stdout + result.stderr assert "script/prod: set DEPLOY_TAG" not in result.stderr - assert "accessory cache's config changed since it started" in result.stderr status = stack.flow("status") assert status.returncode == 0, status.stderr - assert "Accessory cache: config changed since it started" in status.stdout + assert "Deployed tag: v2 (from running containers)" in status.stdout config = stack.flow("config") assert config.returncode == 0, config.stderr assert json.loads(config.stdout)[0]["host"] == "app-1.example.com" diff --git a/tests/test_compose.py b/tests/test_compose.py index a875f5e..2164a72 100644 --- a/tests/test_compose.py +++ b/tests/test_compose.py @@ -1,7 +1,5 @@ """Tests for compose.py — command resolution + execution.""" -import pytest - from flow_deploy import process from flow_deploy.compose import compose_config, compose_run, resolve_command @@ -70,37 +68,3 @@ def test_compose_config_without_interpolation(mock_process): mock_process.responses.append(process.Result(0, "services: {}\n", "")) compose_config(cmd=["docker", "compose"], no_interpolate=True) assert mock_process.calls[0][1] == ["docker", "compose", "config", "--no-interpolate"] - - -def test_would_recreate_asks_compose_with_plain_progress(mock_process): - from flow_deploy.compose import would_recreate - - recreate = " Container proj-db-1 Recreate \n Container proj-db-1 Recreated \n" - mock_process.responses += [ - process.Result(0, "", recreate), - process.Result(0, "", " Container proj-db-1 Running \n"), - process.Result(1, "", "unknown flag: --dry-run"), - ] - assert would_recreate("db", cmd=["docker", "compose"], env={"DEPLOY_TAG": "v1"}) is True - _, args, env, _ = mock_process.calls[0] - assert args == ["docker", "compose", "up", "-d", "--dry-run", "--no-deps", "db"] - assert env == {"DEPLOY_TAG": "v1", "COMPOSE_PROGRESS": "plain", "COMPOSE_ANSI": "never"} - assert would_recreate("db", cmd=["docker", "compose"]) is False - assert would_recreate("db", cmd=["docker", "compose"]) is None # an older compose - - -@pytest.mark.parametrize( - "line, recreates", - [ - (" Container proj-db-1 Recreate ", True), # Compose v5 - (" DRY-RUN MODE - Container proj-db-1 Recreate", True), # Compose v2 - (" DRY-RUN MODE - Container proj-db-1 Recreated", False), # the simulated result - (" DRY-RUN MODE - Container proj-db-1 Running", False), - (" Container proj-db-1 Running ", False), - ], -) -def test_would_recreate_reads_both_compose_formats(mock_process, line, recreates): - from flow_deploy.compose import would_recreate - - mock_process.responses.append(process.Result(0, "", line + "\n")) - assert would_recreate("db", cmd=["docker", "compose"]) is recreates diff --git a/tests/test_operability.py b/tests/test_operability.py index fe48920..ee56eb2 100644 --- a/tests/test_operability.py +++ b/tests/test_operability.py @@ -1,5 +1,5 @@ -"""What a host operator sees: SIGKILL warnings, accessory drift, the run log, -the deploy record, health after a restore, and discovery without app env.""" +"""What a host operator sees: SIGKILL warnings, the run log, the deploy +record, health after a restore, and discovery without app env.""" import json from unittest.mock import patch @@ -63,48 +63,15 @@ def test_a_clean_stop_warns_about_nothing(host, capsys): assert "SIGTERM" not in capsys.readouterr().err -# --------------------------------------------------------------------------- -# 3. Accessory config drift is reported, never acted on -# --------------------------------------------------------------------------- - - -def test_accessory_config_drift_warns_and_leaves_it_alone(host, capsys): - db = next(c for c in host.ctrs if c.service == "postgres") - host.hashes["postgres"] = "hash-after-env-change" - assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 - assert "accessory postgres's config changed since it started" in capsys.readouterr().err - assert db in host.ctrs and db.state == "running" - # Only compose's dry run ever names it: nothing real is done to it. - ups = [c for c in host.commands() if "postgres" in c and " up " in c] - assert ups and all("--dry-run" in c for c in ups) - - -def test_unchanged_accessory_warns_about_nothing(host, capsys): - assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 - assert "accessory" not in capsys.readouterr().err - - -def test_drift_check_failures_are_ignored(host, capsys): - host.fail("--dry-run") - assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 - assert "accessory" not in capsys.readouterr().err - - -def test_status_shows_accessory_drift(host): - host.hashes["postgres"] = "changed" - result = CliRunner().invoke(main, ["status"]) - assert "Accessory postgres: config changed since it started" in result.stdout - - -def test_status_drift_check_passes_deploy_tag_when_the_tag_is_unknown(host): - """Services on different tags: the deployed tag is unknown. The drift - check still passes DEPLOY_TAG, so a fail-closed wrapper answers.""" +def test_status_works_through_a_fail_closed_wrapper_when_the_tag_is_unknown(host): + """Services on different tags: the deployed tag is unknown. status still + passes DEPLOY_TAG on its compose calls, so a fail-closed wrapper answers.""" host.ctrs = [c for c in host.ctrs if c.service != "worker"] host.add("worker", "v2") - host.hashes["postgres"] = "changed" - out = CliRunner().invoke(main, ["status"]).stdout - assert "Deployed tag: unknown" in out - assert "Accessory postgres: config changed since it started" in out + result = CliRunner().invoke(main, ["status"]) + assert result.exit_code == 0 + assert "Deployed tag: unknown" in result.stdout + assert "postgres (accessory)" in result.stdout @pytest.mark.parametrize("args", [["exec", "web", "ls"], ["logs", "web"]]) @@ -135,6 +102,38 @@ def test_record_holds_the_deployed_commit(host, tmp_path): assert record(tmp_path)["sha"] == host.sha == "v2" +def test_a_failed_first_deploy_from_latest_reverts_by_sha_and_tag_still_answers( + monkeypatch, tmp_path +): + """A host whose services all run :latest (as before its first tagged deploy), + and the deploy fails. The revert restores by the previous commit's SHA; the + failed rolling service keeps its :latest container, so the host runs one + image under two tags. `flow-deploy tag` must still answer (the SHA), or a + fail-closed wrapper would refuse every manual and scripted compose call + until the next deploy.""" + from flow_deploy import deployed + + chdir(monkeypatch, tmp_path) + running = {"web": ["latest"], "scheduler": ["latest"], "worker": ["latest"]} + host = FakeHost(DRAIN, running=running).install(monkeypatch) + monkeypatch.setattr(compose, "resolve_command", lambda: list(COMPOSE_CMD)) + host.registry["prev123abc"] = host.images["latest"] # CI pushed that build by SHA too + before = host.running_images() + host.unhealthy_services.add(("web", "v2")) + + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 1 + + assert host.running_images() == before + assert host.running() == { + "web": ["latest"], + "scheduler": ["prev123abc"], + "worker": ["prev123abc"], + } + assert deployed.current() == ("prev123abc", "running containers (one image)") + result = CliRunner().invoke(main, ["tag"]) + assert result.exit_code == 0 and result.stdout == "prev123abc\n" + + # --------------------------------------------------------------------------- # 7. The host-side run log # --------------------------------------------------------------------------- diff --git a/tests/test_rolling_parity.py b/tests/test_rolling_parity.py index 7d4fbe7..14601e3 100644 --- a/tests/test_rolling_parity.py +++ b/tests/test_rolling_parity.py @@ -33,9 +33,9 @@ def is_snapshot(args): """The pre-deploy checks: what each app service runs and the git tag or SHA that restores it, and that no other compose project runs these - services in this directory, and accessory config drift. Plus a revert's - look for stopped leftovers that compose would otherwise restart, and the - exit code of each stopped container (to warn about a SIGKILL). + services in this directory. Plus a revert's look for stopped leftovers + that compose would otherwise restart, and the exit code of each stopped + container (to warn about a SIGKILL). New on this branch, issued before anything changes, so a failure can restore what each service ran rather than what HEAD or :latest says. @@ -49,7 +49,6 @@ def is_snapshot(args): or args[:3] == ["docker", "image", "inspect"] or args[:3] == ["git", "rev-parse", "--verify"] or args[:4] == ["docker", "inspect", "--format", "{{.State.ExitCode}}"] - or "--dry-run" in args )