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 ddb6e55..ed0d6d9 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`: @@ -35,19 +54,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)... @@ -89,6 +112,234 @@ 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.** 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. 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. + +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.** 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. + +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, 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 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. + +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 +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. + +**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. 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, 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 + +Even then the lock is released. Exit `3` is the signal that someone needs to +look. + +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 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 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`. +- 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. + +Deploying rolling services with `--service` while leaving drain-first services +out prints a warning, since those keep running old code. + +```yaml +services: + worker: + labels: + deploy.role: app + deploy.strategy: drain-first + 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: 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 +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, 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. It must fail +closed: when `flow-deploy tag` can't tell, stop rather than fall through to +`:latest`. + +```sh +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 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. + +### 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 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 +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 @@ -113,6 +364,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 @@ -120,6 +378,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 639515a..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. 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. --- @@ -29,18 +29,30 @@ 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 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). 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 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:** ``` @@ -50,18 +62,43 @@ 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** (a failed step, a signal, or an unexpected error), the deploy reverts: -**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. +``` +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 =, + 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 +``` + +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). @@ -75,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. @@ -90,13 +129,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 +250,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 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 (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). + +**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 +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` (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`, 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 @@ -254,14 +314,31 @@ 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:-}" ]; 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 "$@" ``` +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` 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, 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.). **All examples in this spec that reference `` refer to whatever this wrapper resolves to.** @@ -274,6 +351,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 `. + --- ## 4. CLI Interface @@ -290,16 +369,19 @@ 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 | 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 (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 -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. +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. ### 4.2 `flow-deploy status` @@ -309,7 +391,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), 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` @@ -341,6 +423,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. @@ -351,6 +435,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 (images that disagree or are untagged, as in §2.8, 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 @@ -358,8 +463,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) @@ -367,7 +471,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 ────────────────────────────── @@ -435,11 +539,12 @@ 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. ```yaml name: Deploy @@ -447,6 +552,7 @@ name: Deploy on: push: branches: [main] + tags: ["v*"] env: REGISTRY: ghcr.io @@ -459,7 +565,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 @@ -469,12 +575,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: @@ -612,6 +720,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 | @@ -650,7 +759,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 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 c6fff92..e1a693d 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, 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 +# 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 image it was running, named by its release tag or commit SHA. ## 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,23 @@ 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 (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. + +**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/pyproject.toml b/pyproject.toml index 4bf753f..8af04c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,11 +41,17 @@ 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"] [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/cli.py b/src/flow_deploy/cli.py index 251ac69..6a01464 100644 --- a/src/flow_deploy/cli.py +++ b/src/flow_deploy/cli.py @@ -1,13 +1,14 @@ """Click entry point — all commands.""" import json +import re import sys import click 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 +32,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 +44,12 @@ 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})") + 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})") log.info("") for svc in all_services: @@ -57,6 +65,55 @@ 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)}. + """ + 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(compose_cmd) + except RuntimeError as e: + tag, how = None, str(e) + if tag is None: + click.echo(f"Error: can't tell which tag is deployed: {how}", err=True) + sys.exit(1) + return tag, how + + +@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: + 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})) + + @main.command(name="exec", context_settings={"ignore_unknown_options": True}) @click.argument("service") @click.argument("command", nargs=-1, type=click.UNPROCESSED) @@ -66,10 +123,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") @@ -83,7 +151,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) @@ -92,11 +160,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 d6be5a7..045a230 100644 --- a/src/flow_deploy/compose.py +++ b/src/flow_deploy/compose.py @@ -32,10 +32,25 @@ 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.""" - command = cmd or resolve_command() - result = process.run(command + ["config"]) +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. ``no_interpolate`` + leaves ${VARS} as written, so a project whose env isn't present (CI + discovery) still parses. + """ + command = (cmd or resolve_command()) + ["config"] + if no_interpolate: + command.append("--no-interpolate") + if env: + result = process.run(command, env=env) + else: + result = process.run(command) if result.returncode != 0: raise RuntimeError(f"compose config failed: {result.stderr}") return yaml.safe_load(result.stdout) 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/containers.py b/src/flow_deploy/containers.py index 5f305dc..747f772 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 @@ -9,15 +10,29 @@ 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. A status filter matches + stopped containers too (exited, created) without ``--all``. """ 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(): @@ -26,6 +41,42 @@ def get_containers_for_service(service: str, project: str = "") -> list[dict]: return containers +def other_projects_here(project: str, services: list[str]) -> set[str] | None: + """Other compose projects running any of ``services`` in this directory. + + 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} + # 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"}} {{.Label "com.docker.compose.service"}}', + ] + ) + if result.returncode != 0: + return None + 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} + + def identify_old_new(containers: list[dict], new_tag: str) -> tuple[dict | None, dict | None]: """Identify old and new containers by image tag. @@ -71,13 +122,72 @@ 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 +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 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 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 f1b1490..32c2b76 100644 --- a/src/flow_deploy/deploy.py +++ b/src/flow_deploy/deploy.py @@ -2,8 +2,129 @@ 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 +EXIT_LOCKED = 2 +EXIT_DEGRADED = 3 # failed, and something couldn't be put back + +# 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. +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 + + +@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 Previous: + """What an app service was running when the deploy started.""" + + svc: config.ServiceConfig + 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 # the git tag or SHA that brings image_id back + + +@dataclass +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 + 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 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 + + 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) + log.info("") + problems = [] + if self.previous_sha is not None and not git.restore(self.previous_sha): + problems.append("git restore failed") + 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( @@ -12,7 +133,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 @@ -23,92 +145,311 @@ 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 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 + + return _deploy_guarded(compose_cmd, tag, tag_provided, services_filter) - # 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 2 - # Register signal handlers for cleanup - _original_sigterm = signal.getsignal(signal.SIGTERM) - _original_sigint = signal.getsignal(signal.SIGINT) +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. + originals = {signum: signal.getsignal(signum) for signum in HANDLED_SIGNALS} - 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) + for signum in HANDLED_SIGNALS: + signal.signal(signum, _interrupt) - keep_lock = False + run = _Run(compose_cmd) + locked = False + code = EXIT_FAILED 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 1 + # 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 + 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") + code = run.revert(reason) + return code + 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. + if locked: + log.close_run(code) + lock.release() + for signum, handler in originals.items(): + signal.signal(signum, handler) - # 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 - app_services = _resolve_app_services(compose_dict, services_filter) - if app_services is None: - keep_lock = not git.restore(previous_sha) - return 1 +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), rendered with + # this deploy's tag so each image shows what will run. + try: + 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") + + 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) + + 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, [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"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." + ) + 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, 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 + # 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) -> 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. + for svc in reversed(drain_first): + 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. + 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 + 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; any failure reverts + # the whole deploy. + failures = [] + for svc in drain_first: + 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) + if result != SVC_OK: + failures.append(svc.name) + if failures: + return failed(f"{', '.join(failures)} failed to start") + + if run.whole_project: + deployed.write(tag, git.current_sha()) + 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" + ) - 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("") + elapsed = time.time() - start_time - project = compose_dict.get("name", "") - start_time = time.time() + log.info("") + log.info(f"HEAD detached at {tag}") + log.footer(f"complete ({elapsed:.1f}s)") + return EXIT_OK - for svc in app_services: - result = _deploy_service(svc, tag, compose_cmd, project=project) - if result != 0: - log.info("") - keep_lock = not git.restore(previous_sha) - log.footer("FAILED (deploy aborted)") - return 1 - elapsed = time.time() - start_time +def _warn_untagged_images(services: list[config.ServiceConfig], tag: str) -> None: + """Warn about app images that don't follow DEPLOY_TAG. - log.info("") - log.info(f"HEAD detached at {tag}") - log.footer(f"complete ({elapsed:.1f}s)") - finally: - if keep_lock: - log.error( - "Lock retained — git restore failed, manual intervention required. " - "Run: git checkout --detach && rm .git/deploy-lock" + 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}." ) - else: - lock.release() - signal.signal(signal.SIGTERM, _original_sigterm) - signal.signal(signal.SIGINT, _original_sigint) - return 0 + +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 service gets the DEPLOY_TAG that brings its running image back: see + _restore_tag. + """ + 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}" + ) + prev.restore_tag = _restore_tag(prev, run.previous_sha, tag) + run.previous[svc.name] = prev + return True + + +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. + + 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. + """ + 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 _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 _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( @@ -119,7 +460,16 @@ 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): + # 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 if not app_services: log.error("No app services to deploy") @@ -130,28 +480,323 @@ 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 _deploy_service( - svc: config.ServiceConfig, tag: str, compose_cmd: list[str], project: str = "" +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 _drain_service( + svc: config.ServiceConfig, + tag: str, + compose_cmd: list[str], + drained: list[str], + project: str = "", ) -> int: - """Deploy a single service. Returns 0 on success, 1 on failure.""" + """Pull the new image, then stop and remove the running containers. + + 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() + env = {"DEPLOY_TAG": tag} + if not _pull(svc, env, compose_cmd): + log.service_end() + return 1 + + # 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 + drained.append(svc.name) + 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)...") + # 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 = _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") + log.service_end() + return 1 + if not removed: + log.failure(f"could not remove {ctr_id[:7]}") + log.service_end() + return 1 + + log.success(f"{svc.name} drained ({time.time() - svc_start:.1f}s)") + log.service_end() + return 0 + + +def _start_service( + svc: config.ServiceConfig, + tag: str, + compose_cmd: list[str], + replicas: int = 1, + project: str = "", +) -> int: + """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} - # 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) + 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 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, + ) + # 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) + + 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)...") + 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 SVC_OK + + +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: + 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 _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). + + `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 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, 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 + ) + + +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 + 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 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, project) and ok + return ok + + +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. + """ + 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"pull failed: {result.stderr.strip()}") + log.failure(f"could not restore {svc.name}: {result.stderr.strip()}") + 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( + svc: config.ServiceConfig, + tag: str, + compose_cmd: list[str], + project: str = "", + pull: bool = True, +) -> int: + """Deploy a single service with a rolling cutover. + + ``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). + """ + log.service_start(svc.name) + svc_start = time.time() + + env = {"DEPLOY_TAG": tag} + + def end(code: int) -> int: log.service_end() - return 1 - log.step(f"pulled ({time.time() - pull_start:.1f}s)") + return code + + # 1. Pull + if pull and not _pull(svc, env, compose_cmd): + return end(SVC_FAILED) # 2. Scale to 2 log.step("starting new container...") @@ -161,9 +806,9 @@ def _deploy_service( 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()}") - log.service_end() - return 1 + return end(SVC_FAILED) # 3. Get containers, identify old vs new ctrs = containers.get_containers_for_service(svc.name, project=project) @@ -174,16 +819,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"] @@ -203,24 +844,36 @@ 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 = _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. + 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. 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 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 + # 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: + 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: @@ -236,13 +889,23 @@ 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( - ["up", "-d", "--no-deps", "--scale", f"{service_name}=1", service_name], +def _scale_back(service_name: str, env: dict, compose_cmd: list[str]) -> bool: + """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", "--no-recreate", "--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: @@ -251,7 +914,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 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}") + 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 +931,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/src/flow_deploy/deployed.py b/src/flow_deploy/deployed.py new file mode 100644 index 0000000..14dcaf0 --- /dev/null +++ b/src/flow_deploy/deployed.py @@ -0,0 +1,87 @@ +"""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 and len(tags.keys() - {"latest"}) == 1: + # 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)") + 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() + ) + 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..1d66c38 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: @@ -20,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/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 be464c5..059f73f 100644 --- a/src/flow_deploy/log.py +++ b/src/flow_deploy/log.py @@ -13,14 +13,105 @@ 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: - 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 +119,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 +143,19 @@ 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 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}", stream=sys.stderr if stdout_clean else None) + _write(f"[{_timestamp()}] WARNING: {msg}", stream=sys.stderr) + + 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/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/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/conftest.py b/tests/conftest.py index 6af7703..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.""" @@ -10,9 +16,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 +33,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/fake_host.py b/tests/fake_host.py new file mode 100644 index 0000000..b7a1ad7 --- /dev/null +++ b/tests/fake_host.py @@ -0,0 +1,330 @@ +"""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 + exit_code: int | None = None + + +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] = {} # 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.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] + 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", self.run_streaming) + 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 _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) + 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() + 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:]) + 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[: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): + if args[:1] == ["status"]: + 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"]: + 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") + # 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) + 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: # 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) + 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. + 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:]): + 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.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: + 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" + ctr.exit_code = 137 if ctr.service in self.ignores_sigterm else 0 + 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 new file mode 100644 index 0000000..8379ec4 --- /dev/null +++ b/tests/fixtures/rolling_master.json @@ -0,0 +1,2088 @@ +{ + "happy": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "web003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "web001" + ], + null + ], + [ + [ + "docker", + "rm", + "web001" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "worker004" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "worker002" + ], + null + ], + [ + [ + "docker", + "rm", + "worker002" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ] + ], + "lock_left": false + }, + "health_abort": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "web003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "web003" + ], + null + ], + [ + [ + "docker", + "rm", + "web003" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + null + ] + ], + "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", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "web003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "web001" + ], + null + ], + [ + [ + "docker", + "rm", + "web001" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "worker004" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "worker004" + ], + null + ], + [ + [ + "docker", + "rm", + "worker004" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + 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", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + 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", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + 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", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + null + ] + ], + "lock_left": false + }, + "unidentifiable": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + 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", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "web003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "web001" + ], + null + ], + [ + [ + "docker", + "rm", + "web001" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "worker004" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "worker002" + ], + null + ], + [ + [ + "docker", + "rm", + "worker002" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ] + ], + "lock_left": false + }, + "healthcheck_skip": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "web003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "web001" + ], + null + ], + [ + [ + "docker", + "rm", + "web001" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "worker002" + ], + null + ], + [ + [ + "docker", + "rm", + "worker002" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ] + ], + "lock_left": false + }, + "service_filter": { + "code": 0, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "worker003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "worker002" + ], + null + ], + [ + [ + "docker", + "rm", + "worker002" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ] + ], + "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": "prev123abc" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "prev123abc" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "web003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "web001" + ], + null + ], + [ + [ + "docker", + "rm", + "web001" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "prev123abc" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "prev123abc" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "prev123abc" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "worker004" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "worker002" + ], + null + ], + [ + [ + "docker", + "rm", + "worker002" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "prev123abc" + } + ] + ], + "lock_left": false + }, + "restore_fail": { + "code": 1, + "calls": [ + [ + [ + "git", + "status", + "--porcelain" + ], + null + ], + [ + [ + "git", + "fetch", + "origin" + ], + null + ], + [ + [ + "git", + "rev-parse", + "HEAD" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + 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", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "docker", + "compose", + "pull", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "web=2", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=web", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "web003" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "web001" + ], + null + ], + [ + [ + "docker", + "rm", + "web001" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "web=1", + "web" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "pull", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--no-recreate", + "--scale", + "worker=2", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ], + [ + [ + "docker", + "ps", + "--filter", + "label=com.docker.compose.service=worker", + "--filter", + "label=com.docker.compose.project=proj", + "--filter", + "status=running", + "--format", + "{{json .}}" + ], + null + ], + [ + [ + "docker", + "inspect", + "--format", + "{{.State.Health.Status}}", + "worker005" + ], + null + ], + [ + [ + "docker", + "stop", + "--time", + "30", + "worker002" + ], + null + ], + [ + [ + "docker", + "rm", + "worker002" + ], + null + ], + [ + [ + "docker", + "compose", + "up", + "-d", + "--no-deps", + "--scale", + "worker=1", + "worker" + ], + { + "DEPLOY_TAG": "v2" + } + ] + ], + "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", + "v2" + ], + null + ], + [ + [ + "docker", + "compose", + "config" + ], + null + ], + [ + [ + "git", + "checkout", + "--detach", + "prev123abc" + ], + null + ] + ], + "lock_left": false + } +} 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 new file mode 100644 index 0000000..4c9d389 --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,370 @@ +"""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]) + # :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) + + +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:-latest}", + "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, 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 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, 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 + 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, 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", + "-aq", + "--filter", + f"label=com.docker.compose.project={self.project}", + ] + ).stdout.split() + result = {} + 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 { + 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 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() + + 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..be41034 --- /dev/null +++ b/tests/integration/test_deploys.py @@ -0,0 +1,554 @@ +"""flow-deploy against real containers: drain-first, rolling, and every revert path.""" + +import json +import os +import time + +import pytest + +from tests.integration.conftest import SIGNALS, run, 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, previous="v1"): + assert code == expected_code, out + assert stack.running() == expected_running, out + assert stack.head() == stack.sha(previous), "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" + + +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): + """Everything goes back to v1: web (shipped) and the scheduler (started + healthy) too, and the worker at its replica count.""" + stack.commit("v1", standard()) + stack.commit("v3", standard(worker=BAD_WORKER)) + stack.up("v1", scale={"worker": 2}) + + result = stack.deploy("v3") + + assert_reverted( + stack, + {"web": ["v1"], "scheduler": ["v1"], "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 + # 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( + ("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_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}}" + ) + 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") == [f"{stack.registry}/stub:{v1}"] + + +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"] + + +# --------------------------------------------------------------------------- +# 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 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_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}) + 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") + 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} 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) + + +# --------------------------------------------------------------------------- +# What an operator sees: kills, 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_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 + + +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, 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 + status = stack.flow("status") + assert status.returncode == 0, status.stderr + 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" + 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 new file mode 100644 index 0000000..061697f --- /dev/null +++ b/tests/rolling_scenarios.py @@ -0,0 +1,125 @@ +"""Rolling-only deploy scenarios on a FakeHost, shared by the parity test and its recorder. + +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 + +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). +""" + +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"}}, + } +} + +V1 = {"web": ["v1"], "worker": ["v1"]} + + +def _skip_worker_health(config): + labels = config["services"]["worker"]["labels"] + labels["deploy.healthcheck.skip"] = "true" + return config + + +def _twins(host): + """Old and new containers on the deploy tag with the same CreatedAt: unidentifiable.""" + host.same_created = True + + +# name -> (running, setup(host) or None, deploy kwargs, config transform or None) +SCENARIOS = { + "happy": (V1, None, {}, None), + "health_abort": (V1, lambda h: h.unhealthy_services.add(("web", "v2")), {}, None), + "second_service_health_abort": ( + V1, + lambda h: h.unhealthy_services.add(("worker", "v2")), + {}, + None, + ), + "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, + ), + "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.""" + 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) + host.wrapper_requires_tag = False # master's config call didn't pass DEPLOY_TAG + 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) + code = deploy_module.deploy(cmd=COMPOSE_CMD, **{"tag": "v2", **kwargs}) + return { + "code": code, + "calls": [[args, env] for args, env in zip(host.calls, host.envs)], + "lock_left": os.path.exists(".git/deploy-lock"), + } + + +if __name__ == "__main__": + 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 + + 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_cli.py b/tests/test_cli.py index b1c496c..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") @@ -145,7 +149,28 @@ 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. + + +@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(): diff --git a/tests/test_compose.py b/tests/test_compose.py index 0db4319..2164a72 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: @@ -54,3 +62,9 @@ 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"] diff --git a/tests/test_containers.py b/tests/test_containers.py index a7340d0..3735100 100644 --- a/tests/test_containers.py +++ b/tests/test_containers.py @@ -4,9 +4,15 @@ from flow_deploy import process from flow_deploy.containers import ( + exit_code, get_container_health, get_containers_for_service, identify_old_new, + image_ids, + image_repo, + image_tag, + local_image_id, + other_projects_here, remove_container, stop_container, ) @@ -61,6 +67,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"} @@ -90,6 +117,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 @@ -100,3 +133,120 @@ 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_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)) + 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 + + +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 web\n", "")) + assert other_projects_here("proj", ["web"]) == {"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", ["web"]) == 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", ["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 diff --git a/tests/test_deploy.py b/tests/test_deploy.py index 229721b..09fc372 100644 --- a/tests/test_deploy.py +++ b/tests/test_deploy.py @@ -1,451 +1,416 @@ -"""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_restore_failure_retains_lock(mock_process, monkeypatch, tmp_path, capsys): - """If git restore fails after a deploy failure, the lock should be retained.""" - _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 == 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() - - -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_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(host, tmp_path, capsys): + """A failed git restore exits 3 but still releases the lock: no manual cleanup.""" + 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(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 by the release tag it ran. + assert host.running_images() == before + assert host.running() == {"web": ["v1"], "worker": ["v1"]} + assert host.sha == "prev123abc" + 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): + 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_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): + """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 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" + + +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_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() + 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_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_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): + 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_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) + 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) + 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_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] + 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): + 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 new file mode 100644 index 0000000..c00f512 --- /dev/null +++ b/tests/test_deploy_failures.py @@ -0,0 +1,251 @@ +"""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, _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 +# --------------------------------------------------------------------------- + + +@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 + + +@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)) + 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") + # 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") + + +def test_a_second_signal_during_a_held_drain_is_also_held(drain_host): + def two(): + send(signal.SIGINT)() + send(signal.SIGTERM)() + + 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="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + assert seen == [signal.SIG_IGN] + + +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) + host = FakeHost(ROLLING).install(monkeypatch) + released = [] + monkeypatch.setattr(deploy_mod.lock, "acquire", send(signal.SIGTERM)) + monkeypatch.setattr(deploy_mod.lock, "release", lambda: released.append(True)) + 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(rolling_host, monkeypatch): + 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) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == 0 + assert during_release == [signal.SIG_IGN] + assert signal.getsignal(signal.SIGHUP) is original + + +def test_unexpected_exception_reverts(drain_host, monkeypatch, capsys): + def boom(*args, **kwargs): + raise KeyError("Image") + + monkeypatch.setattr(deploy_mod, "_deploy_service", boom) + assert deploy(tag="v2", cmd=COMPOSE_CMD) == EXIT_FAILED + assert "unexpected error: KeyError('Image'); reverting" in capsys.readouterr().err + assert drain_host.running_images() == v1(drain_host, "web", "scheduler", "worker") + + +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="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") + + +# --------------------------------------------------------------------------- +# Cleanup failures turn a clean failure (1) into a degraded one (3) +# --------------------------------------------------------------------------- + + +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 web003" in captured.out + assert "cleanup failed for web" in captured.err + + +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 web001 did not complete" in captured.out + assert "::error::" not in captured.out + + +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_fails, expected", [(False, 1), (True, 3)]) +def test_rolling_unidentifiable_containers_scale_back( + monkeypatch, tmp_path, scale_back_fails, 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(drain_host): + """Couldn't see what started, so couldn't remove it: exit 3, not a clean revert.""" + 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 + + +@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 + + +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"]} + + +# --------------------------------------------------------------------------- +# Dry run and helpers +# --------------------------------------------------------------------------- + + +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_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): + 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_deployed.py b/tests/test_deployed.py new file mode 100644 index 0000000..d27c2c1 --- /dev/null +++ b/tests/test_deployed.py @@ -0,0 +1,231 @@ +"""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_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 + 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", "abc123sha") + host.add("worker", "latest") + 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_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 + + +# --------------------------------------------------------------------------- +# 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 new file mode 100644 index 0000000..e90843b --- /dev/null +++ b/tests/test_drain_first.py @@ -0,0 +1,258 @@ +"""deploy.strategy=drain-first on a FakeHost: ordering, replicas, and full reverts.""" + +import pytest + +from flow_deploy import config +from flow_deploy.deploy import deploy +from tests.fake_host import COMPOSE_CMD, FakeHost +from tests.helpers import 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") + ) + # 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) + 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() + + +@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_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_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_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_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 + + assert host.running_images() == before + assert host.sha == "prev123abc" + 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") == "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]) + assert rollback < restore + + +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_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_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 host.running_images() == before + assert host.running()["worker"] == ["prev123abc"] + + +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="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 ( + 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_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_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 diff --git a/tests/test_git.py b/tests/test_git.py index f8c183e..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, ) @@ -33,6 +34,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): @@ -121,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_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..2987929 100644 --- a/tests/test_lock.py +++ b/tests/test_lock.py @@ -53,3 +53,41 @@ 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 + + +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_log.py b/tests/test_log.py index 3e1b32b..f0e7b52 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -105,9 +105,64 @@ 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 error("something broke") err = capsys.readouterr().err 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 + + error("boom") + captured = capsys.readouterr() + assert "::error::boom" in captured.out + assert "ERROR: boom" in captured.err diff --git a/tests/test_operability.py b/tests/test_operability.py new file mode 100644 index 0000000..ee56eb2 --- /dev/null +++ b/tests/test_operability.py @@ -0,0 +1,343 @@ +"""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 + +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 + + +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") + 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"]]) +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 +# --------------------------------------------------------------------------- + + +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" + + +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 +# --------------------------------------------------------------------------- + + +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_process.py b/tests/test_process.py index b45063b..aefc213 100644 --- a/tests/test_process.py +++ b/tests/test_process.py @@ -40,3 +40,16 @@ def test_run_streaming_returns_exit_code(): def test_run_streaming_nonzero(): code = run_streaming(["false"]) 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 new file mode 100644 index 0000000..14601e3 --- /dev/null +++ b/tests/test_rolling_parity.py @@ -0,0 +1,133 @@ +"""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 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 + +from flow_deploy import deploy as deploy_mod +from flow_deploy import process +from tests.rolling_scenarios import SCENARIOS, record + +MASTER = json.loads((Path(__file__).parent / "fixtures" / "rolling_master.json").read_text()) + +# 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. + "restore_fail": {"code": 3, "lock_left": False}, +} + + +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, 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. + """ + 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[:3] == ["docker", "image", "inspect"] + or args[:3] == ["git", "rev-parse", "--verify"] + or args[:4] == ["docker", "inspect", "--format", "{{.State.ExitCode}}"] + ) + + +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 == ["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): + # 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) + + 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": + # 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"] == "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" + + expected = {"code": MASTER[name]["code"], "lock_left": MASTER[name]["lock_left"]} + expected.update(DELIBERATE_OUTCOMES.get(name, {})) + assert observed["code"] == expected["code"] + assert observed["lock_left"] == expected["lock_left"] 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