#!/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:]))