From 567e9cca7c20046f77a66b57c849cdd7cd34fc15 Mon Sep 17 00:00:00 2001 From: Dragonish Date: Wed, 25 Nov 2026 17:03:54 +0000 Subject: [PATCH] feat(docker): add opt-in boot and shutdown units for hosts that run Docker with live-restore docker_start_missed installs a boot unit that starts the containers dockerd's restore pass skipped after a reboot of the whole host. docker_stop_at_shutdown installs a unit that ends container processes at shutdown while the network and NFS shares are still up, so a container holding an NFS mount no longer stalls the shutdown. Both default to false and do nothing without /usr/bin/docker. Refs #369 Assisted-by: Claude Code --- .../fragments/docker-boot-shutdown-units.yml | 11 + roles/docker/README.md | 26 +- roles/docker/defaults/main.yml | 16 ++ roles/docker/files/docker-start-missed | 176 ++++++++++++ roles/docker/files/docker-stop-at-shutdown | 44 +++ roles/docker/meta/argument_specs.yml | 40 +++ roles/docker/molecule/default/converge.yml | 26 ++ .../molecule/default/files/build-stub-repo.sh | 7 +- roles/docker/molecule/default/verify.yml | 119 +++++++- roles/docker/tasks/main.yml | 5 + roles/docker/tasks/remove.yml | 14 + roles/docker/tasks/unit_absent.yml | 35 +++ roles/docker/tasks/units.yml | 123 ++++++++ roles/docker/tasks/validate.yml | 10 + tests/sanity/ignore-common.txt | 2 + tests/scripts/test_docker_files.py | 269 ++++++++++++++++++ 16 files changed, 917 insertions(+), 6 deletions(-) create mode 100644 changelogs/fragments/docker-boot-shutdown-units.yml create mode 100755 roles/docker/files/docker-start-missed create mode 100755 roles/docker/files/docker-stop-at-shutdown create mode 100644 roles/docker/tasks/unit_absent.yml create mode 100644 roles/docker/tasks/units.yml create mode 100644 tests/scripts/test_docker_files.py diff --git a/changelogs/fragments/docker-boot-shutdown-units.yml b/changelogs/fragments/docker-boot-shutdown-units.yml new file mode 100644 index 0000000..b51ea6f --- /dev/null +++ b/changelogs/fragments/docker-boot-shutdown-units.yml @@ -0,0 +1,11 @@ +--- +minor_changes: + - >- + docker - Add the opt-in inputs ``docker_start_missed`` and ``docker_stop_at_shutdown`` (both default ``false``, so a host that does not + set them is unchanged) for a host that runs Docker with ``live-restore``. ``docker_start_missed`` installs a boot unit that starts the + containers dockerd's restore pass skipped after a reboot of the whole host (exited with code 255 during this boot, restart policy + ``unless-stopped`` or ``always``; one stopped on purpose stays stopped), with ``docker_start_missed_settle_seconds`` (default 30). + ``docker_stop_at_shutdown`` installs a unit that ends every container process at shutdown while the network and NFS shares are still up + (SIGTERM, then SIGKILL after ``docker_stop_at_shutdown_timeout`` seconds, default 30, never ``docker stop`` or ``docker kill``), so that + a container holding an NFS mount does not stall the shutdown while the network is already down. Setting an input back to ``false``, or ``docker_remove``, + removes its unit and script. Both units do nothing when ``/usr/bin/docker`` does not exist. diff --git a/roles/docker/README.md b/roles/docker/README.md index f2be8a2..182ca06 100644 --- a/roles/docker/README.md +++ b/roles/docker/README.md @@ -26,16 +26,35 @@ Ubuntu. The key and repository URLs point at `download.docker.com/linux/ubuntu`, | `docker_gpg_url` | `https://download.docker.com/linux/ubuntu/gpg` | no | Key URL. | | `docker_repo_base_url` | `https://download.docker.com/linux/ubuntu` | no | Repository base URL. | | `docker_apt_arch` | derived from the host | no | Architecture in the APT source. Empty derives it (`x86_64` gives `amd64`, `aarch64` gives `arm64`); another architecture fails until this is set. A value set here is always used; lowercase letters and digits only. | +| `docker_start_missed` | `false` | no | Install a boot unit that starts the containers Docker skipped after a reboot (see [Boot and shutdown units](#boot-and-shutdown-units)). | +| `docker_start_missed_settle_seconds` | `30` | no | Seconds the boot unit waits after Docker answers, so dockerd's own restarts finish first. | +| `docker_stop_at_shutdown` | `false` | no | Install a unit that ends container processes at shutdown while the network and NFS are still up. | +| `docker_stop_at_shutdown_timeout` | `30` | no | Seconds the shutdown unit waits after SIGTERM before it sends SIGKILL (at least 1). | | `docker_service` | `docker` | no | systemd unit name. | | `docker_group` | `docker` | no | Group for `docker_users`. | | `docker_users` | `[]` | no | Users added to the group. | ## Tags -`docker` (everything), `install`, `update`, `remove`, `configure` (group membership). The tasks in `remove.yml` carry `docker` and `remove`. +`docker` (everything), `install`, `update`, `remove`, `configure` (group membership and the two units). The tasks in `remove.yml` carry `docker` and `remove`. Update (`docker_update: true`) and removal (`docker_remove: true`) are opt-in: run them on a host that is safe to change. +## Boot and shutdown units + +Both are opt-in, for a host that runs Docker with `live-restore` (a `docker.service` restart then leaves containers running). They are part of this role, so they exist only on a host you apply it to, and each does nothing when `/usr/bin/docker` does not exist. + +- **`docker_start_missed`**: a reboot of the whole host kills the containers, and dockerd's restore pass at the next boot sometimes skips one without trying (`RestartCount` stays 0; Docker reports exit code 255). The unit `docker-start-missed.service` runs once per boot after Docker, waits `docker_start_missed_settle_seconds`, and starts a container only if its restart policy is `unless-stopped` or `always`, it exited with code 255, and it finished after this boot began. A container stopped on purpose (exit code 0, 137 or 143) stays stopped. It is `Type=simple`, so it never delays or fails the boot. +- **`docker_stop_at_shutdown`**: with `live-restore` dockerd does not stop containers at host shutdown, and systemd-shutdown signals them after the network is gone. A container that holds an NFS mount then blocks in the kernel's final unmount until the SIGKILL timer. The unit `docker-stop-at-shutdown.service` is started by the role; its stop action runs after Docker has stopped and before the network and remote file systems, sends SIGTERM to every container process, waits up to `docker_stop_at_shutdown_timeout` seconds, then SIGKILL, and logs to the journal under the tag `docker-stop-at-shutdown`. It never calls `docker stop` or `docker kill`, which would set the manually-stopped marker, so a container with `unless-stopped` starts again at the next boot. Check that `systemctl is-active docker-stop-at-shutdown` says `active`, because the stop action runs only for an active unit. + +Setting an input back to `false` removes that unit's file and script. The role never stops a running shutdown unit, because stopping it runs its stop action and ends every container; it takes effect as systemd reloads and reboots. + +Things to know before you switch `docker_stop_at_shutdown` on: + +- The unit is ordered before `docker.service` and after `network-online.target` and `remote-fs.target`. That ordering applies at boot as well: Docker starts only after the network and the remote file systems are up, so an unreachable NFS server delays Docker until its mount gives up. +- The script reads the layout of the systemd cgroup driver on cgroup v2 (`/sys/fs/cgroup/system.slice/docker-.scope`, and the cgroups below it). On a host that lays containers out differently it finds nothing, logs "no container scopes" and changes nothing, so check the journal (`journalctl -t docker-stop-at-shutdown -b -1`) after the first reboot. +- `docker-start-missed --dry-run` lists what the boot unit would start; add `--settle 0` to skip the wait. + ## Example play ```yaml @@ -56,10 +75,11 @@ What it shows, with the role's tasks running unchanged: - The source line has the architecture, the `signed-by` keyring and `ansible_distribution_release`. - The packages are installed from that repository, the unit is enabled and active, and `docker_users` join `docker_group`. - `docker_remove` with `docker_remove_data` removes the source line, the keyring, the packages, the unit and `/var/lib/docker`. -- The argument check refuses a mapping for `docker_users` and a non-boolean `docker_remove`. +- Both units are installed, enabled, ordered against `docker.service` as stated, the shutdown unit is active, a unit is removed when its input is `false`, and `docker_remove` removes both. +- The argument check refuses a mapping for `docker_users`, a non-boolean `docker_remove` and a `docker_stop_at_shutdown_timeout` of 0. - A second run changes nothing (molecule's idempotence check). -What it does not show: that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for the `curl` the role installs. These gaps are a known residual risk of the role. +What it does not show: what the units do at a real boot or shutdown (the container has no dockerd, no NFS shares and no reboot; the selection logic of `docker-start-missed` is unit-tested in `tests/scripts/test_docker_files.py`), that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for the `curl` the role installs. These gaps are a known residual risk of the role. ## Notes diff --git a/roles/docker/defaults/main.yml b/roles/docker/defaults/main.yml index 0c7acee..152a93a 100644 --- a/roles/docker/defaults/main.yml +++ b/roles/docker/defaults/main.yml @@ -30,3 +30,19 @@ docker_users: [] # Docker manipulates iptables directly for any published container port # (`-p`), bypassing UFW rules entirely - so the role owns no UFW rule and does # not call the ufw role. + +# With live-restore Docker leaves containers running when dockerd stops, but a reboot of the whole host kills them, and dockerd's restore +# pass at the next boot sometimes skips one without trying. When true, a boot unit starts the containers that Docker left down: only +# those exited with code 255 during this boot whose restart policy is unless-stopped or always, so one stopped on purpose stays stopped. +# Off by default; set it on a host that runs Docker with live-restore. +docker_start_missed: false +# Seconds to wait after Docker answers, so dockerd's own restarts finish first. +docker_start_missed_settle_seconds: 30 + +# With live-restore dockerd does not stop containers at host shutdown, and systemd-shutdown signals them only after the network is gone. A +# container that holds an NFS mount then blocks in the kernel's final unmount until the SIGKILL timer, and the host takes minutes to stop. +# When true, a shutdown unit sends SIGTERM to every container process while the network and NFS are still up, waits up to +# docker_stop_at_shutdown_timeout seconds, then SIGKILL. It never uses `docker stop`, so the manually-stopped marker is not set. +# Off by default; set it on a host whose containers mount NFS shares. +docker_stop_at_shutdown: false +docker_stop_at_shutdown_timeout: 30 diff --git a/roles/docker/files/docker-start-missed b/roles/docker/files/docker-start-missed new file mode 100755 index 0000000..b25a616 --- /dev/null +++ b/roles/docker/files/docker-start-missed @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Start the containers that Docker skipped when the host booted. + +With live-restore, dockerd leaves containers running when it stops, but a reboot of the whole host kills them. At the next boot dockerd's +restore pass sometimes skips one without trying to restart it (RestartCount stays 0, no error) although its restart policy is +unless-stopped or always. Docker then reports the container as exited with code 255, the code it uses when the process vanished without +Docker seeing it exit. + +This runs once per boot, after docker.service, waits for the normal restarts to settle and starts what is still down. It starts a +container only when ALL of these hold, so a container someone stopped on purpose stays stopped: + - the restart policy is unless-stopped or always; + - it is exited with code 255 (a manual `docker stop` gives 0, 137 or 143); + - it finished after this boot began (it died with this reboot, not earlier). +Exit 0: nothing to do, or everything started (--dry-run only reports). 1: a start failed or the container did not stay up. 2: Docker never +answered, or its output could not be read. The boot time comes from /proc/uptime: in an LXC that needs lxcfs, otherwise it is the host's +and the window only gets wider, which the exit-code and policy tests still bound. +A container whose data cannot be read fails the run (exit 2) instead of being guessed at. Standard library only: it runs on the managed host. +""" + +import argparse +import json +import subprocess +import sys +import time +from datetime import datetime, timezone + +POLICIES = ("unless-stopped", "always") +KILLED_EXIT_CODE = 255 +BOOT_TOLERANCE_SECONDS = 5 + + +def parse_time(text): + """Docker's RFC 3339 timestamps carry nanoseconds, which datetime cannot read: cut to microseconds.""" + head, _, rest = text.rstrip("Z").partition(".") + frac = "".join(ch for ch in rest if ch.isdigit())[:6].ljust(6, "0") + return datetime.strptime(f"{head}.{frac}", "%Y-%m-%dT%H:%M:%S.%f").replace( + tzinfo=timezone.utc # noqa: UP017 (datetime.UTC needs Python 3.11; Ubuntu 22.04 has 3.10) + ) + + +def missed(containers, boot_time): + """Names of the containers (docker inspect objects) that died with this reboot and should be running.""" + names = [] + for c in containers: + state, policy = ( + c.get("State", {}), + c.get("HostConfig", {}).get("RestartPolicy", {}).get("Name", ""), + ) + if ( + state.get("Running") + or state.get("Status") == "restarting" + or policy not in POLICIES + ): + continue + if state.get("ExitCode") != KILLED_EXIT_CODE: + continue + finished = state.get("FinishedAt", "") + if not finished or finished.startswith("0001-"): + continue + if ( + parse_time(finished) - boot_time + ).total_seconds() >= -BOOT_TOLERANCE_SECONDS: + names.append(c["Name"].lstrip("/")) + return sorted(names) + + +def boot_time_now(uptime_path="/proc/uptime"): + with open(uptime_path, encoding="ascii") as handle: + up = float(handle.read().split()[0]) + return datetime.fromtimestamp(time.time() - up, tz=timezone.utc) # noqa: UP017 (see parse_time) + + +def docker(*args): + return subprocess.run( + ["docker", *args], capture_output=True, text=True, check=False + ) + + +def wait_for_docker(attempts, delay, run=docker, sleep=time.sleep): + for _ in range(attempts): + if run("info").returncode == 0: + return True + sleep(delay) + return False + + +def find_missed(run, boot_time, log): + """The names to start, or None when Docker's answer could not be read (already logged).""" + listing = run("ps", "-aq", "--filter", "status=exited") + if listing.returncode != 0: + log(f"docker ps failed: {listing.stderr.strip()}") + return None + ids = listing.stdout.split() + try: + inspected = [] + if ids: + inspection = run("inspect", *ids) + if inspection.returncode != 0 and not inspection.stdout.strip(): + log(f"docker inspect failed: {inspection.stderr.strip()}") + return None + inspected = json.loads( + inspection.stdout + ) # a container removed in between is simply missing from the list + return missed(inspected, boot_time) + except ( + ValueError, + KeyError, + TypeError, + ) as exc: # not JSON, or a timestamp or field Docker formats differently than expected + log(f"could not read the container list: {exc!r}") + return None + + +def start_all(names, run, sleep, log): + """Start each container, then check after a few seconds that it stayed up. Returns the names that failed.""" + failed = [] + for name in names: + result = run("start", name) + if result.returncode != 0: + log(f"could not start {name}: {result.stderr.strip()}") + failed.append(name) + else: + log(f"started {name}, which docker skipped at boot") + sleep(5) + for name in names: + if ( + name not in failed + and run("inspect", "-f", "{{.State.Running}}", name).stdout.strip() + != "true" + ): + log(f"{name} did not stay up") + failed.append(name) + return failed + + +def run_once( + settle, run=docker, sleep=time.sleep, boot_time=None, log=print, dry_run=False +): + boot_time = boot_time or boot_time_now() + if not wait_for_docker(24, 5, run, sleep): + log("docker did not answer within 2 minutes") + return 2 + sleep( + settle + ) # dockerd's own restart pass runs in the first seconds: let it finish before judging what is still down + todo = find_missed(run, boot_time, log) + if todo is None: + return 2 + if not todo: + log("no container to start") + return 0 + if dry_run: + log("would start: " + ", ".join(todo)) + return 0 + return 1 if start_all(todo, run, sleep, log) else 0 + + +def main(argv): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--settle", + type=int, + default=30, + help="seconds to wait after docker answers, for dockerd's own restarts", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="say what would be started and start nothing", + ) + args = parser.parse_args(argv) + return run_once(args.settle, dry_run=args.dry_run) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/roles/docker/files/docker-stop-at-shutdown b/roles/docker/files/docker-stop-at-shutdown new file mode 100755 index 0000000..6ddd6fb --- /dev/null +++ b/roles/docker/files/docker-stop-at-shutdown @@ -0,0 +1,44 @@ +#!/bin/bash +# End every container's processes while the network and the NFS shares are still up. +# +# With live-restore dockerd does not stop containers at host shutdown, and systemd-shutdown then signals them only after the network is +# gone. A container that holds an NFS mount blocks in the kernel's final unmount of it (a request to a server it can no longer reach) +# until the SIGKILL timer, which makes the host take minutes to stop. +# +# Run by the unit's ExecStop, which systemd orders after docker.service has stopped (so no restart policy interferes) and before the +# network and remote-fs targets. SIGTERM to every process of every container, wait, then SIGKILL what is left. It never uses +# `docker stop` or `docker kill`: both set the manually-stopped marker, and a container with restart policy unless-stopped would then not +# start again at the next boot. With dockerd down the containers simply exit and their policy restarts them at boot. +# It reads the systemd cgroup driver's layout (cgroup v2, /sys/fs/cgroup/system.slice/docker-.scope). On a host that lays containers out +# differently it finds nothing, says so in the journal and changes nothing. +set -u +shopt -s nullglob + +timeout="${DOCKER_STOP_TIMEOUT:-30}" +scopes=(/sys/fs/cgroup/system.slice/docker-*.scope) + +if [ "${#scopes[@]}" -eq 0 ]; then + logger -t docker-stop-at-shutdown "no container scopes, nothing to do" + exit 0 +fi + +# Every process of every scope, including those in child cgroups. Only real PIDs: a process this namespace cannot see is listed as 0, +# and `kill 0` would signal our own process group. +pids() { find "${scopes[@]}" -name cgroup.procs -exec cat {} + 2> /dev/null | grep -E '^[1-9][0-9]*$'; } + +logger -t docker-stop-at-shutdown "SIGTERM to $(pids | wc -l) processes in ${#scopes[@]} container scopes (wait up to ${timeout}s)" +pids | xargs -r kill -TERM 2> /dev/null + +deadline=$((SECONDS + timeout)) +while [ "$SECONDS" -lt "$deadline" ] && [ -n "$(pids)" ]; do + sleep 0.25 +done + +left=$(pids | wc -l) +if [ "$left" -gt 0 ]; then + logger -t docker-stop-at-shutdown "$left processes still there after ${timeout}s: SIGKILL" + pids | xargs -r kill -KILL 2> /dev/null + sleep 1 +fi +logger -t docker-stop-at-shutdown "done after ${SECONDS}s, processes left: $(pids | wc -l)" +exit 0 diff --git a/roles/docker/meta/argument_specs.yml b/roles/docker/meta/argument_specs.yml index d9b567c..d958f1c 100644 --- a/roles/docker/meta/argument_specs.yml +++ b/roles/docker/meta/argument_specs.yml @@ -62,6 +62,46 @@ argument_specs: Architecture written into the APT source. Empty (the default) derives it from the host: C(x86_64) gives C(amd64), C(aarch64) gives C(arm64). Any other host architecture fails the play, so set this to the name Docker publishes for it. Lowercase letters and digits only. A value set here is always used. + docker_start_missed: + type: bool + default: false + description: + - >- + Installs C(/usr/local/sbin/docker-start-missed) and the unit C(docker-start-missed.service). After each boot the unit starts the + containers that Docker left down: exited with code 255 during this boot, with restart policy C(unless-stopped) or C(always). A + container stopped on purpose stays stopped. Setting it back to false removes the unit and the script. + - >- + Meant for a host that runs Docker with C(live-restore), where dockerd's restore pass can skip a container after a reboot of the + whole host. The unit does nothing when C(/usr/bin/docker) does not exist. + docker_start_missed_settle_seconds: + type: int + default: 30 + description: + - Seconds the unit waits after Docker answers, so dockerd's own restarts finish before it judges what is still down. At least 0. + docker_stop_at_shutdown: + type: bool + default: false + description: + - >- + Installs C(/usr/local/sbin/docker-stop-at-shutdown) and the unit C(docker-stop-at-shutdown.service), started by the role, whose stop + action runs at host shutdown after Docker has stopped and before the network and remote file systems. It sends SIGTERM to every + container process, waits up to C(docker_stop_at_shutdown_timeout) seconds, then SIGKILL. It never uses C(docker stop) or + C(docker kill), which would set the manually-stopped marker. Setting it back to false removes the unit and the script. The role + never stops the running unit, because stopping it runs its stop action and ends every container. + - >- + The unit is ordered before C(docker.service) and after C(network-online.target) and C(remote-fs.target), and that ordering + also applies at boot: Docker then starts only after the network and the remote file systems are up. The script reads the + layout of the systemd cgroup driver on cgroup v2 (C(/sys/fs/cgroup/system.slice/docker-.scope)); on a host that lays + containers out differently it finds nothing, says so in the journal and changes nothing. + - >- + Meant for a host that runs Docker with C(live-restore) and whose containers mount NFS shares: without it a container holding + a mount blocks the shutdown in the kernel's final unmount once the network is gone. The unit does nothing when + C(/usr/bin/docker) does not exist. + docker_stop_at_shutdown_timeout: + type: int + default: 30 + description: + - Seconds the unit waits for container processes to end after SIGTERM before it sends SIGKILL. At least 1. docker_service: type: str default: docker diff --git a/roles/docker/molecule/default/converge.yml b/roles/docker/molecule/default/converge.yml index e022faa..ae29515 100644 --- a/roles/docker/molecule/default/converge.yml +++ b/roles/docker/molecule/default/converge.yml @@ -9,6 +9,9 @@ docker_gpg_url: file:///srv/docker-stub-repo/docker.asc docker_repo_base_url: file:///srv/docker-stub-repo docker_users: [moleculeuser] + docker_start_missed: true + docker_stop_at_shutdown: true + docker_stop_at_shutdown_timeout: 20 roles: - role: mortis.kamino.docker @@ -83,3 +86,26 @@ - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" - "'docker_apt_arch' in ansible_failed_result.msg | default('')" quiet: true + +# The unit timings are checked before anything changes. +- name: A docker_stop_at_shutdown_timeout of 0 is refused + hosts: all + gather_facts: false + vars: + docker_stop_at_shutdown_timeout: 0 + tasks: + - name: Apply the role with a timeout of 0 + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.docker + - name: Fail when the timeout was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: + - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" + - "'docker_stop_at_shutdown_timeout' in ansible_failed_result.msg | default('')" + quiet: true diff --git a/roles/docker/molecule/default/files/build-stub-repo.sh b/roles/docker/molecule/default/files/build-stub-repo.sh index 8abc112..bc90086 100755 --- a/roles/docker/molecule/default/files/build-stub-repo.sh +++ b/roles/docker/molecule/default/files/build-stub-repo.sh @@ -5,7 +5,7 @@ # build-stub-repo.sh # # The repository holds empty stand-ins for docker-ce, docker-ce-cli and containerd.io (the -# default docker_packages). docker-ce ships a stub docker.service and a postinst that creates +# default docker_packages). docker-ce ships a stub docker.service, a stub /usr/bin/docker and a postinst that creates # the docker group, as the real package does. The Release file is signed with a throwaway key # generated here; the matching public key is exported to /docker.asc, which is what # the role fetches as its keyring. The secret key stays in and is never installed. @@ -32,7 +32,10 @@ Description: stand-in for $name in the docker role's molecule scenario Empty package. It installs nothing from Docker. CONTROL if [ "$name" = docker-ce ]; then - mkdir -p "$tree/usr/lib/systemd/system" + mkdir -p "$tree/usr/lib/systemd/system" "$tree/usr/bin" + # The units the role installs only run where /usr/bin/docker exists; nothing here runs it. + printf '#!/bin/sh\nexit 1\n' > "$tree/usr/bin/docker" + chmod 0755 "$tree/usr/bin/docker" cat > "$tree/usr/lib/systemd/system/docker.service" <<'UNIT' [Unit] Description=Stand-in for the Docker Engine (molecule) diff --git a/roles/docker/molecule/default/verify.yml b/roles/docker/molecule/default/verify.yml index 2fb7020..70c5d4e 100644 --- a/roles/docker/molecule/default/verify.yml +++ b/roles/docker/molecule/default/verify.yml @@ -90,6 +90,119 @@ that: "'docker' in docker_verify_groups.stdout.split()" quiet: true +# The two units: installed, enabled, ordered as the role promises, and the shutdown unit running (its stop action runs only for an +# active unit). Their behaviour at a real boot or shutdown cannot be shown here: the container has no dockerd, no NFS and no reboot, and the +# shutdown script is not run because the container shares the runner's cgroup tree. +- name: Verify the boot and shutdown units + hosts: all + gather_facts: false + vars: + docker_verify_units: [docker-start-missed, docker-stop-at-shutdown] + tasks: + - name: Stat the scripts and the unit files + ansible.builtin.stat: + path: "{{ item }}" + loop: + - /usr/local/sbin/docker-start-missed + - /usr/local/sbin/docker-stop-at-shutdown + - /etc/systemd/system/docker-start-missed.service + - /etc/systemd/system/docker-stop-at-shutdown.service + register: docker_verify_unit_files + + - name: The scripts are executable and the unit files are not + ansible.builtin.assert: + that: + - docker_verify_unit_files.results | map(attribute='stat.exists') | unique | list == [true] + - docker_verify_unit_files.results[0].stat.mode == "0755" + - docker_verify_unit_files.results[1].stat.mode == "0755" + - docker_verify_unit_files.results[2].stat.mode == "0644" + - docker_verify_unit_files.results[3].stat.mode == "0644" + quiet: true + + - name: Ask systemd about the units + ansible.builtin.command: + argv: + - systemctl + - show + - --property=UnitFileState,ActiveState,After,Before + - "{{ item }}.service" + loop: "{{ docker_verify_units }}" + register: docker_verify_unit_show + changed_when: false + + - name: Both units are enabled + ansible.builtin.assert: + that: "'UnitFileState=enabled' in item.stdout" + quiet: true + loop: "{{ docker_verify_unit_show.results }}" + + - name: The boot unit starts after docker, the shutdown unit stops before it + ansible.builtin.assert: + that: + - "'docker.service' in (docker_verify_unit_show.results[0].stdout | regex_search('After=.*'))" + - "'docker.service' in (docker_verify_unit_show.results[1].stdout | regex_search('Before=.*'))" + - "'network-online.target' in (docker_verify_unit_show.results[1].stdout | regex_search('After=.*'))" + - "'remote-fs.target' in (docker_verify_unit_show.results[1].stdout | regex_search('After=.*'))" + quiet: true + + - name: The shutdown unit is active, which is what lets its stop action run + ansible.builtin.assert: + that: "'ActiveState=active' in docker_verify_unit_show.results[1].stdout" + quiet: true + + - name: Read the shutdown unit + ansible.builtin.slurp: + src: /etc/systemd/system/docker-stop-at-shutdown.service + register: docker_verify_stop_unit + + - name: The timeout the converge set reaches the unit + ansible.builtin.assert: + that: + - "'Environment=DOCKER_STOP_TIMEOUT=20' in (docker_verify_stop_unit.content | b64decode)" + - "'TimeoutStopSec=50' in (docker_verify_stop_unit.content | b64decode)" + quiet: true + + - name: The start script refuses an option it does not know + ansible.builtin.command: /usr/local/sbin/docker-start-missed --no-such-option + register: docker_verify_start_run + changed_when: false + failed_when: docker_verify_start_run.rc != 2 + +# Switching an input back to false removes that unit and script and leaves the other alone. +- name: Verify that a unit is removed when its input is false + hosts: all + vars: + docker_gpg_url: file:///srv/docker-stub-repo/docker.asc + docker_repo_base_url: file:///srv/docker-stub-repo + docker_users: [moleculeuser] + docker_start_missed: false + docker_stop_at_shutdown: true + docker_stop_at_shutdown_timeout: 20 + tasks: + - name: Apply the role with the boot unit off + ansible.builtin.include_role: + name: mortis.kamino.docker + + - name: Stat the boot unit's files and the shutdown unit's script + ansible.builtin.stat: + path: "{{ item }}" + loop: + - /usr/local/sbin/docker-start-missed + - /etc/systemd/system/docker-start-missed.service + - /usr/local/sbin/docker-stop-at-shutdown + register: docker_verify_off + + - name: The boot unit is gone and the shutdown unit is still there + ansible.builtin.assert: + that: docker_verify_off.results | map(attribute='stat.exists') | list == [false, false, true] + quiet: true + + - name: Apply the role again with both inputs on + ansible.builtin.include_role: + name: mortis.kamino.docker + vars: + docker_start_missed: true + # docker_remove_data is set, so this also covers the destructive path: the packages are # purged and /var/lib/docker, seeded in prepare.yml, is deleted. The removal stops the unit # before the package takes it away, so it can only run once; a second run would fail on the @@ -114,9 +227,13 @@ - /etc/apt/keyrings/docker.asc - /var/lib/docker - /usr/lib/systemd/system/docker.service + - /usr/local/sbin/docker-start-missed + - /usr/local/sbin/docker-stop-at-shutdown + - /etc/systemd/system/docker-start-missed.service + - /etc/systemd/system/docker-stop-at-shutdown.service register: docker_verify_gone - - name: The source list, the keyring, the data and the unit are gone + - name: The source list, the keyring, the data, the unit and the two extra units are gone ansible.builtin.assert: that: docker_verify_gone.results | map(attribute='stat.exists') | unique | list == [false] quiet: true diff --git a/roles/docker/tasks/main.yml b/roles/docker/tasks/main.yml index d5c2446..84384b7 100644 --- a/roles/docker/tasks/main.yml +++ b/roles/docker/tasks/main.yml @@ -31,5 +31,10 @@ when: not (docker_remove | default(false) | bool) tags: [docker, configure] +- name: Install or remove the boot and shutdown units + ansible.builtin.include_tasks: units.yml + when: not (docker_remove | default(false) | bool) + tags: [docker, configure] + - name: Flush handlers ansible.builtin.meta: flush_handlers diff --git a/roles/docker/tasks/remove.yml b/roles/docker/tasks/remove.yml index 134a76d..707dbdf 100644 --- a/roles/docker/tasks/remove.yml +++ b/roles/docker/tasks/remove.yml @@ -8,6 +8,20 @@ enabled: false tags: [docker, remove] +- name: Take out the start-at-boot unit + ansible.builtin.include_tasks: unit_absent.yml + vars: + __docker_unit_name: docker-start-missed + __docker_unit_script: /usr/local/sbin/docker-start-missed + tags: [docker, remove] + +- name: Take out the stop-at-shutdown unit + ansible.builtin.include_tasks: unit_absent.yml + vars: + __docker_unit_name: docker-stop-at-shutdown + __docker_unit_script: /usr/local/sbin/docker-stop-at-shutdown + tags: [docker, remove] + - name: Remove Docker Engine packages become: true ansible.builtin.apt: diff --git a/roles/docker/tasks/unit_absent.yml b/roles/docker/tasks/unit_absent.yml new file mode 100644 index 0000000..9fe8fa5 --- /dev/null +++ b/roles/docker/tasks/unit_absent.yml @@ -0,0 +1,35 @@ +--- +# Takes one of the role's units out: disable it, delete its files, tell systemd. A running unit is not stopped, because stopping +# docker-stop-at-shutdown runs its stop action and ends every container. Needs __docker_unit_name and __docker_unit_script. +- name: Disable {{ __docker_unit_name }} + become: true + ansible.builtin.systemd: + name: "{{ __docker_unit_name }}.service" + enabled: false + register: __docker_unit_disabled + # The unit may not exist (systemd: "Could not find the requested service"): there is nothing to disable. + failed_when: + - __docker_unit_disabled.failed | default(false) + - "'Could not find the requested service' not in (__docker_unit_disabled.msg | default(''))" + when: not ansible_check_mode + tags: [docker, configure, remove] + +- name: Remove the files of {{ __docker_unit_name }} + become: true + ansible.builtin.file: + path: "{{ item }}" + state: absent + loop: + - "/etc/systemd/system/{{ __docker_unit_name }}.service" + - "{{ __docker_unit_script }}" + register: __docker_unit_removed + tags: [docker, configure, remove] + +- name: Reload systemd after removing {{ __docker_unit_name }} + become: true + ansible.builtin.systemd: + daemon_reload: true + when: + - __docker_unit_removed is changed + - not ansible_check_mode + tags: [docker, configure, remove] diff --git a/roles/docker/tasks/units.yml b/roles/docker/tasks/units.yml new file mode 100644 index 0000000..f7e008c --- /dev/null +++ b/roles/docker/tasks/units.yml @@ -0,0 +1,123 @@ +--- +# The two opt-in units for a host that runs Docker with live-restore. Each is installed when its input is true and removed when it is false. +- name: Install the boot unit that starts containers Docker skipped + when: docker_start_missed | bool + tags: [docker, configure] + block: + - name: Install the script that starts containers Docker skipped at boot + become: true + ansible.builtin.copy: + src: docker-start-missed + dest: /usr/local/sbin/docker-start-missed + owner: root + group: root + mode: "0755" + tags: [docker, configure] + + # Type=simple, not oneshot: a oneshot unit in multi-user.target holds the boot until it finishes, which can take minutes. A failure + # still shows in `systemctl --failed`, and the target only Wants this unit, so it never fails the boot. No Wants= on Docker: a host + # whose operator keeps Docker disabled must not get it started by this unit. + - name: Install the unit that starts containers Docker skipped at boot + become: true + ansible.builtin.copy: + dest: /etc/systemd/system/docker-start-missed.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Start containers that Docker skipped at boot + After={{ docker_service }}.service + ConditionPathExists=/usr/bin/docker + + [Service] + Type=simple + ExecStart=/usr/local/sbin/docker-start-missed --settle {{ docker_start_missed_settle_seconds }} + + [Install] + WantedBy=multi-user.target + register: __docker_start_missed_unit + tags: [docker, configure] + + # Not in check mode: on the first run the unit file above is only simulated, so systemd would not find it. + - name: Enable the unit that starts containers Docker skipped at boot + become: true + ansible.builtin.systemd: + name: docker-start-missed.service + enabled: true + daemon_reload: true + when: not ansible_check_mode + tags: [docker, configure] + +- name: Take out the unit that starts containers Docker skipped + ansible.builtin.include_tasks: unit_absent.yml + vars: + __docker_unit_name: docker-start-missed + __docker_unit_script: /usr/local/sbin/docker-start-missed + when: not (docker_start_missed | bool) + tags: [docker, configure] + +- name: Install the shutdown unit that ends containers while the network is up + when: docker_stop_at_shutdown | bool + tags: [docker, configure] + block: + - name: Install the script that ends containers at shutdown + become: true + ansible.builtin.copy: + src: docker-stop-at-shutdown + dest: /usr/local/sbin/docker-stop-at-shutdown + owner: root + group: root + mode: "0755" + tags: [docker, configure] + + # Stop order is the reverse of start order: Before= makes docker stop first, so no restart policy can interfere, and After= the network + # and remote file systems makes this unit stop before them, while NFS can still be reached. The work is the stop action, which systemd + # runs only for a unit that is active: RemainAfterExit keeps it active after its start action, and the role starts it below. + - name: Install the unit that ends containers at shutdown + become: true + ansible.builtin.copy: + dest: /etc/systemd/system/docker-stop-at-shutdown.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=Stop containers while the network and NFS shares are still up + After=network-online.target remote-fs.target + Before={{ docker_service }}.service + ConditionPathExists=/usr/bin/docker + + [Service] + Type=oneshot + RemainAfterExit=yes + ExecStart=/bin/true + Environment=DOCKER_STOP_TIMEOUT={{ docker_stop_at_shutdown_timeout }} + ExecStop=/usr/local/sbin/docker-stop-at-shutdown + TimeoutStopSec={{ (docker_stop_at_shutdown_timeout | int) + 30 }} + + [Install] + WantedBy=multi-user.target + register: __docker_stop_at_shutdown_unit + tags: [docker, configure] + + # Started now, so the first shutdown after this run is covered without a reboot. Not in check mode: the unit file above is only + # simulated there, and a dry run must not start anything. A changed unit is not restarted, because stopping it runs its stop action, + # which ends every container. + - name: Enable and start the unit that ends containers at shutdown + become: true + ansible.builtin.systemd: + name: docker-stop-at-shutdown.service + enabled: true + state: started + daemon_reload: true + when: not ansible_check_mode + tags: [docker, configure] + +- name: Take out the shutdown unit that ends containers + ansible.builtin.include_tasks: unit_absent.yml + vars: + __docker_unit_name: docker-stop-at-shutdown + __docker_unit_script: /usr/local/sbin/docker-stop-at-shutdown + when: not (docker_stop_at_shutdown | bool) + tags: [docker, configure] diff --git a/roles/docker/tasks/validate.yml b/roles/docker/tasks/validate.yml index a4bf452..656a817 100644 --- a/roles/docker/tasks/validate.yml +++ b/roles/docker/tasks/validate.yml @@ -21,3 +21,13 @@ {% endif %} quiet: true tags: always + +- name: Check the unit timings + ansible.builtin.assert: + that: + - docker_start_missed_settle_seconds | int(-1) >= 0 + - docker_stop_at_shutdown_timeout | int(0) >= 1 + fail_msg: >- + docker_start_missed_settle_seconds must be a whole number of at least 0 and docker_stop_at_shutdown_timeout a whole number of at least 1. + quiet: true + tags: always diff --git a/tests/sanity/ignore-common.txt b/tests/sanity/ignore-common.txt index c73591b..66c57c2 100644 --- a/tests/sanity/ignore-common.txt +++ b/tests/sanity/ignore-common.txt @@ -2,3 +2,5 @@ COPYING no-smart-quotes LICENSES/GPL-3.0-only.txt no-smart-quotes LICENSES/GPL-3.0-or-later.txt no-smart-quotes roles/docker/molecule/default/files/build-stub-repo.sh shebang # run by the docker scenario, not by Ansible +roles/docker/files/docker-start-missed shebang # a command the role installs on the host, run by systemd, not an Ansible module +roles/docker/files/docker-stop-at-shutdown shebang # a command the role installs on the host, run by systemd, not an Ansible module diff --git a/tests/scripts/test_docker_files.py b/tests/scripts/test_docker_files.py new file mode 100644 index 0000000..0c4491b --- /dev/null +++ b/tests/scripts/test_docker_files.py @@ -0,0 +1,269 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Run with: python3 -m unittest discover -s tests/scripts""" + +import importlib.machinery +import importlib.util +import json +import pathlib +import re +import unittest +from datetime import UTC, datetime +from types import SimpleNamespace + +ROLE_FILES = pathlib.Path(__file__).resolve().parents[2] / "roles/docker/files" +# The script has no .py suffix (it is installed as a command), so name the loader. +loader = importlib.machinery.SourceFileLoader( + "docker_start_missed", str(ROLE_FILES / "docker-start-missed") +) +spec = importlib.util.spec_from_loader("docker_start_missed", loader) +m = importlib.util.module_from_spec(spec) +loader.exec_module(m) + +BOOT = datetime(2026, 11, 17, 14, 40, 14, tzinfo=UTC) + + +def container( + name, + policy="unless-stopped", + code=255, + finished="2026-11-17T14:40:16.660987249Z", + running=False, + status="exited", +): + return { + "Name": f"/{name}", + "HostConfig": {"RestartPolicy": {"Name": policy}}, + "State": { + "Running": running, + "Status": "running" if running else status, + "ExitCode": code, + "FinishedAt": finished, + }, + } + + +class Missed(unittest.TestCase): + def test_the_skipped_container_is_selected(self): + self.assertEqual(m.missed([container("prometheus")], BOOT), ["prometheus"]) + + def test_running_container_is_left_alone(self): + self.assertEqual( + m.missed([container("grafana", running=True, code=0)], BOOT), [] + ) + + def test_a_manual_stop_stays_stopped(self): + for code in (0, 137, 143, 1): + self.assertEqual(m.missed([container("x", code=code)], BOOT), [], code) + + def test_died_before_this_boot_is_not_ours(self): + self.assertEqual( + m.missed([container("x", finished="2026-11-16T10:00:00.1Z")], BOOT), [] + ) + + def test_boot_tolerance(self): + self.assertEqual( + m.missed([container("x", finished="2026-11-17T14:40:10Z")], BOOT), + ["x"], + "within 5 s before the computed boot time", + ) + self.assertEqual( + m.missed([container("x", finished="2026-11-17T14:40:08Z")], BOOT), [] + ) + + def test_only_unless_stopped_and_always(self): + for policy, expected in ( + ("unless-stopped", ["x"]), + ("always", ["x"]), + ("on-failure", []), + ("no", []), + ("", []), + ): + self.assertEqual( + m.missed([container("x", policy=policy)], BOOT), expected, policy + ) + + def test_never_started_container_has_no_finish_time(self): + self.assertEqual( + m.missed([container("x", finished="0001-01-01T00:00:00Z")], BOOT), [] + ) + self.assertEqual(m.missed([container("x", finished="")], BOOT), []) + + def test_a_restarting_container_is_left_to_docker(self): + self.assertEqual(m.missed([container("x", status="restarting")], BOOT), []) + + def test_names_are_sorted_and_stripped(self): + self.assertEqual( + m.missed( + [ + container("blackbox"), + container("prometheus"), + container("grafana", running=True), + ], + BOOT, + ), + ["blackbox", "prometheus"], + ) + + +class ParseTime(unittest.TestCase): + def test_nanoseconds(self): + self.assertEqual( + m.parse_time("2026-11-17T14:40:16.660987249Z"), + datetime(2026, 11, 17, 14, 40, 16, 660987, tzinfo=UTC), + ) + + def test_no_fraction(self): + self.assertEqual( + m.parse_time("2026-11-17T14:40:16Z"), + datetime(2026, 11, 17, 14, 40, 16, tzinfo=UTC), + ) + + +class FakeDocker: + """Stands in for the docker CLI: `exited` is what `ps` and `inspect` report, `start_rc` the exit code per name.""" + + def __init__(self, exited, start_rc=None, info_rc=0, stays_up=True): + self.exited, self.start_rc, self.info_rc, self.stays_up = ( + exited, + start_rc or {}, + info_rc, + stays_up, + ) + self.calls = [] + + def __call__(self, *args): + self.calls.append(args) + out = SimpleNamespace(returncode=0, stdout="", stderr="") + if args[0] == "info": + out.returncode = self.info_rc + elif args[0] == "ps": + out.stdout = " ".join(f"id{i}" for i, _container in enumerate(self.exited)) + elif args[0] == "inspect" and args[1] != "-f": + out.stdout = json.dumps(self.exited) + elif args[0] == "inspect": + out.stdout = "true\n" if self.stays_up else "false\n" + elif args[0] == "start": + out.returncode = self.start_rc.get(args[1], 0) + out.stderr = "boom" if out.returncode else "" + return out + + def started(self): + return [c[1] for c in self.calls if c[0] == "start"] + + +class RunOnce(unittest.TestCase): + def run_it(self, fake): + logs = [] + rc = m.run_once( + 0, run=fake, sleep=lambda _s: None, boot_time=BOOT, log=logs.append + ) + return rc, logs + + def test_starts_the_skipped_ones_only(self): + fake = FakeDocker([container("prometheus"), container("manual", code=0)]) + rc, logs = self.run_it(fake) + self.assertEqual((rc, fake.started()), (0, ["prometheus"])) + self.assertTrue(any("prometheus" in line for line in logs)) + + def test_nothing_to_do(self): + fake = FakeDocker([]) + self.assertEqual(self.run_it(fake)[0], 0) + self.assertEqual(fake.started(), []) + + def test_a_failed_start_fails_the_unit_but_the_others_still_start(self): + fake = FakeDocker([container("a"), container("b")], start_rc={"a": 1}) + rc, logs = self.run_it(fake) + self.assertEqual((rc, fake.started()), (1, ["a", "b"])) + self.assertTrue(any("could not start a" in line for line in logs)) + + def test_a_container_that_does_not_stay_up_fails_the_unit(self): + rc, logs = self.run_it(FakeDocker([container("a")], stays_up=False)) + self.assertEqual(rc, 1) + self.assertTrue(any("did not stay up" in line for line in logs)) + + def test_dry_run_reports_and_starts_nothing(self): + fake = FakeDocker([container("prometheus")]) + logs = [] + rc = m.run_once( + 0, + run=fake, + sleep=lambda _s: None, + boot_time=BOOT, + log=logs.append, + dry_run=True, + ) + self.assertEqual((rc, fake.started()), (0, [])) + self.assertEqual(logs, ["would start: prometheus"]) + + def test_inspect_failing_is_a_docker_problem(self): + class Fake(FakeDocker): + def __call__(self, *args): + out = super().__call__(*args) + if args[0] == "inspect": + out.returncode, out.stdout, out.stderr = 1, "", "daemon error" + return out + + rc, logs = self.run_it(Fake([container("a")])) + self.assertEqual(rc, 2) + self.assertTrue(any("inspect failed" in line for line in logs)) + + def test_a_removed_container_does_not_stop_the_rest(self): + class Fake(FakeDocker): + def __call__(self, *args): + out = super().__call__(*args) + if args[0] == "inspect" and args[1] != "-f": + out.returncode = 1 # docker prints the containers it found and exits 1 for the missing one + return out + + fake = Fake([container("a")]) + self.assertEqual((self.run_it(fake)[0], fake.started()), (0, ["a"])) + + def test_unreadable_inspect_output_is_a_docker_problem(self): + class Fake(FakeDocker): + def __call__(self, *args): + out = super().__call__(*args) + if args[0] == "inspect" and args[1] != "-f": + out.stdout = "not json" + return out + + fake = Fake([container("a")]) + self.assertEqual((self.run_it(fake)[0], fake.started()), (2, [])) + + def test_a_timestamp_in_an_unexpected_format_is_a_docker_problem(self): + fake = FakeDocker([container("a", finished="Nov 17 14:40:16 2026")]) + self.assertEqual((self.run_it(fake)[0], fake.started()), (2, [])) + + def test_ps_failing_is_a_docker_problem(self): + class Fake(FakeDocker): + def __call__(self, *args): + out = super().__call__(*args) + if args[0] == "ps": + out.returncode, out.stderr = 1, "denied" + return out + + self.assertEqual(self.run_it(Fake([container("a")]))[0], 2) + + def test_docker_never_answers(self): + fake = FakeDocker([container("a")], info_rc=1) + rc, _logs = self.run_it(fake) + self.assertEqual((rc, fake.started()), (2, [])) + + +class StopAtShutdownScript(unittest.TestCase): + def test_it_never_calls_docker_stop_or_kill(self): + # Both set the manually-stopped marker, so a container with restart policy unless-stopped would not start at the next boot. + code = [ + line + for line in (ROLE_FILES / "docker-stop-at-shutdown") + .read_text() + .splitlines() + if not line.lstrip().startswith("#") + ] + self.assertEqual( + [line for line in code if re.search(r"\bdocker\s+(stop|kill)\b", line)], [] + ) + + +if __name__ == "__main__": + unittest.main() -- 2.43.0