feat(docker): add opt-in boot and shutdown units for hosts that run Docker with live-restore
Build / build (pull_request) Successful in 27s
Lint / lint (pull_request) Successful in 2m15s
Molecule / molecule (pull_request) Successful in 4m17s

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
This commit is contained in:
Dragonish committed 2026-11-25 17:31:37 +00:00
1 parent 4a7189c067
commit 567e9cca7c
16 files changed
+917 -6

No files matched your search

+23 -3
View File
@@ -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-<id>.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
+16
View File
@@ -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
+176
View File
@@ -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:]))
+44
View File
@@ -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-<id>.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
+40
View File
@@ -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-<id>.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
@@ -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
@@ -5,7 +5,7 @@
# build-stub-repo.sh <repo-root> <codename> <work-dir>
#
# 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 <repo-root>/docker.asc, which is what
# the role fetches as its keyring. The secret key stays in <work-dir> 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)
+118 -1
View File
@@ -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
+5
View File
@@ -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
+14
View File
@@ -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:
+35
View File
@@ -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]
+123
View File
@@ -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]
+10
View File
@@ -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