diff --git a/roles/github_runner_cluster/README.md b/roles/github_runner_cluster/README.md index a639b34..0d2c405 100644 --- a/roles/github_runner_cluster/README.md +++ b/roles/github_runner_cluster/README.md @@ -587,7 +587,7 @@ or read from 1Password by adding `exadev.github_runner.github_runner_secrets_one `tests/unit/test_cluster_host_prerequisites.py` covers the [host preparation](#host-preparation) without a real host: the defaults, that both node modes include the steps at the right point, and the steps themselves (`tests/cluster_host_prerequisites/run.yml`) against stand-ins for `modprobe`, `sysctl`, `apparmor_parser` and `sudo` on `PATH`, with a k3s data directory laid out as k3s leaves it. -`tests/unit/test_runtime_autostart.py` covers the [container runtime tasks](#container-runtime-after-a-reboot-macos) without a Mac: it renders the launchd agent and daemon through `tests/runtime_autostart/render_plist.yml`, and runs `tasks/runtime.yml` and `tasks/end_checks.yml` through the role against stand-ins for `docker`, `colima`, `launchctl`, `plutil` and `sudo` on `PATH`, the stand-in `launchctl` refusing to change the system domain unless it was run through the stand-in `sudo`. It checks the variable defaults, that Linux hosts are left alone, that a second run changes nothing, that `--check` writes and starts nothing, and that each way the runtime or the node's container can be down fails with its message. `tests/unit/test_container_runtime.py` covers the filter that works out the runtime from the Docker context. Nothing there touches a real Colima, launchd or Docker Desktop, so loading the agent into a real login session, and the daemon starting a Colima VM at a real boot with no one logged in, are the parts only a run on a Mac can show. +`tests/unit/test_runtime_autostart*.py` cover the [container runtime tasks](#container-runtime-after-a-reboot-macos) without a Mac: they render the launchd agent and daemon through `tests/runtime_autostart/render_plist.yml`, and run `tasks/runtime.yml` and `tasks/end_checks.yml` through the role against stand-ins for `docker`, `colima`, `launchctl`, `plutil` and `sudo` on `PATH`, the stand-in `launchctl` refusing to change the system domain unless it was run through the stand-in `sudo`. They check the variable defaults, that Linux hosts are left alone, that a second run changes nothing, that `--check` writes and starts nothing, and that each way the runtime or the node's container can be down fails with its message. `tests/unit/test_container_runtime.py` covers the filter that works out the runtime from the Docker context. Nothing there touches a real Colima, launchd or Docker Desktop, so loading the agent into a real login session, and the daemon starting a Colima VM at a real boot with no one logged in, are the parts only a run on a Mac can show. `tests/unit/test_cluster_colima_size.py` covers the Colima VM size: the filters that read the profile's size (`plugins/filter/cluster_colima.py`) and take and give back the `fleet-regrade` Lease (`plugins/filter/cluster_guard.py`), and `tasks/colima_size.yml` run through the role (`tests/colima_size/run.yml`) against stand-ins for `docker` and `colima` that keep each profile's VM, the node containers, the cluster's nodes and the Lease as files. It checks the `colima` arguments, the derived memory (the host's less both reserves, a larger reserve giving a smaller VM, a derivation below the floor sized at the floor with a warning, an explicit memory winning within the budget and refused above it before anything is read from the VM), that a VM of the size set is only read, that a second run changes nothing, the order of a resize (the Lease, the cordon, the runner pods, the drain, the stop, the start with the new size, the uncordon, the Lease given back), that a held Lease, a server that is not Ready and a server whose etcd is unhealthy each refuse before anything changes, that `--check` reports and changes nothing, that several hosts take their turns one at a time, the refusal of a value that is not a whole number, and that a host that does not run Colima is left alone and says so under `-v`. A real Colima VM's resize is shown only by its first run on a Mac. diff --git a/tests/unit/runtime_autostart_support.py b/tests/unit/runtime_autostart_support.py new file mode 100644 index 0000000..e334cec --- /dev/null +++ b/tests/unit/runtime_autostart_support.py @@ -0,0 +1,477 @@ +"""What the tests of the cluster role's runtime tasks share: the paths and values they read, the stand-in for docker, colima, launchctl, plutil, sudo and ps, and the fixture that runs the role against it.""" + +from __future__ import annotations + +import grp +import os +import pwd +import re +import shutil +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from typing import Any + +import yaml + + +ROOT = Path(__file__).resolve().parents[2] +ROLE = ROOT / "roles" / "github_runner_cluster" +RENDER = ROOT / "tests" / "runtime_autostart" / "render_plist.yml" +RUN = ROOT / "tests" / "runtime_autostart" / "run.yml" +HOST_OS = ROOT / "tests" / "runtime_autostart" / "host_os.yml" +ANSIBLE_PLAYBOOK = os.environ.get("ANSIBLE_PLAYBOOK", "ansible-playbook") +DEFAULTS: dict[str, Any] = yaml.safe_load((ROLE / "defaults" / "main.yml").read_text()) +UID = 501 +HOME = "/Users/example" +DARWIN_ONLY = "ansible_facts['system'] == 'Darwin'" +MODULES_FILE = "/etc/modules-load.d/br_netfilter.conf" +SYSCTL_FILE = "/etc/sysctl.d/90-github-runner-br-netfilter.conf" +I386_ENTRY = "/proc/sys/fs/binfmt_misc/qemu-i386" +I386_OFF = f"test ! -e {I386_ENTRY} || echo 0 | sudo tee {I386_ENTRY} > /dev/null" + + +def ansible_env() -> dict[str, str]: + return {**os.environ, "ANSIBLE_COLLECTIONS_PATH": str(ROOT / "playbooks" / "collections"), "ANSIBLE_LOCALHOST_WARNING": "false", "ANSIBLE_INVENTORY_UNPARSED_WARNING": "false", "ANSIBLE_RETRY_FILES_ENABLED": "false"} + + +# Stands in for docker, colima, launchctl, plutil and sudo, which are all this one script under five names. State is files in $RUNTIME_STUB: runtime-up (the Docker daemon answers), session (the user has a login session), loaded (the agent is loaded in it), daemon-loaded (the daemon is loaded into the system domain, which only root can change), .state (what docker ps prints), colima-start-fails; every call is appended to calls.log with the Docker context it ran with. The Colima VM is the directory vm in $RUNTIME_STUB: its files are under vm/files, /proc/sys/net/bridge exists under vm/files only while br_netfilter is loaded, and a sysctl is the file vm/sysctl/ (a bridge key reads 1 once the module is loaded, as the kernel's default, unless the file says otherwise). +STUB = """#!{python} +import os, sys +stub = os.environ["RUNTIME_STUB"] +name = os.path.basename(sys.argv[0]) +args = sys.argv[1:] +if name == "sudo": + # Does what sudo does for the role, which is to run the command as root: it marks the command with RUNTIME_ROOT, which the stand-in launchctl needs to change the system domain, and keeps its own calls out of calls.log. + with open(os.path.join(stub, "sudo.log"), "a") as sudo_log: + sudo_log.write(" ".join(args) + "\\n") + while args[0] != "/bin/sh": + args = args[1:] + os.environ["RUNTIME_ROOT"] = "1" + os.execv(args[0], args) +with open(os.path.join(stub, "calls.log"), "a") as log: + log.write(os.environ.get("DOCKER_CONTEXT", "-") + " " + name + " " + " ".join(args) + "\\n") +with open(os.path.join(stub, "colima-home.log"), "a") as homes: + homes.write(name + " " + " ".join(args) + " " + os.environ.get("COLIMA_HOME", "-") + "\\n") +def exists(file): + return os.path.exists(os.path.join(stub, file)) +def hang(): + # A program that never answers and does not die on SIGALRM, as a Go binary does not; with ignore-term it ignores TERM as well, so only KILL ends it. + import signal, time + signal.signal(signal.SIGALRM, signal.SIG_IGN) + if exists("ignore-term"): + signal.signal(signal.SIGTERM, signal.SIG_IGN) + with open(os.path.join(stub, "hung.pids"), "a") as pids: + pids.write(str(os.getpid()) + "\\n") + time.sleep(300) +def touch(file): + open(os.path.join(stub, file), "w").close() +def need_root(): + if os.environ.get("RUNTIME_ROOT") != "1": + sys.exit("launchctl: Operation not permitted while changing the system domain as a user") +if name == "docker" and args[:2] == ["context", "inspect"]: + # Read from the context file alone, so it answers with the daemon down. An empty context name or an unknown one is an error, as docker's is. + if args[-1] == "" or exists("context-unknown"): + sys.exit("context " + repr(args[-1]) + ": context not found") + if not exists("context-host"): + sys.exit("context inspect: no context-host file") + print(open(os.path.join(stub, "context-host")).read(), end="") +elif name == "docker": + if args[:1] == ["info"] and exists("docker-hangs"): + hang() + if args[:1] == ["info"] and exists("docker-exit"): + sys.exit(int(open(os.path.join(stub, "docker-exit")).read())) + if not exists("runtime-up") and args[:1] == ["info"] and exists("docker-answers-after"): + # A daemon that fails its first tries and then answers, as one that is restarting or a loaded host does. + counter = os.path.join(stub, "docker-info-failures") + seen = int(open(counter).read()) if os.path.exists(counter) else 0 + if seen >= int(open(os.path.join(stub, "docker-answers-after")).read()): + touch("runtime-up") + else: + open(counter, "w").write(str(seen + 1)) + if not exists("runtime-up"): + sys.exit("Cannot connect to the Docker daemon") + if args[0] == "info": + print("27.0.0") + elif args[0] == "ps": + container = args[args.index("--filter") + 1].removeprefix("name=^/").removesuffix("$") + if exists(container + ".state"): + print(open(os.path.join(stub, container + ".state")).read(), end="") + else: + sys.exit("unexpected docker call: " + " ".join(args)) +elif name == "colima" and args[0] == "ssh": + if exists("guest-hangs") and args[args.index("--") + 1:] == ["true"]: + hang() + if exists("guest-answers") and args[args.index("--") + 1:] == ["true"]: + sys.exit(0) + if not exists("runtime-up"): + sys.exit("colima: the VM is not running") + command = args[args.index("--") + 1:] + sudo = command[0] == "sudo" + if sudo: + command = command[1:] + vm = os.path.join(stub, "vm") + def vm_file(path): + return os.path.join(vm, "files", path.lstrip("/")) + def sysctl_file(key): + return os.path.join(vm, "sysctl", key) + if command[0] == "cat": + if not os.path.exists(vm_file(command[1])): + sys.exit("cat: " + command[1] + ": No such file or directory") + print(open(vm_file(command[1])).read(), end="") + elif command == ["uname", "-m"]: + # aarch64 unless a test says otherwise, as the VM of an Apple silicon Mac is. + print(open(os.path.join(vm, "arch")).read().strip() if os.path.exists(os.path.join(vm, "arch")) else "aarch64") + elif command[0] == "test" and command[1] == "-d": + sys.exit(0 if os.path.isdir(vm_file(command[2])) else 1) + elif command[0] == "sysctl" and command[1] == "-n": + if command[2].startswith("net.bridge.") and not os.path.isdir(vm_file("/proc/sys/net/bridge")): + sys.exit("sysctl: cannot stat /proc/sys/" + command[2].replace(".", "/") + ": No such file or directory") + print(open(sysctl_file(command[2])).read().strip() if os.path.exists(sysctl_file(command[2])) else "1") + elif sudo and command[0] == "sysctl" and command[1] == "-w": + key, value = command[2].split("=") + if key.startswith("net.bridge.") and not os.path.isdir(vm_file("/proc/sys/net/bridge")): + sys.exit("sysctl: cannot stat /proc/sys/" + key.replace(".", "/") + ": No such file or directory") + os.makedirs(os.path.dirname(sysctl_file(key)), exist_ok=True) + open(sysctl_file(key), "w").write(value) + elif sudo and command[0] == "modprobe": + if command[-1] != "br_netfilter": + sys.exit("modprobe: FATAL: Module " + command[-1] + " not found") + os.makedirs(vm_file("/proc/sys/net/bridge"), exist_ok=True) + elif command[0] == "dpkg-query": + installed = open(os.path.join(vm, "packages")).read().split() if os.path.exists(os.path.join(vm, "packages")) else [] + if command[-1] not in installed: + sys.exit("dpkg-query: no packages found matching " + command[-1]) + print("install ok installed", end="") + elif sudo and command[0] == "apt-get" and command[1] == "update": + os.makedirs(vm, exist_ok=True) + open(os.path.join(vm, "package-index"), "w").write("updated\\n") + elif sudo and command[0] == "apt-get" and command[1] == "install": + # A fresh VM has an empty package index: an install with no update before it fails as apt does. + if not os.path.exists(os.path.join(vm, "package-index")): + sys.exit("E: Unable to locate package " + command[-1]) + os.makedirs(vm, exist_ok=True) + open(os.path.join(vm, "packages"), "a").write(command[-1] + "\\n") + elif command[0] == "systemctl" and command[1] == "is-active": + active = open(os.path.join(vm, "active-units")).read().split() if os.path.exists(os.path.join(vm, "active-units")) else [] + print("active" if command[2] in active else "inactive") + sys.exit(0 if command[2] in active else 3) + elif sudo and command[0] == "systemctl" and command[1] == "daemon-reload": + pass + elif sudo and command[0] == "systemctl" and command[1:3] == ["enable", "--now"]: + os.makedirs(vm, exist_ok=True) + open(os.path.join(vm, "active-units"), "a").write(command[3] + "\\n") + elif sudo and command[0] == "chmod": + os.chmod(vm_file(command[2]), int(command[1], 8)) + elif sudo and command[0] == "tee": + os.makedirs(os.path.dirname(vm_file(command[1])), exist_ok=True) + content = sys.stdin.read() + open(vm_file(command[1]), "w").write(content) + print(content, end="") + else: + sys.exit("unexpected colima ssh call: " + " ".join(command)) +elif name == "colima" and args[0] == "list": + # One JSON object per profile, whatever profile is asked for: this host has the profile the test names and another one beside it, which is always running. + profile = os.environ.get("RUNTIME_PROFILE", "default") + print('{{"name":"other","status":"Running","runtime":"docker"}}') + print('{{"name":"' + profile + '","status":"' + ("Running" if exists("colima-listed-running") else "Stopped") + '","runtime":"docker"}}') +elif name == "colima" and args[0] == "stop": + if args[:3] != ["stop", "--profile", os.environ.get("RUNTIME_PROFILE", "default")] or args[3:] not in ([], ["--force"]): + sys.exit("unexpected colima stop call: " + " ".join(args)) + if args[3:] == [] and exists("clean-stop-hangs"): + hang() + if args[3:] == [] and exists("clean-stop-fails"): + sys.exit("colima: the VM does not stop") + for file in ("colima-listed-running", "runtime-up", "docker-hangs", "guest-hangs", "docker-exit"): + if exists(file): + os.remove(os.path.join(stub, file)) +elif name == "colima": + if args[0] != "start" or args[-1] != "--activate=false": + sys.exit("unexpected colima call: " + " ".join(args)) + if exists("colima-start-fails"): + sys.exit("colima: the VM did not start") + # Starting a profile Colima already lists as running does nothing, so a wedged VM stays wedged. + if not exists("colima-listed-running"): + touch("colima-listed-running") + touch("runtime-up") + # A VM that is started again answers. + for file in ("docker-hangs", "guest-hangs", "docker-exit"): + if exists(file): + os.remove(os.path.join(stub, file)) +elif name == "ps": + # The host agent as ps shows it, from the file agent-ps (" "); a pid that is not running prints nothing and fails. + if not exists("agent-ps"): + sys.exit(1) + print(open(os.path.join(stub, "agent-ps")).read(), end="") +elif name == "launchctl": + system = args[1] == "system" or args[1].startswith("system/") + # Each job is loaded or not on its own: the watchdog's has a flag of its own beside the start job's. + def flag(target): + return ("watchdog-" if "watchdog" in target else "") + ("daemon-loaded" if system else "loaded") + if args[0] == "print": + sys.exit(0 if exists(flag(args[1]) if system or args[1].count("/") == 2 else "session") else 113) + elif args[0] == "bootstrap": + if not os.path.exists(args[2]): + sys.exit("Bootstrap failed: no such plist") + if system: + need_root() + touch(flag(args[2])) + elif args[0] == "bootout": + if system: + need_root() + os.remove(os.path.join(stub, flag(args[1]))) + else: + sys.exit("unexpected launchctl call: " + " ".join(args)) +elif name == "plutil": + if args[0] != "-lint" or b" str | None: + """Return the name of the task whose header last precedes a "fatal:" line in ansible-playbook's output, or None when nothing failed.""" + task = None + for line in stdout.splitlines(): + header = re.match(r"TASK \[(?:[^:\]]+ : )?(.*)\] \*+$", line) + if header: + task = header.group(1) + elif line.startswith("fatal: "): + return task + return None + + +@unittest.skipIf(shutil.which(ANSIBLE_PLAYBOOK) is None, "ansible-playbook is not installed") +class RoleFixture(unittest.TestCase): + """The stand-in host a test runs the cluster role's runtime tasks against, with the readers of what the stand-ins recorded. It holds no tests, so a module that imports it runs none of another module's.""" + + def setUp(self) -> None: + self.work = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.work) + self.stub = self.work / "stub" + self.home = self.work / "home" + self.stub.mkdir() + self.home.mkdir() + self.bin = self.work / "bin" + self.bin.mkdir() + for name in ("docker", "colima", "launchctl", "plutil", "sudo", "ps"): + tool = self.bin / name + tool.write_text(STUB.format(python=sys.executable)) + tool.chmod(0o755) + self.plist = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima.default.plist" + # Stands in for /Library/LaunchDaemons, which exists on every Mac; the role's own path is narrowed to it below. + self.daemons = self.work / "LaunchDaemons" + self.daemons.mkdir() + # What `docker ps` prints for the node's container once the runtime answers; the end checks need it running. + (self.stub / "github-runner-k3s.state").write_text("running") + + def state(self, *flags: str) -> None: + for flag in flags: + (self.stub / flag).write_text("") + + def run_role(self, *extra: str, tasks: str = "runtime,end_checks", context: str = "colima", context_host: str | None = None, system: str = "Darwin", **variables: Any) -> subprocess.CompletedProcess[str]: + # The endpoint Colima gives its profile's context: the profile's socket in the default home, unless a test says where else. + profile = context.removeprefix("colima-") if context.startswith("colima-") else "default" + (self.stub / "context-host").write_text(context_host if context_host is not None else f"unix://{self.home}/.colima/{profile}/docker.sock") + host = { + "runtime_system": system, + "runtime_uid": UID, + "runtime_home": str(self.home), + "runtime_tasks": tasks, + "github_runner_cluster_docker_cli_context": context, + "github_runner_cluster_docker_cli_environment": {"DOCKER_CONTEXT": context} if context else {}, + "github_runner_cluster_docker_role": "server", + "github_runner_cluster_runtime_path": f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin", + # The tests are not root, so the daemon's property list is owned by the user running them and sits beside the stand-in daemon directory. + "runtime_user": "example", + "github_runner_cluster_runtime_daemon_plist": f"{self.daemons}/{{{{ github_runner_cluster_runtime_launchd_label }}}}.plist", + "github_runner_cluster_runtime_daemon_owner": pwd.getpwuid(os.getuid()).pw_name, + "github_runner_cluster_runtime_daemon_group": grp.getgrgid(os.getgid()).gr_name, + "github_runner_cluster_runtime_watchdog_daemon_plist": f"{self.daemons}/{{{{ github_runner_cluster_runtime_watchdog_label }}}}.plist", + # Off unless a test turns it on, so that the exact launchctl calls the tests of the start job assert are the start job's alone. + "github_runner_cluster_runtime_watchdog": False, + **variables, + } + inventory = self.work / "inventory.yml" + inventory.write_text(yaml.safe_dump({"all": {"hosts": {"node1": host}}})) + # The stand-ins come first on the playbook's own PATH as well as the tasks', so a tool a task runs without the role's PATH still cannot reach this machine's real launchd, Colima or Docker. + env = ansible_env() | {"RUNTIME_STUB": str(self.stub), "RUNTIME_PROFILE": profile, "PATH": f"{self.bin}{os.pathsep}{os.environ['PATH']}"} + return subprocess.run([ANSIBLE_PLAYBOOK, "-i", str(inventory), str(RUN), *extra], capture_output=True, text=True, check=False, env=env, cwd=self.work) + + def calls(self) -> list[str]: + log = self.stub / "calls.log" + return log.read_text().splitlines() if log.exists() else [] + + def colima_homes(self) -> list[str]: + """The COLIMA_HOME (`-` for none) of every colima call, as ` ` lines.""" + log = self.stub / "colima-home.log" + return [line.removeprefix("colima ") for line in log.read_text().splitlines() if line.startswith("colima ")] if log.exists() else [] + + def assert_colima_ran_in(self, home: str) -> None: + """Every colima call (the start and the VM's kernel settings alike) ran with `home`, and the start was among them.""" + homes = self.colima_homes() + self.assertTrue(any(line.startswith("start ") for line in homes), homes) + self.assertEqual([line for line in homes if not line.endswith(f" {home}")], []) + + def changes(self) -> list[str]: + return [call for call in self.calls() if re.match(r"\S+ (colima start|launchctl (bootstrap|bootout))", call)] + + def vm_changes(self) -> list[str]: + """The commands run as root in the Colima VM, in order, without the colima ssh prefix.""" + return [command for command in self.vm_calls() if not self.is_route_guard(command)] + + def vm_calls(self) -> list[str]: + return [match.group(1) for call in self.calls() if (match := re.match(r"\S+ colima ssh --profile \S+ -- (sudo .*)", call))] + + @staticmethod + def is_route_guard(command: str) -> bool: + return "route-guard" in command or "systemctl" in command or "iputils-ping" in command or "apt-get update" in command + + def route_guard_changes(self) -> list[str]: + """The commands that install the route guard in the VM, in order.""" + return [command for command in self.vm_calls() if self.is_route_guard(command)] + + def vm_file(self, path: str) -> Path: + return self.stub / "vm" / "files" / path.lstrip("/") + + def recap(self, result: subprocess.CompletedProcess[str]) -> dict[str, int]: + match = re.search(r"node1\s+: ok=(\d+)\s+changed=(\d+)\s+unreachable=(\d+)\s+failed=(\d+)", result.stdout) + assert match is not None, result.stdout + result.stderr + return dict(zip(("ok", "changed", "unreachable", "failed"), map(int, match.groups()))) + + # A profile Colima lists as running while its runtime does not answer. + + FAST = {"github_runner_cluster_runtime_probe_attempts": 3, "github_runner_cluster_runtime_probe_delay": 0, "github_runner_cluster_runtime_probe_timeout": 5} + + def forget(self) -> None: + """Start a sub-case from a clean stub directory and a clean home.""" + for entry in self.stub.iterdir(): + if entry.is_dir(): + shutil.rmtree(entry) + elif entry.name not in ("context-host", "github-runner-k3s.state"): + entry.unlink() + shutil.rmtree(self.home / ".colima", ignore_errors=True) + + def stops(self) -> list[str]: + return [call for call in self.calls() if re.match(r"\S+ colima stop", call)] + + def starts(self) -> list[str]: + return [call for call in self.calls() if re.match(r"\S+ colima start", call)] + + AGENT = "/usr/local/bin/limactl hostagent --pidfile /example/ha.pid --socket /example/ha.sock" + + @staticmethod + def etime(seconds: int) -> str: + """ps's elapsed time, [[days-]hours:]minutes:seconds.""" + days, rest = divmod(seconds, 86400) + hours, rest = divmod(rest, 3600) + minutes, secs = divmod(rest, 60) + return (f"{days}-" if days else "") + (f"{hours:02d}:" if days or hours else "") + f"{minutes:02d}:{secs:02d}" + + def listed_running(self, agent_age: int | None = 7200, command: str | None = None, stale_file: bool = False) -> None: + """A VM Colima lists as running whose Docker daemon is silent, with a live host agent that has run for `agent_age` seconds (None for no pid file at all). `stale_file` leaves a pid file that is old but names no running process, as one from before a reboot does; `command` is what the process runs.""" + self.state("session", "colima-listed-running") + if agent_age is None: + return + pid = self.home / ".colima" / "_lima" / "colima" / "ha.pid" + pid.parent.mkdir(parents=True, exist_ok=True) + pid.write_text("4242\n") + old = time.time() - 7 * 86400 + os.utime(pid, (old, old)) + if not stale_file: + (self.stub / "agent-ps").write_text(f"{self.etime(agent_age)} {command or self.AGENT}\n") + + def hung_pids(self) -> list[int]: + log = self.stub / "hung.pids" + return [int(line) for line in log.read_text().split()] if log.exists() else [] + + def assert_all_ended(self) -> None: + for pid in self.hung_pids(): + for _ in range(50): + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.1) + else: + self.fail(f"the hung stand-in {pid} is still running") + + def info_calls(self) -> list[str]: + return [call for call in self.calls() if re.match(r"\S+ docker info", call)] + + def assert_left_alone(self, result: subprocess.CompletedProcess[str], *words: str) -> None: + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertEqual(failed_task(result.stdout), "Fail where the VM is not shown to be wedged or the stop is off") + self.assertEqual(self.stops(), []) + self.assertEqual(self.starts(), []) + self.assertIn("colima stop --profile default --force", result.stdout, "the recovery by hand is named") + for word in words: + self.assertIn(word, result.stdout) + + HANG = {"github_runner_cluster_runtime_probe_attempts": 2, "github_runner_cluster_runtime_probe_delay": 0, "github_runner_cluster_runtime_probe_timeout": 2, "github_runner_cluster_runtime_kill_grace": 1, "github_runner_cluster_runtime_clean_stop_timeout": 2} + LABEL = "com.exadev.github-runner.colima.node" + + @property + def node_home(self) -> str: + return f"{self.home}/.colima-node" + + @property + def node_daemon(self) -> Path: + return self.daemons / f"{self.LABEL}.plist" + + @property + def node_agent(self) -> Path: + return self.home / "Library" / "LaunchAgents" / f"{self.LABEL}.plist" + + def run_node(self, *extra: str, **variables: Any) -> subprocess.CompletedProcess[str]: + """Run the role for the bridged node profile (context colima-node, in ~/.colima-node), which is started at boot.""" + return self.run_role(*extra, context="colima-node", context_host=f"unix://{self.node_home}/node/docker.sock", **variables) + + def v2_19_agent(self) -> None: + """A host the previous release set up: the node profile's login agent installed, and loaded when the user has a session.""" + self.node_agent.parent.mkdir(parents=True) + self.node_agent.write_text("") + if (self.stub / "session").exists(): + self.state("loaded") + + def system_calls(self) -> list[str]: + """The launchctl calls that change the system domain, which the stand-in refuses without root.""" + return [call for call in self.calls() if re.search(r"launchctl (bootstrap|bootout) system", call)] + + def assert_a_second_run_changes_nothing(self, context: str, context_host: str | None) -> None: + self.state("session") + self.run_role(context=context, context_host=context_host) + before = self.calls() + result = self.run_role(context=context, context_host=context_host) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.recap(result)["changed"], 0, result.stdout) + self.assertEqual([call for call in self.calls()[len(before) :] if not re.match(r"\S+ (docker (info|ps|context inspect)|launchctl print|colima ssh --profile \S+ -- (cat|test|uname|sysctl -n|systemctl is-active|dpkg-query) )", call)], []) + self.assertNotIn("bootstrap", " ".join(self.calls()[len(before) :])) + + def i386_writes(self) -> list[str]: + """The commands run as root in the VM that write its qemu-i386 entry, in order.""" + return [command for command in self.vm_calls() if I386_ENTRY in command] + + def x86_vm(self, provision: list[dict[str, str]] | None = None, handler: str | None = "enabled") -> Path: + """An x86_64 VM whose qemu-i386 entry reads `handler` (none for no entry), and its profile's colima.yaml with `provision`.""" + self.state("runtime-up") + (self.stub / "vm").mkdir(exist_ok=True) + (self.stub / "vm" / "arch").write_text("x86_64\n") + if handler is not None: + entry = self.vm_file(I386_ENTRY) + entry.parent.mkdir(parents=True, exist_ok=True) + entry.write_text(f"{handler}\ninterpreter /usr/bin/qemu-i386\nflags: POCF\n") + config = self.home / ".colima" / "default" / "colima.yaml" + config.parent.mkdir(parents=True, exist_ok=True) + config.write_text(yaml.safe_dump({"cpu": 8, "arch": "x86_64", "binfmt": True, "provision": provision})) + return config + + # The watchdog's launchd job. + + def watchdog_calls(self) -> list[str]: + """The launchctl calls that load or unload the watchdog, without the Docker context each is logged under. """ + return [call.split(" ", 1)[1] for call in self.calls() if re.match(r"\S+ launchctl (bootstrap|bootout)", call) and "watchdog" in call] diff --git a/tests/unit/test_runtime_autostart.py b/tests/unit/test_runtime_autostart.py index 3509b42..6f0ca3a 100644 --- a/tests/unit/test_runtime_autostart.py +++ b/tests/unit/test_runtime_autostart.py @@ -1,13 +1,11 @@ -"""Tests for how the cluster role keeps a macOS host's container runtime running across reboots: the launchd agent and daemon template (tests/runtime_autostart/render_plist.yml), the variable defaults, the macOS-only guard in tasks/main.yml, and tasks/runtime.yml and tasks/end_checks.yml run through the role (tests/runtime_autostart/run.yml) against stand-ins for docker, colima, launchctl, plutil and sudo.""" +"""Tests for how the cluster role keeps a macOS host's container runtime running across reboots: the launchd agent and daemon template (tests/runtime_autostart/render_plist.yml), the variable defaults, the macOS-only guard in tasks/main.yml and the bounded runner. The role's runtime tasks run against stand-ins in the test_runtime_autostart_*.py modules beside this one.""" from __future__ import annotations -import grp import json import os import platform import plistlib -import pwd import re import shutil import signal @@ -20,25 +18,7 @@ from typing import Any import yaml - -ROOT = Path(__file__).resolve().parents[2] -ROLE = ROOT / "roles" / "github_runner_cluster" -RENDER = ROOT / "tests" / "runtime_autostart" / "render_plist.yml" -RUN = ROOT / "tests" / "runtime_autostart" / "run.yml" -HOST_OS = ROOT / "tests" / "runtime_autostart" / "host_os.yml" -ANSIBLE_PLAYBOOK = os.environ.get("ANSIBLE_PLAYBOOK", "ansible-playbook") -DEFAULTS: dict[str, Any] = yaml.safe_load((ROLE / "defaults" / "main.yml").read_text()) -UID = 501 -HOME = "/Users/example" -DARWIN_ONLY = "ansible_facts['system'] == 'Darwin'" -MODULES_FILE = "/etc/modules-load.d/br_netfilter.conf" -SYSCTL_FILE = "/etc/sysctl.d/90-github-runner-br-netfilter.conf" -I386_ENTRY = "/proc/sys/fs/binfmt_misc/qemu-i386" -I386_OFF = f"test ! -e {I386_ENTRY} || echo 0 | sudo tee {I386_ENTRY} > /dev/null" - - -def ansible_env() -> dict[str, str]: - return {**os.environ, "ANSIBLE_COLLECTIONS_PATH": str(ROOT / "playbooks" / "collections"), "ANSIBLE_LOCALHOST_WARNING": "false", "ANSIBLE_INVENTORY_UNPARSED_WARNING": "false", "ANSIBLE_RETRY_FILES_ENABLED": "false"} +from runtime_autostart_support import ANSIBLE_PLAYBOOK, DARWIN_ONLY, DEFAULTS, HOME, HOST_OS, MODULES_FILE, RENDER, ROLE, ROOT, SYSCTL_FILE, ansible_env def render_plist(**role_vars: Any) -> bytes: @@ -332,213 +312,6 @@ def test_the_comment_cannot_end_the_document_early(self) -> None: self.assertNotIn(b"--", comment.group(1)) -# Stands in for docker, colima, launchctl, plutil and sudo, which are all this one script under five names. State is files in $RUNTIME_STUB: runtime-up (the Docker daemon answers), session (the user has a login session), loaded (the agent is loaded in it), daemon-loaded (the daemon is loaded into the system domain, which only root can change), .state (what docker ps prints), colima-start-fails; every call is appended to calls.log with the Docker context it ran with. The Colima VM is the directory vm in $RUNTIME_STUB: its files are under vm/files, /proc/sys/net/bridge exists under vm/files only while br_netfilter is loaded, and a sysctl is the file vm/sysctl/ (a bridge key reads 1 once the module is loaded, as the kernel's default, unless the file says otherwise). -STUB = """#!{python} -import os, sys -stub = os.environ["RUNTIME_STUB"] -name = os.path.basename(sys.argv[0]) -args = sys.argv[1:] -if name == "sudo": - # Does what sudo does for the role, which is to run the command as root: it marks the command with RUNTIME_ROOT, which the stand-in launchctl needs to change the system domain, and keeps its own calls out of calls.log. - with open(os.path.join(stub, "sudo.log"), "a") as sudo_log: - sudo_log.write(" ".join(args) + "\\n") - while args[0] != "/bin/sh": - args = args[1:] - os.environ["RUNTIME_ROOT"] = "1" - os.execv(args[0], args) -with open(os.path.join(stub, "calls.log"), "a") as log: - log.write(os.environ.get("DOCKER_CONTEXT", "-") + " " + name + " " + " ".join(args) + "\\n") -with open(os.path.join(stub, "colima-home.log"), "a") as homes: - homes.write(name + " " + " ".join(args) + " " + os.environ.get("COLIMA_HOME", "-") + "\\n") -def exists(file): - return os.path.exists(os.path.join(stub, file)) -def hang(): - # A program that never answers and does not die on SIGALRM, as a Go binary does not; with ignore-term it ignores TERM as well, so only KILL ends it. - import signal, time - signal.signal(signal.SIGALRM, signal.SIG_IGN) - if exists("ignore-term"): - signal.signal(signal.SIGTERM, signal.SIG_IGN) - with open(os.path.join(stub, "hung.pids"), "a") as pids: - pids.write(str(os.getpid()) + "\\n") - time.sleep(300) -def touch(file): - open(os.path.join(stub, file), "w").close() -def need_root(): - if os.environ.get("RUNTIME_ROOT") != "1": - sys.exit("launchctl: Operation not permitted while changing the system domain as a user") -if name == "docker" and args[:2] == ["context", "inspect"]: - # Read from the context file alone, so it answers with the daemon down. An empty context name or an unknown one is an error, as docker's is. - if args[-1] == "" or exists("context-unknown"): - sys.exit("context " + repr(args[-1]) + ": context not found") - if not exists("context-host"): - sys.exit("context inspect: no context-host file") - print(open(os.path.join(stub, "context-host")).read(), end="") -elif name == "docker": - if args[:1] == ["info"] and exists("docker-hangs"): - hang() - if args[:1] == ["info"] and exists("docker-exit"): - sys.exit(int(open(os.path.join(stub, "docker-exit")).read())) - if not exists("runtime-up") and args[:1] == ["info"] and exists("docker-answers-after"): - # A daemon that fails its first tries and then answers, as one that is restarting or a loaded host does. - counter = os.path.join(stub, "docker-info-failures") - seen = int(open(counter).read()) if os.path.exists(counter) else 0 - if seen >= int(open(os.path.join(stub, "docker-answers-after")).read()): - touch("runtime-up") - else: - open(counter, "w").write(str(seen + 1)) - if not exists("runtime-up"): - sys.exit("Cannot connect to the Docker daemon") - if args[0] == "info": - print("27.0.0") - elif args[0] == "ps": - container = args[args.index("--filter") + 1].removeprefix("name=^/").removesuffix("$") - if exists(container + ".state"): - print(open(os.path.join(stub, container + ".state")).read(), end="") - else: - sys.exit("unexpected docker call: " + " ".join(args)) -elif name == "colima" and args[0] == "ssh": - if exists("guest-hangs") and args[args.index("--") + 1:] == ["true"]: - hang() - if exists("guest-answers") and args[args.index("--") + 1:] == ["true"]: - sys.exit(0) - if not exists("runtime-up"): - sys.exit("colima: the VM is not running") - command = args[args.index("--") + 1:] - sudo = command[0] == "sudo" - if sudo: - command = command[1:] - vm = os.path.join(stub, "vm") - def vm_file(path): - return os.path.join(vm, "files", path.lstrip("/")) - def sysctl_file(key): - return os.path.join(vm, "sysctl", key) - if command[0] == "cat": - if not os.path.exists(vm_file(command[1])): - sys.exit("cat: " + command[1] + ": No such file or directory") - print(open(vm_file(command[1])).read(), end="") - elif command == ["uname", "-m"]: - # aarch64 unless a test says otherwise, as the VM of an Apple silicon Mac is. - print(open(os.path.join(vm, "arch")).read().strip() if os.path.exists(os.path.join(vm, "arch")) else "aarch64") - elif command[0] == "test" and command[1] == "-d": - sys.exit(0 if os.path.isdir(vm_file(command[2])) else 1) - elif command[0] == "sysctl" and command[1] == "-n": - if command[2].startswith("net.bridge.") and not os.path.isdir(vm_file("/proc/sys/net/bridge")): - sys.exit("sysctl: cannot stat /proc/sys/" + command[2].replace(".", "/") + ": No such file or directory") - print(open(sysctl_file(command[2])).read().strip() if os.path.exists(sysctl_file(command[2])) else "1") - elif sudo and command[0] == "sysctl" and command[1] == "-w": - key, value = command[2].split("=") - if key.startswith("net.bridge.") and not os.path.isdir(vm_file("/proc/sys/net/bridge")): - sys.exit("sysctl: cannot stat /proc/sys/" + key.replace(".", "/") + ": No such file or directory") - os.makedirs(os.path.dirname(sysctl_file(key)), exist_ok=True) - open(sysctl_file(key), "w").write(value) - elif sudo and command[0] == "modprobe": - if command[-1] != "br_netfilter": - sys.exit("modprobe: FATAL: Module " + command[-1] + " not found") - os.makedirs(vm_file("/proc/sys/net/bridge"), exist_ok=True) - elif command[0] == "dpkg-query": - installed = open(os.path.join(vm, "packages")).read().split() if os.path.exists(os.path.join(vm, "packages")) else [] - if command[-1] not in installed: - sys.exit("dpkg-query: no packages found matching " + command[-1]) - print("install ok installed", end="") - elif sudo and command[0] == "apt-get" and command[1] == "update": - os.makedirs(vm, exist_ok=True) - open(os.path.join(vm, "package-index"), "w").write("updated\\n") - elif sudo and command[0] == "apt-get" and command[1] == "install": - # A fresh VM has an empty package index: an install with no update before it fails as apt does. - if not os.path.exists(os.path.join(vm, "package-index")): - sys.exit("E: Unable to locate package " + command[-1]) - os.makedirs(vm, exist_ok=True) - open(os.path.join(vm, "packages"), "a").write(command[-1] + "\\n") - elif command[0] == "systemctl" and command[1] == "is-active": - active = open(os.path.join(vm, "active-units")).read().split() if os.path.exists(os.path.join(vm, "active-units")) else [] - print("active" if command[2] in active else "inactive") - sys.exit(0 if command[2] in active else 3) - elif sudo and command[0] == "systemctl" and command[1] == "daemon-reload": - pass - elif sudo and command[0] == "systemctl" and command[1:3] == ["enable", "--now"]: - os.makedirs(vm, exist_ok=True) - open(os.path.join(vm, "active-units"), "a").write(command[3] + "\\n") - elif sudo and command[0] == "chmod": - os.chmod(vm_file(command[2]), int(command[1], 8)) - elif sudo and command[0] == "tee": - os.makedirs(os.path.dirname(vm_file(command[1])), exist_ok=True) - content = sys.stdin.read() - open(vm_file(command[1]), "w").write(content) - print(content, end="") - else: - sys.exit("unexpected colima ssh call: " + " ".join(command)) -elif name == "colima" and args[0] == "list": - # One JSON object per profile, whatever profile is asked for: this host has the profile the test names and another one beside it, which is always running. - profile = os.environ.get("RUNTIME_PROFILE", "default") - print('{{"name":"other","status":"Running","runtime":"docker"}}') - print('{{"name":"' + profile + '","status":"' + ("Running" if exists("colima-listed-running") else "Stopped") + '","runtime":"docker"}}') -elif name == "colima" and args[0] == "stop": - if args[:3] != ["stop", "--profile", os.environ.get("RUNTIME_PROFILE", "default")] or args[3:] not in ([], ["--force"]): - sys.exit("unexpected colima stop call: " + " ".join(args)) - if args[3:] == [] and exists("clean-stop-hangs"): - hang() - if args[3:] == [] and exists("clean-stop-fails"): - sys.exit("colima: the VM does not stop") - for file in ("colima-listed-running", "runtime-up", "docker-hangs", "guest-hangs", "docker-exit"): - if exists(file): - os.remove(os.path.join(stub, file)) -elif name == "colima": - if args[0] != "start" or args[-1] != "--activate=false": - sys.exit("unexpected colima call: " + " ".join(args)) - if exists("colima-start-fails"): - sys.exit("colima: the VM did not start") - # Starting a profile Colima already lists as running does nothing, so a wedged VM stays wedged. - if not exists("colima-listed-running"): - touch("colima-listed-running") - touch("runtime-up") - # A VM that is started again answers. - for file in ("docker-hangs", "guest-hangs", "docker-exit"): - if exists(file): - os.remove(os.path.join(stub, file)) -elif name == "ps": - # The host agent as ps shows it, from the file agent-ps (" "); a pid that is not running prints nothing and fails. - if not exists("agent-ps"): - sys.exit(1) - print(open(os.path.join(stub, "agent-ps")).read(), end="") -elif name == "launchctl": - system = args[1] == "system" or args[1].startswith("system/") - # Each job is loaded or not on its own: the watchdog's has a flag of its own beside the start job's. - def flag(target): - return ("watchdog-" if "watchdog" in target else "") + ("daemon-loaded" if system else "loaded") - if args[0] == "print": - sys.exit(0 if exists(flag(args[1]) if system or args[1].count("/") == 2 else "session") else 113) - elif args[0] == "bootstrap": - if not os.path.exists(args[2]): - sys.exit("Bootstrap failed: no such plist") - if system: - need_root() - touch(flag(args[2])) - elif args[0] == "bootout": - if system: - need_root() - os.remove(os.path.join(stub, flag(args[1]))) - else: - sys.exit("unexpected launchctl call: " + " ".join(args)) -elif name == "plutil": - if args[0] != "-lint" or b" str | None: - """Return the name of the task whose header last precedes a "fatal:" line in ansible-playbook's output, or None when nothing failed.""" - task = None - for line in stdout.splitlines(): - header = re.match(r"TASK \[(?:[^:\]]+ : )?(.*)\] \*+$", line) - if header: - task = header.group(1) - elif line.startswith("fatal: "): - return task - return None - - class BoundedRunTest(unittest.TestCase): """files/run_bounded.pl, which gives probes, the guest command and the clean stop a deadline that holds whatever the command does with signals.""" @@ -622,1072 +395,5 @@ def test_a_command_that_cannot_be_started_exits_127(self) -> None: self.assertEqual(result.returncode, 127) -@unittest.skipIf(shutil.which(ANSIBLE_PLAYBOOK) is None, "ansible-playbook is not installed") -class RoleTest(unittest.TestCase): - def setUp(self) -> None: - self.work = Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, self.work) - self.stub = self.work / "stub" - self.home = self.work / "home" - self.stub.mkdir() - self.home.mkdir() - self.bin = self.work / "bin" - self.bin.mkdir() - for name in ("docker", "colima", "launchctl", "plutil", "sudo", "ps"): - tool = self.bin / name - tool.write_text(STUB.format(python=sys.executable)) - tool.chmod(0o755) - self.plist = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima.default.plist" - # Stands in for /Library/LaunchDaemons, which exists on every Mac; the role's own path is narrowed to it below. - self.daemons = self.work / "LaunchDaemons" - self.daemons.mkdir() - # What `docker ps` prints for the node's container once the runtime answers; the end checks need it running. - (self.stub / "github-runner-k3s.state").write_text("running") - - def state(self, *flags: str) -> None: - for flag in flags: - (self.stub / flag).write_text("") - - def run_role(self, *extra: str, tasks: str = "runtime,end_checks", context: str = "colima", context_host: str | None = None, system: str = "Darwin", **variables: Any) -> subprocess.CompletedProcess[str]: - # The endpoint Colima gives its profile's context: the profile's socket in the default home, unless a test says where else. - profile = context.removeprefix("colima-") if context.startswith("colima-") else "default" - (self.stub / "context-host").write_text(context_host if context_host is not None else f"unix://{self.home}/.colima/{profile}/docker.sock") - host = { - "runtime_system": system, - "runtime_uid": UID, - "runtime_home": str(self.home), - "runtime_tasks": tasks, - "github_runner_cluster_docker_cli_context": context, - "github_runner_cluster_docker_cli_environment": {"DOCKER_CONTEXT": context} if context else {}, - "github_runner_cluster_docker_role": "server", - "github_runner_cluster_runtime_path": f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin", - # The tests are not root, so the daemon's property list is owned by the user running them and sits beside the stand-in daemon directory. - "runtime_user": "example", - "github_runner_cluster_runtime_daemon_plist": f"{self.daemons}/{{{{ github_runner_cluster_runtime_launchd_label }}}}.plist", - "github_runner_cluster_runtime_daemon_owner": pwd.getpwuid(os.getuid()).pw_name, - "github_runner_cluster_runtime_daemon_group": grp.getgrgid(os.getgid()).gr_name, - "github_runner_cluster_runtime_watchdog_daemon_plist": f"{self.daemons}/{{{{ github_runner_cluster_runtime_watchdog_label }}}}.plist", - # Off unless a test turns it on, so that the exact launchctl calls the tests of the start job assert are the start job's alone. - "github_runner_cluster_runtime_watchdog": False, - **variables, - } - inventory = self.work / "inventory.yml" - inventory.write_text(yaml.safe_dump({"all": {"hosts": {"node1": host}}})) - # The stand-ins come first on the playbook's own PATH as well as the tasks', so a tool a task runs without the role's PATH still cannot reach this machine's real launchd, Colima or Docker. - env = ansible_env() | {"RUNTIME_STUB": str(self.stub), "RUNTIME_PROFILE": profile, "PATH": f"{self.bin}{os.pathsep}{os.environ['PATH']}"} - return subprocess.run([ANSIBLE_PLAYBOOK, "-i", str(inventory), str(RUN), *extra], capture_output=True, text=True, check=False, env=env, cwd=self.work) - - def calls(self) -> list[str]: - log = self.stub / "calls.log" - return log.read_text().splitlines() if log.exists() else [] - - def colima_homes(self) -> list[str]: - """The COLIMA_HOME (`-` for none) of every colima call, as ` ` lines.""" - log = self.stub / "colima-home.log" - return [line.removeprefix("colima ") for line in log.read_text().splitlines() if line.startswith("colima ")] if log.exists() else [] - - def assert_colima_ran_in(self, home: str) -> None: - """Every colima call (the start and the VM's kernel settings alike) ran with `home`, and the start was among them.""" - homes = self.colima_homes() - self.assertTrue(any(line.startswith("start ") for line in homes), homes) - self.assertEqual([line for line in homes if not line.endswith(f" {home}")], []) - - def changes(self) -> list[str]: - return [call for call in self.calls() if re.match(r"\S+ (colima start|launchctl (bootstrap|bootout))", call)] - - def vm_changes(self) -> list[str]: - """The commands run as root in the Colima VM, in order, without the colima ssh prefix.""" - return [command for command in self.vm_calls() if not self.is_route_guard(command)] - - def vm_calls(self) -> list[str]: - return [match.group(1) for call in self.calls() if (match := re.match(r"\S+ colima ssh --profile \S+ -- (sudo .*)", call))] - - @staticmethod - def is_route_guard(command: str) -> bool: - return "route-guard" in command or "systemctl" in command or "iputils-ping" in command or "apt-get update" in command - - def route_guard_changes(self) -> list[str]: - """The commands that install the route guard in the VM, in order.""" - return [command for command in self.vm_calls() if self.is_route_guard(command)] - - def vm_file(self, path: str) -> Path: - return self.stub / "vm" / "files" / path.lstrip("/") - - def recap(self, result: subprocess.CompletedProcess[str]) -> dict[str, int]: - match = re.search(r"node1\s+: ok=(\d+)\s+changed=(\d+)\s+unreachable=(\d+)\s+failed=(\d+)", result.stdout) - assert match is not None, result.stdout + result.stderr - return dict(zip(("ok", "changed", "unreachable", "failed"), map(int, match.groups()))) - - def test_a_stopped_colima_is_started_and_the_agent_installed_and_loaded(self) -> None: - self.state("session") - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), ["colima colima start --profile default --activate=false".replace("colima colima", "colima colima"), f"colima launchctl bootstrap gui/{UID} {self.plist}"]) - self.assertEqual(plistlib.loads(self.plist.read_bytes())["ProgramArguments"][3:5], ["--profile", "default"]) - self.assertEqual(self.plist.stat().st_mode & 0o777, 0o644) - self.assertTrue((self.stub / "loaded").exists()) - - # A profile Colima lists as running while its runtime does not answer. - - FAST = {"github_runner_cluster_runtime_probe_attempts": 3, "github_runner_cluster_runtime_probe_delay": 0, "github_runner_cluster_runtime_probe_timeout": 5} - - def forget(self) -> None: - """Start a sub-case from a clean stub directory and a clean home.""" - for entry in self.stub.iterdir(): - if entry.is_dir(): - shutil.rmtree(entry) - elif entry.name not in ("context-host", "github-runner-k3s.state"): - entry.unlink() - shutil.rmtree(self.home / ".colima", ignore_errors=True) - - def stops(self) -> list[str]: - return [call for call in self.calls() if re.match(r"\S+ colima stop", call)] - - def starts(self) -> list[str]: - return [call for call in self.calls() if re.match(r"\S+ colima start", call)] - - AGENT = "/usr/local/bin/limactl hostagent --pidfile /example/ha.pid --socket /example/ha.sock" - - @staticmethod - def etime(seconds: int) -> str: - """ps's elapsed time, [[days-]hours:]minutes:seconds.""" - days, rest = divmod(seconds, 86400) - hours, rest = divmod(rest, 3600) - minutes, secs = divmod(rest, 60) - return (f"{days}-" if days else "") + (f"{hours:02d}:" if days or hours else "") + f"{minutes:02d}:{secs:02d}" - - def listed_running(self, agent_age: int | None = 7200, command: str | None = None, stale_file: bool = False) -> None: - """A VM Colima lists as running whose Docker daemon is silent, with a live host agent that has run for `agent_age` seconds (None for no pid file at all). `stale_file` leaves a pid file that is old but names no running process, as one from before a reboot does; `command` is what the process runs.""" - self.state("session", "colima-listed-running") - if agent_age is None: - return - pid = self.home / ".colima" / "_lima" / "colima" / "ha.pid" - pid.parent.mkdir(parents=True, exist_ok=True) - pid.write_text("4242\n") - old = time.time() - 7 * 86400 - os.utime(pid, (old, old)) - if not stale_file: - (self.stub / "agent-ps").write_text(f"{self.etime(agent_age)} {command or self.AGENT}\n") - - def hung_pids(self) -> list[int]: - log = self.stub / "hung.pids" - return [int(line) for line in log.read_text().split()] if log.exists() else [] - - def assert_all_ended(self) -> None: - for pid in self.hung_pids(): - for _ in range(50): - try: - os.kill(pid, 0) - except ProcessLookupError: - break - time.sleep(0.1) - else: - self.fail(f"the hung stand-in {pid} is still running") - - def info_calls(self) -> list[str]: - return [call for call in self.calls() if re.match(r"\S+ docker info", call)] - - def test_a_vm_whose_runtime_stays_silent_and_whose_guest_and_agent_confirm_it_is_stopped_cleanly_and_started_again(self) -> None: - self.listed_running() - result = self.run_role(**self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), ["colima colima stop --profile default"]) - self.assertEqual(self.starts(), ["colima colima start --profile default --activate=false"]) - self.assertLess(self.calls().index(self.stops()[0]), self.calls().index(self.starts()[0])) - # The first probe and every further try. - self.assertGreaterEqual(len(self.info_calls()), 4) - self.assertTrue((self.stub / "runtime-up").exists()) - - def test_a_clean_stop_that_fails_is_followed_by_a_forced_one(self) -> None: - self.listed_running() - self.state("clean-stop-fails") - result = self.run_role(**self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), ["colima colima stop --profile default", "colima colima stop --profile default --force"]) - self.assertEqual(len(self.starts()), 1) - - def test_only_the_hosts_own_profile_is_stopped_while_another_listed_profile_runs(self) -> None: - self.listed_running() - self.run_role(**self.FAST) - self.assertEqual([call for call in self.stops() if "--profile other" in call], []) - self.assertTrue(self.stops()) - - def test_a_daemon_that_answers_on_a_later_try_is_never_stopped(self) -> None: - # The first probe and one further try fail, as on a loaded host or while dockerd restarts, and the next answers. - self.listed_running() - (self.stub / "docker-answers-after").write_text("2") - result = self.run_role(**self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), []) - self.assertEqual(self.starts(), []) - - def assert_left_alone(self, result: subprocess.CompletedProcess[str], *words: str) -> None: - self.assertNotEqual(result.returncode, 0, result.stdout) - self.assertEqual(failed_task(result.stdout), "Fail where the VM is not shown to be wedged or the stop is off") - self.assertEqual(self.stops(), []) - self.assertEqual(self.starts(), []) - self.assertIn("colima stop --profile default --force", result.stdout, "the recovery by hand is named") - for word in words: - self.assertIn(word, result.stdout) - - def test_a_guest_that_answers_a_command_is_left_alone_although_docker_is_silent(self) -> None: - self.listed_running() - self.state("guest-answers") - self.assert_left_alone(self.run_role(**self.FAST), "a command in the guest succeeded") - - def test_a_vm_whose_agent_started_moments_ago_is_left_alone_however_old_its_pid_file_is(self) -> None: - # The pid file is a week old, from a boot long gone, and the process it names started thirty seconds ago. - self.listed_running(agent_age=30) - self.assert_left_alone(self.run_role(**self.FAST), "for less than 600 seconds") - - def test_a_pid_file_naming_no_running_process_leaves_the_age_unknown_and_nothing_is_stopped(self) -> None: - # An old pid file whose process is gone, as after a reboot: its date says the agent is old, and that must not count. - self.listed_running(stale_file=True) - self.assert_left_alone(self.run_role(**self.FAST), "could not be read") - - def test_a_pid_file_naming_another_program_leaves_the_age_unknown(self) -> None: - self.listed_running(command="/usr/sbin/cron -f") - self.assert_left_alone(self.run_role(**self.FAST), "could not be read") - - def test_a_pid_file_naming_a_program_whose_path_merely_contains_hostagent_leaves_the_age_unknown(self) -> None: - self.listed_running(command="/opt/hostagent/bin/cron -f") - self.assert_left_alone(self.run_role(**self.FAST), "could not be read") - - def test_a_report_of_an_old_agent_does_not_say_ago_twice(self) -> None: - self.listed_running(command="/usr/local/bin/limactl hostagent x", agent_age=7200) - self.state("guest-answers") - result = self.run_role(**self.FAST) - self.assertIn("for more than 600 seconds;", result.stdout) - self.assertNotIn("seconds ago", result.stdout) - - # The Docker context, which the stop reads for its socket check on its own. - - def test_a_host_that_names_its_colima_home_and_has_no_readable_context_still_runs(self) -> None: - # The README's route for a host whose context does not say where the profile is (DOCKER_HOST, say): the variable gives the home and the context cannot be read. Nothing is listed as running, so the play starts the profile as before. - for label, variables in (("an empty context", {"context": ""}), ("an unknown context", {})): - with self.subTest(label=label): - self.forget() - self.state("session") - if not variables: - self.state("context-unknown") - result = self.run_role(github_runner_cluster_colima_home="/elsewhere", github_runner_cluster_runtime="colima", **variables) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assert_colima_ran_in("/elsewhere") - self.assertEqual(self.stops(), []) - - def test_a_context_that_cannot_be_read_never_leads_to_a_stop_and_the_report_says_so(self) -> None: - for label, variables in (("an empty context", {"context": ""}), ("an unknown context", {"unknown": True})): - with self.subTest(label=label): - self.forget() - self.listed_running() - if variables.get("unknown"): - self.state("context-unknown") - result = self.run_role(github_runner_cluster_colima_home=f"{self.home}/.colima", github_runner_cluster_runtime="colima", **{k: v for k, v in variables.items() if k != "unknown"}, **self.FAST) - self.assert_left_alone(result, "so its socket is not proven to belong to the profile") - - def test_a_context_whose_endpoint_is_another_runtime_never_leads_to_a_stop(self) -> None: - for endpoint in ("tcp://remote.example.invalid:2375", "unix:///var/run/docker.sock"): - with self.subTest(endpoint=endpoint): - self.forget() - self.listed_running() - result = self.run_role(context_host=endpoint, github_runner_cluster_colima_home=f"{self.home}/.colima", **self.FAST) - self.assert_left_alone(result, "does not point at the socket of the profile") - - # The supervisor failing is not a failed probe. - - def test_a_supervisor_that_cannot_run_the_command_fails_the_run_naming_it_and_is_not_evidence(self) -> None: - for code in (127, 255): - with self.subTest(code=code): - self.forget() - self.listed_running() - (self.stub / "docker-exit").write_text(str(code)) - result = self.run_role(**self.FAST) - self.assertNotEqual(result.returncode, 0, result.stdout) - self.assertIn("run_bounded.pl", result.stdout) - self.assertEqual(self.stops(), []) - - def test_a_host_without_perl_fails_the_run_naming_the_supervisor(self) -> None: - self.listed_running() - result = self.run_role(github_runner_cluster_runtime_path=str(self.bin), **self.FAST) - self.assertNotEqual(result.returncode, 0, result.stdout) - self.assertIn("run_bounded.pl", result.stdout) - self.assertEqual(self.stops(), []) - - def test_a_perl_that_is_not_executable_fails_the_run_naming_the_supervisor(self) -> None: - # The command module reports this with the OS error number as its rc (13), not 2: the message identifies it. - self.listed_running() - perl_dir = self.work / "no-perl" - perl_dir.mkdir() - (perl_dir / "perl").write_text("#!/bin/sh\n") - (perl_dir / "perl").chmod(0o644) - result = self.run_role(github_runner_cluster_runtime_path=f"{perl_dir}{os.pathsep}{self.bin}", **self.FAST) - self.assertNotEqual(result.returncode, 0, result.stdout) - self.assertIn("run_bounded.pl", result.stdout) - self.assertEqual(self.stops(), []) - - def test_a_tool_that_fails_by_itself_still_counts_as_a_failed_probe(self) -> None: - # docker exiting 1 (cannot connect) is the daemon's answer, not the supervisor's. - self.listed_running() - (self.stub / "docker-exit").write_text("1") - result = self.run_role(**self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(len(self.stops()), 1) - - def test_an_agent_that_has_run_for_days_counts_as_old(self) -> None: - self.listed_running(agent_age=3 * 86400 + 3600 + 61) - result = self.run_role(**self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(len(self.stops()), 1) - - def test_an_agent_whose_age_cannot_be_read_does_not_count_as_old(self) -> None: - self.listed_running(agent_age=None) - self.assert_left_alone(self.run_role(**self.FAST), "could not be read") - - def test_a_colima_home_that_is_not_where_the_context_points_never_leads_to_a_stop(self) -> None: - # The variable names another Colima home than the one the Docker context's socket is in: the probes measured one runtime and a stop would act on another's profile. (A context whose endpoint is no Colima socket at all fails earlier, in the filter that reads the home from it.) - self.listed_running() - result = self.run_role(github_runner_cluster_colima_home="/elsewhere", **self.FAST) - self.assert_left_alone(result, "does not point at the socket of the profile") - - def test_with_the_stop_switched_off_a_confirmed_wedge_fails_naming_the_switch(self) -> None: - self.listed_running() - self.assert_left_alone(self.run_role(github_runner_cluster_runtime_force_stop_wedged=False, **self.FAST), "github_runner_cluster_runtime_force_stop_wedged is off") - - def test_the_stop_switch_is_independent_of_autostart(self) -> None: - self.listed_running() - result = self.run_role(github_runner_cluster_runtime_force_stop_wedged=False, github_runner_cluster_runtime_autostart=True, **self.FAST) - self.assertNotEqual(result.returncode, 0) - self.assertEqual(self.stops(), []) - - def test_a_second_run_after_the_recovery_stops_and_starts_nothing(self) -> None: - self.listed_running() - self.run_role(**self.FAST) - before = len(self.calls()) - result = self.run_role(**self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([call for call in self.calls()[before:] if re.match(r"\S+ colima (stop|start)", call)], []) - - def test_a_stopped_profile_is_started_without_being_stopped_first(self) -> None: - self.state("session") - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), []) - - def test_a_running_runtime_is_neither_listed_nor_stopped(self) -> None: - self.state("session", "runtime-up", "colima-listed-running") - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), []) - self.assertEqual([call for call in self.calls() if re.match(r"\S+ colima list", call)], []) - - HANG = {"github_runner_cluster_runtime_probe_attempts": 2, "github_runner_cluster_runtime_probe_delay": 0, "github_runner_cluster_runtime_probe_timeout": 2, "github_runner_cluster_runtime_kill_grace": 1, "github_runner_cluster_runtime_clean_stop_timeout": 2} - - def test_probes_that_never_reply_and_ignore_sigalrm_are_ended_and_the_vm_is_stopped_and_started(self) -> None: - # docker info and the guest command never reply and ignore SIGALRM, as Go programs do; the clean stop never ends and ignores TERM too. - self.listed_running() - self.state("docker-hangs", "guest-hangs", "clean-stop-hangs", "ignore-term") - began = time.monotonic() - result = self.run_role(**self.HANG) - elapsed = time.monotonic() - began - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), ["colima colima stop --profile default", "colima colima stop --profile default --force"]) - self.assertEqual(len(self.starts()), 1) - # Unbounded, each stand-in sleeps for 300 seconds. - self.assertLess(elapsed, 120) - self.assertGreaterEqual(len(self.hung_pids()), 5) - self.assert_all_ended() - - def test_a_hung_docker_with_a_guest_that_answers_fails_the_run_within_the_bound_and_stops_nothing(self) -> None: - self.listed_running() - self.state("docker-hangs", "guest-answers") - began = time.monotonic() - result = self.run_role(**self.HANG) - self.assertLess(time.monotonic() - began, 120) - self.assert_left_alone(result, "a command in the guest succeeded") - self.assert_all_ended() - - def test_a_hung_first_probe_counts_as_the_runtime_not_answering(self) -> None: - # A stopped profile whose Docker socket accepts and never replies: the start follows, as for a socket that refuses. - self.state("session", "docker-hangs") - began = time.monotonic() - result = self.run_role(**self.HANG) - self.assertLess(time.monotonic() - began, 120) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(len(self.starts()), 1) - self.assert_all_ended() - - def test_check_mode_reads_everything_stops_nothing_and_says_what_a_real_run_would_do(self) -> None: - self.listed_running() - result = self.run_role("--check", **self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), []) - self.assertTrue((self.stub / "colima-listed-running").exists()) - self.assertIn("A real run would stop the profile", result.stdout) - - def test_check_mode_on_a_vm_that_is_not_shown_to_be_wedged_says_nothing_would_be_stopped(self) -> None: - self.listed_running() - self.state("guest-answers") - result = self.run_role("--check", **self.FAST) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.stops(), []) - self.assertIn("A real run would stop nothing and fail here", result.stdout) - - def test_every_docker_call_uses_the_hosts_docker_context(self) -> None: - self.state("session") - self.run_role(context="colima-example") - docker_calls = [call for call in self.calls() if " docker " in call] - self.assertTrue(docker_calls) - self.assertTrue(all(call.startswith("colima-example ") for call in docker_calls), docker_calls) - self.assertIn("colima-example colima start --profile example --activate=false", self.calls()) - - def test_a_profile_in_a_home_of_its_own_is_started_and_loaded_with_that_home(self) -> None: - # The bridged node profile: context colima-node, profile node, in ~/.colima-node. Without COLIMA_HOME colima would start a new profile of that name in ~/.colima. A login agent is chosen here, since the node profile is started at boot by default. - self.state("session") - node_home = f"{self.home}/.colima-node" - result = self.run_role(context="colima-node", context_host=f"unix://{node_home}/node/docker.sock", github_runner_cluster_runtime_autostart_at="login") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assert_colima_ran_in(node_home) - agent = plistlib.loads(self.home.joinpath("Library/LaunchAgents/com.exadev.github-runner.colima.node.plist").read_bytes()) - self.assertEqual(agent["EnvironmentVariables"]["COLIMA_HOME"], node_home) - self.assertEqual(agent["ProgramArguments"][3:6], ["--profile", "node", "--activate=false"]) - self.assertEqual(list(self.daemons.iterdir()), []) - - LABEL = "com.exadev.github-runner.colima.node" - - @property - def node_home(self) -> str: - return f"{self.home}/.colima-node" - - @property - def node_daemon(self) -> Path: - return self.daemons / f"{self.LABEL}.plist" - - @property - def node_agent(self) -> Path: - return self.home / "Library" / "LaunchAgents" / f"{self.LABEL}.plist" - - def run_node(self, *extra: str, **variables: Any) -> subprocess.CompletedProcess[str]: - """Run the role for the bridged node profile (context colima-node, in ~/.colima-node), which is started at boot.""" - return self.run_role(*extra, context="colima-node", context_host=f"unix://{self.node_home}/node/docker.sock", **variables) - - def v2_19_agent(self) -> None: - """A host the previous release set up: the node profile's login agent installed, and loaded when the user has a session.""" - self.node_agent.parent.mkdir(parents=True) - self.node_agent.write_text("") - if (self.stub / "session").exists(): - self.state("loaded") - - def system_calls(self) -> list[str]: - """The launchctl calls that change the system domain, which the stand-in refuses without root.""" - return [call for call in self.calls() if re.search(r"launchctl (bootstrap|bootout) system", call)] - - def test_the_node_profile_is_started_by_a_daemon_at_boot_with_nobody_logged_in(self) -> None: - # The state of a Mac that has rebooted to the login window: no session, so no gui domain to load an agent into. - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), ["colima-node colima start --profile node --activate=false", f"colima-node launchctl bootstrap system {self.node_daemon}"]) - daemon = plistlib.loads(self.node_daemon.read_bytes()) - self.assertEqual((daemon["Label"], daemon["UserName"], daemon["RunAtLoad"]), (self.LABEL, "example", True)) - self.assertEqual(daemon["EnvironmentVariables"], {"PATH": f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin", "HOME": str(self.home), "COLIMA_HOME": self.node_home}) - self.assertEqual(self.node_daemon.stat().st_mode & 0o777, 0o644) - self.assertTrue((self.stub / "daemon-loaded").exists()) - self.assertFalse(self.node_agent.exists()) - self.assertFalse((self.home / "Library" / "LaunchAgents").exists()) - self.assertNotIn("loads at the next login", result.stdout) - - def test_the_daemon_is_written_and_loaded_as_root_and_nothing_else_is(self) -> None: - self.run_node() - sudo = (self.stub / "sudo.log").read_text().splitlines() - self.assertTrue(any(f"{self.LABEL}.plist" in line or "ansible" in line for line in sudo), sudo) - # The stand-in launchctl refuses the system domain without root, and the run passed, so the load and any unload went through sudo; the read-only calls and the colima start did not need it. - self.assertEqual(len(self.system_calls()), 1) - - def test_the_daemon_is_also_installed_for_a_user_with_a_login_session_and_the_agent_never_is(self) -> None: - self.state("session") - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes()[-1], f"colima-node launchctl bootstrap system {self.node_daemon}") - self.assertFalse((self.stub / "loaded").exists()) - self.assertEqual([call for call in self.calls() if "gui/" in call], []) - - def test_a_running_node_profile_is_not_started_again_when_the_daemon_is_installed(self) -> None: - self.state("runtime-up") - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), [f"colima-node launchctl bootstrap system {self.node_daemon}"]) - - def test_a_host_the_previous_release_set_up_moves_from_the_agent_to_the_daemon(self) -> None: - self.state("session", "runtime-up") - self.v2_19_agent() - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), [f"colima-node launchctl bootstrap system {self.node_daemon}", f"colima-node launchctl bootout gui/{UID}/{self.LABEL}"]) - self.assertFalse(self.node_agent.exists()) - self.assertFalse((self.stub / "loaded").exists()) - self.assertTrue((self.stub / "daemon-loaded").exists()) - self.assertTrue(self.node_daemon.exists()) - - def test_an_agent_that_was_never_loaded_because_nobody_logged_in_is_only_deleted(self) -> None: - # What m1 looked like after its reboot: the agent file on disk, the login window up. - self.state("runtime-up") - self.v2_19_agent() - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertFalse(self.node_agent.exists()) - self.assertEqual([call for call in self.calls() if "gui/" in call and "launchctl print gui/" not in call], []) - self.assertEqual(self.changes(), [f"colima-node launchctl bootstrap system {self.node_daemon}"]) - - def test_the_agent_of_another_profile_is_left_alone(self) -> None: - self.state("session", "runtime-up") - other = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima.default.plist" - other.parent.mkdir(parents=True) - other.write_text("") - self.run_node() - self.assertEqual(other.read_text(), "") - - def test_a_second_run_with_the_daemon_in_place_changes_nothing_and_loads_nothing(self) -> None: - self.state("runtime-up") - self.run_node() - before = self.calls() - sudo_before = (self.stub / "sudo.log").read_text() - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.recap(result)["changed"], 0, result.stdout) - self.assertEqual([call for call in self.calls()[len(before):] if not re.match(r"\S+ (docker (info|ps|context inspect)|launchctl print |colima ssh --profile \S+ -- (cat|test|uname|sysctl -n|systemctl is-active|dpkg-query) )", call)], []) - # The template runs as root to compare ownership; it is the only thing that does, and it changes nothing. - self.assertEqual(self.system_calls(), [call for call in before if "launchctl bootstrap system" in call]) - self.assertTrue((self.stub / "sudo.log").read_text().startswith(sudo_before)) - - def test_a_changed_daemon_is_unloaded_before_it_is_loaded_again(self) -> None: - self.state("runtime-up") - self.run_node() - self.node_daemon.write_text(self.node_daemon.read_text().replace("start", "stop")) - before = len(self.changes()) - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes()[before:], [f"colima-node launchctl bootout system/{self.LABEL}", f"colima-node launchctl bootstrap system {self.node_daemon}"]) - self.assertIn("start", self.node_daemon.read_text()) - - def test_a_daemon_that_is_in_place_but_not_loaded_is_loaded(self) -> None: - self.state("runtime-up") - self.run_node() - (self.stub / "daemon-loaded").unlink() - result = self.run_node() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes()[-1], f"colima-node launchctl bootstrap system {self.node_daemon}") - - def test_check_mode_installs_and_loads_nothing_and_removes_nothing(self) -> None: - self.state("session", "runtime-up") - self.v2_19_agent() - result = self.run_node("--check", "--diff") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), []) - self.assertFalse(self.node_daemon.exists()) - self.assertTrue(self.node_agent.exists()) - self.assertIn("UserName", result.stdout, "the diff shows the daemon's property list") - self.assertGreater(self.recap(result)["changed"], 0) - - def test_a_host_set_back_to_login_retires_the_daemon(self) -> None: - self.state("session", "runtime-up") - self.run_node() - result = self.run_node(github_runner_cluster_runtime_autostart_at="login") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes()[-2:], [f"colima-node launchctl bootstrap gui/{UID} {self.node_agent}", f"colima-node launchctl bootout system/{self.LABEL}"]) - self.assertFalse(self.node_daemon.exists()) - self.assertFalse((self.stub / "daemon-loaded").exists()) - self.assertTrue(self.node_agent.exists()) - - def test_a_host_can_ask_for_a_daemon_for_any_profile(self) -> None: - self.state("runtime-up") - result = self.run_role(github_runner_cluster_runtime_autostart_at="boot") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(plistlib.loads((self.daemons / "com.exadev.github-runner.colima.default.plist").read_bytes())["UserName"], "example") - self.assertFalse(self.plist.exists()) - - def test_a_value_that_is_not_a_choice_is_refused_before_anything_changes(self) -> None: - self.state("session") - result = self.run_node(github_runner_cluster_runtime_autostart_at="sometimes") - self.assertNotEqual(result.returncode, 0) - self.assertIn("must be auto, login or boot, not sometimes", result.stdout) - self.assertEqual(self.calls(), []) - - def test_the_default_profile_keeps_its_login_agent_and_never_touches_the_system_domain(self) -> None: - self.state("session") - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), ["colima colima start --profile default --activate=false", f"colima launchctl bootstrap gui/{UID} {self.plist}"]) - self.assertEqual(list(self.daemons.iterdir()), []) - self.assertFalse((self.stub / "sudo.log").exists()) - # The VM's own systemd units live under /etc/systemd/system, which is not launchd's system domain. - self.assertEqual([call for call in self.calls() if "system" in call and "colima ssh" not in call], []) - - def test_autostart_off_leaves_an_installed_daemon_and_agent_as_they_are(self) -> None: - self.state("runtime-up") - self.node_daemon.write_text("") - self.v2_19_agent() - result = self.run_node(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual((self.node_daemon.read_text(), self.node_agent.read_text()), ("", "")) - self.assertEqual(self.changes(), []) - - def test_the_variable_wins_over_the_context_and_the_context_is_not_read(self) -> None: - # A profile that is stopped never reaches the stop's own read of the context, so the home comes from the variable alone. - self.state("session") - result = self.run_role(context="colima-node", github_runner_cluster_colima_home="/elsewhere") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assert_colima_ran_in("/elsewhere") - self.assertFalse([call for call in self.calls() if " docker context " in call]) - - def test_a_profile_in_the_default_home_runs_with_no_variable(self) -> None: - self.state("session") - self.run_role() - self.assert_colima_ran_in("-") - self.assertNotIn("COLIMA_HOME", plistlib.loads(self.plist.read_bytes())["EnvironmentVariables"]) - - def test_a_context_that_is_not_the_profiles_socket_fails_before_anything_changes(self) -> None: - self.state("session") - result = self.run_role(context="colima-node", context_host="tcp://127.0.0.1:2375") - self.assertNotEqual(result.returncode, 0) - self.assertIn("set github_runner_cluster_colima_home", result.stdout) - self.assertEqual(self.changes(), []) - - def test_a_stopped_profile_in_a_home_of_its_own_is_started_under_check_mode_reading_only(self) -> None: - self.state("session") - result = self.run_role("--check", context="colima-node", context_host=f"unix://{self.home}/.colima-node/node/docker.sock") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), []) - - def test_docker_desktop_and_other_runtimes_read_no_context(self) -> None: - for context in ("desktop-linux", "orbstack"): - with self.subTest(context=context): - self.run_role(context=context) - self.assertFalse([call for call in self.calls() if " docker context " in call]) - - def assert_a_second_run_changes_nothing(self, context: str, context_host: str | None) -> None: - self.state("session") - self.run_role(context=context, context_host=context_host) - before = self.calls() - result = self.run_role(context=context, context_host=context_host) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.recap(result)["changed"], 0, result.stdout) - self.assertEqual([call for call in self.calls()[len(before) :] if not re.match(r"\S+ (docker (info|ps|context inspect)|launchctl print|colima ssh --profile \S+ -- (cat|test|uname|sysctl -n|systemctl is-active|dpkg-query) )", call)], []) - self.assertNotIn("bootstrap", " ".join(self.calls()[len(before) :])) - - def test_a_second_run_changes_nothing(self) -> None: - self.assert_a_second_run_changes_nothing("colima", None) - - def test_a_second_run_changes_nothing_for_a_profile_in_a_home_of_its_own(self) -> None: - self.assert_a_second_run_changes_nothing("colima-node", f"unix://{self.home}/.colima-node/node/docker.sock") - - def test_a_running_runtime_is_not_started_again_but_still_gets_the_agent(self) -> None: - self.state("session", "runtime-up") - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), [f"colima launchctl bootstrap gui/{UID} {self.plist}"]) - self.assertTrue(self.plist.exists()) - - def test_a_changed_definition_is_unloaded_before_it_is_loaded(self) -> None: - self.state("session") - self.run_role() - self.plist.write_text(self.plist.read_text().replace("start", "stop")) - before = len(self.changes()) - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes()[before:], [f"colima launchctl bootout gui/{UID}/com.exadev.github-runner.colima.default", f"colima launchctl bootstrap gui/{UID} {self.plist}"]) - self.assertIn("start", self.plist.read_text()) - - def test_without_a_login_session_the_agent_is_installed_and_left_for_the_next_login(self) -> None: - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertTrue(self.plist.exists()) - self.assertNotIn("bootstrap", " ".join(self.calls())) - self.assertIn("loads at the next login", result.stdout) - - def test_a_malformed_property_list_never_replaces_the_installed_one(self) -> None: - self.state("session") - self.run_role() - installed = self.plist.read_bytes() - (self.bin / "plutil").write_text("#!/bin/sh\nexit 1\n") - result = self.run_role("-e", "github_runner_cluster_runtime_path=" + f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin{os.pathsep}/changed") - self.assertNotEqual(result.returncode, 0) - self.assertEqual(self.plist.read_bytes(), installed) - - def test_a_colima_that_will_not_start_fails_the_run_at_that_task(self) -> None: - self.state("session", "colima-start-fails") - result = self.run_role() - self.assertNotEqual(result.returncode, 0) - self.assertEqual(failed_task(result.stdout), "Start the Colima profile if it is stopped") - self.assertFalse(self.plist.exists()) - - def test_autostart_off_installs_nothing_and_a_stopped_runtime_fails_with_the_fix(self) -> None: - self.state("session") - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertNotEqual(result.returncode, 0) - self.assertEqual(failed_task(result.stdout), "Fail unless the container runtime is up") - self.assertIn("Colima profile default is not running on node1. Start it with `colima start --profile default`", result.stdout) - self.assertEqual(self.changes(), []) - self.assertFalse(self.plist.exists()) - - def test_autostart_off_with_a_running_runtime_passes(self) -> None: - self.state("runtime-up") - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), []) - - def test_docker_desktop_is_never_started_and_a_stopped_one_says_which_setting_to_turn_on(self) -> None: - self.state("session") - result = self.run_role(context="desktop-linux") - self.assertNotEqual(result.returncode, 0) - self.assertIn("Docker Desktop is not running on node1, and this role cannot start it", result.stdout) - self.assertIn("Settings > General > Start Docker Desktop when you sign in to your computer", result.stdout) - self.assertEqual(self.changes(), []) - self.assertFalse(self.plist.parent.exists()) - - def test_a_running_docker_desktop_installs_nothing(self) -> None: - self.state("session", "runtime-up") - result = self.run_role(context="desktop-linux") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), []) - self.assertFalse(self.plist.parent.exists()) - - def test_another_runtime_is_only_checked(self) -> None: - result = self.run_role(context="orbstack") - self.assertNotEqual(result.returncode, 0) - self.assertIn("The container runtime is not running on node1", result.stdout) - self.assertEqual(self.changes(), []) - - def test_a_linux_host_is_not_touched(self) -> None: - result = self.run_role(system="Linux") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.calls(), []) - self.assertFalse((self.home / "Library").exists()) - - def test_check_mode_starts_and_installs_nothing_and_does_not_fail_on_a_stopped_runtime(self) -> None: - self.state("session") - result = self.run_role("--check", "--diff") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), []) - self.assertFalse(self.plist.exists()) - self.assertIn("com.exadev.github-runner.colima.default", result.stdout, "the diff shows the property list") - - def test_check_mode_reports_a_changed_definition(self) -> None: - self.state("session") - self.run_role() - self.plist.write_text(self.plist.read_text().replace("start", "stop")) - result = self.run_role("--check", "--diff") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertGreater(self.recap(result)["changed"], 0) - self.assertIn("stop", self.plist.read_text()) - - def test_a_colima_vm_without_the_module_gets_the_files_that_load_it_and_the_module(self) -> None: - self.state("runtime-up") - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.vm_changes(), [f"sudo tee {MODULES_FILE}", f"sudo tee {SYSCTL_FILE}", "sudo modprobe -- br_netfilter"]) - self.assertEqual(self.vm_file(MODULES_FILE).read_text().splitlines()[-1], "br_netfilter") - self.assertEqual(self.vm_file(SYSCTL_FILE).read_text().splitlines()[1:], ["net.bridge.bridge-nf-call-iptables = 1", "net.bridge.bridge-nf-call-ip6tables = 1"]) - self.assertTrue(self.vm_file("/proc/sys/net/bridge").is_dir()) - - def test_a_second_run_changes_nothing_in_the_vm(self) -> None: - self.state("runtime-up") - self.run_role(github_runner_cluster_runtime_autostart=False) - before = self.calls() - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.recap(result)["changed"], 0, result.stdout) - self.assertEqual([call for call in self.calls()[len(before) :] if " sudo " in call], []) - - def test_the_route_guard_is_installed_in_the_vm_with_its_timer_and_started(self) -> None: - script, unit = DEFAULTS["github_runner_cluster_colima_route_guard_script"], DEFAULTS["github_runner_cluster_colima_route_guard_unit"] - self.state("runtime-up") - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual( - self.route_guard_changes(), - ["sudo apt-get update", "sudo apt-get install -y --no-install-recommends iputils-ping", f"sudo tee {script}", f"sudo tee /etc/systemd/system/{unit}.service", f"sudo tee /etc/systemd/system/{unit}.timer", f"sudo chmod 0755 {script}", "sudo systemctl daemon-reload", f"sudo systemctl enable --now {unit}.timer"], - ) - self.assertEqual(self.vm_file(script).read_text().strip(), (ROLE / "files" / "route-guard.sh").read_text().strip()) - self.assertEqual(self.vm_file(script).stat().st_mode & 0o777, 0o755) - timer = self.vm_file(f"/etc/systemd/system/{unit}.timer").read_text() - self.assertIn(f"OnBootSec={DEFAULTS['github_runner_cluster_colima_route_guard_interval_seconds']}s", timer) - # systemd's default accuracy of a minute would let a tick slip far past the interval. - self.assertIn("AccuracySec=1s", timer) - self.assertIn(f"ExecStart={script}", self.vm_file(f"/etc/systemd/system/{unit}.service").read_text()) - - def test_a_second_run_leaves_the_route_guard_alone(self) -> None: - self.state("runtime-up") - self.run_role(github_runner_cluster_runtime_autostart=False) - before = len(self.route_guard_changes()) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.route_guard_changes()[before:], []) - - def test_a_stopped_route_guard_timer_is_started_again_without_rewriting_the_files(self) -> None: - unit = DEFAULTS["github_runner_cluster_colima_route_guard_unit"] - self.state("runtime-up") - self.run_role(github_runner_cluster_runtime_autostart=False) - (self.stub / "vm" / "active-units").write_text("") - before = len(self.route_guard_changes()) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.route_guard_changes()[before:], [f"sudo systemctl enable --now {unit}.timer"]) - - def test_a_changed_route_guard_script_is_rewritten_and_systemd_reloaded(self) -> None: - script = DEFAULTS["github_runner_cluster_colima_route_guard_script"] - self.state("runtime-up") - self.run_role(github_runner_cluster_runtime_autostart=False) - self.vm_file(script).write_text("#!/bin/sh\nexit 0\n") - before = len(self.route_guard_changes()) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.route_guard_changes()[before:], [f"sudo tee {script}", f"sudo chmod 0755 {script}", "sudo systemctl daemon-reload"]) - - def test_the_module_is_loaded_again_when_a_restarted_vm_has_lost_it_and_the_files_are_left_alone(self) -> None: - self.state("runtime-up") - self.run_role(github_runner_cluster_runtime_autostart=False) - shutil.rmtree(self.vm_file("/proc")) - before = len(self.vm_changes()) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.vm_changes()[before:], ["sudo modprobe -- br_netfilter"]) - - def test_a_loaded_module_is_not_loaded_again_but_the_files_are_still_written(self) -> None: - self.state("runtime-up") - self.vm_file("/proc/sys/net/bridge").mkdir(parents=True) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.vm_changes(), [f"sudo tee {MODULES_FILE}", f"sudo tee {SYSCTL_FILE}"]) - - def test_the_file_a_person_wrote_by_hand_is_replaced_by_the_managed_one(self) -> None: - self.state("runtime-up") - self.vm_file(MODULES_FILE).parent.mkdir(parents=True) - self.vm_file(MODULES_FILE).write_text("br_netfilter\n") - self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertIn(f"sudo tee {MODULES_FILE}", self.vm_changes()) - self.assertIn("Managed by the exadev.github_runner collection", self.vm_file(MODULES_FILE).read_text()) - - def test_a_bridge_sysctl_that_is_off_is_set_after_the_module_is_loaded(self) -> None: - self.state("runtime-up") - (self.stub / "vm" / "sysctl").mkdir(parents=True) - (self.stub / "vm" / "sysctl" / "net.bridge.bridge-nf-call-iptables").write_text("0") - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.vm_changes()[2:], ["sudo modprobe -- br_netfilter", "sudo sysctl -w net.bridge.bridge-nf-call-iptables=1"]) - - def test_the_vm_of_the_hosts_profile_is_the_one_prepared(self) -> None: - self.state("runtime-up") - self.run_role(context="colima-example", github_runner_cluster_runtime_autostart=False) - ssh_calls = [call for call in self.calls() if " colima ssh " in call] - self.assertTrue(ssh_calls) - self.assertTrue(all(call.startswith("colima-example colima ssh --profile example -- ") for call in ssh_calls), ssh_calls) - - def test_the_vm_is_prepared_with_the_agent_installed_as_well(self) -> None: - self.state("session") - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.changes(), ["colima colima start --profile default --activate=false", f"colima launchctl bootstrap gui/{UID} {self.plist}"]) - self.assertEqual(self.vm_changes()[-1], "sudo modprobe -- br_netfilter") - - def test_check_mode_reports_what_the_vm_needs_and_changes_none_of_it(self) -> None: - self.state("runtime-up") - result = self.run_role("--check", github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.vm_changes(), []) - self.assertFalse((self.stub / "vm").exists()) - for reported in (f"write {MODULES_FILE} in the VM", f"write {SYSCTL_FILE} in the VM", "modprobe br_netfilter in the VM"): - self.assertIn(reported, result.stdout) - - def test_a_vm_that_would_only_be_started_by_a_check_run_is_not_read(self) -> None: - self.state("session") - result = self.run_role("--check") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([call for call in self.calls() if " colima ssh " in call], []) - - def test_a_runtime_that_is_not_colima_leaves_the_kernel_alone(self) -> None: - self.state("runtime-up") - for context in ("desktop-linux", "orbstack"): - with self.subTest(context=context): - result = self.run_role(context=context, github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([call for call in self.calls() if " colima " in call], []) - - def test_a_stopped_runtime_that_is_not_started_fails_before_the_vm_is_touched(self) -> None: - self.state("session") - self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(self.vm_changes(), []) - self.assertEqual([call for call in self.calls() if " colima " in call], []) - - def i386_writes(self) -> list[str]: - """The commands run as root in the VM that write its qemu-i386 entry, in order.""" - return [command for command in self.vm_calls() if I386_ENTRY in command] - - def x86_vm(self, provision: list[dict[str, str]] | None = None, handler: str | None = "enabled") -> Path: - """An x86_64 VM whose qemu-i386 entry reads `handler` (none for no entry), and its profile's colima.yaml with `provision`.""" - self.state("runtime-up") - (self.stub / "vm").mkdir(exist_ok=True) - (self.stub / "vm" / "arch").write_text("x86_64\n") - if handler is not None: - entry = self.vm_file(I386_ENTRY) - entry.parent.mkdir(parents=True, exist_ok=True) - entry.write_text(f"{handler}\ninterpreter /usr/bin/qemu-i386\nflags: POCF\n") - config = self.home / ".colima" / "default" / "colima.yaml" - config.parent.mkdir(parents=True, exist_ok=True) - config.write_text(yaml.safe_dump({"cpu": 8, "arch": "x86_64", "binfmt": True, "provision": provision})) - return config - - def test_an_x86_vm_switches_the_i386_handler_off_now_and_after_every_start(self) -> None: - config = self.x86_vm() - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.i386_writes(), [f"sudo tee {I386_ENTRY}"]) - self.assertEqual(self.vm_file(I386_ENTRY).read_text().strip(), "0") - settings = yaml.safe_load(config.read_text()) - self.assertEqual(settings["provision"], [{"mode": "after-boot", "script": I386_OFF}]) - # Only the provision list changes: Colima's binfmt setting stays on, so the foreign-architecture handler is kept. - self.assertEqual({key: value for key, value in settings.items() if key != "provision"}, {"cpu": 8, "arch": "x86_64", "binfmt": True}) - - def test_the_provision_script_switches_off_only_the_i386_entry_and_tolerates_its_absence(self) -> None: - self.assertEqual(I386_ENTRY, "/proc/sys/fs/binfmt_misc/qemu-i386") - self.assertEqual(I386_OFF, f"test ! -e {I386_ENTRY} || echo 0 | sudo tee {I386_ENTRY} > /dev/null") - for present in (True, False): - with self.subTest(present=present): - entry = self.work / f"entry-{present}" - if present: - entry.write_text("enabled\n") - script = I386_OFF.replace(I386_ENTRY, str(entry)).replace("sudo ", "") - self.assertEqual(subprocess.run(["sh", "-c", script], check=False).returncode, 0) - self.assertEqual(entry.read_text().strip() if present else entry.exists(), "0" if present else False) - - def test_a_second_run_on_an_x86_vm_changes_nothing(self) -> None: - config = self.x86_vm() - self.run_role(github_runner_cluster_runtime_autostart=False) - before, written = len(self.vm_changes()), config.read_text() - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.recap(result)["changed"], 0, result.stdout) - self.assertEqual(self.vm_changes()[before:], []) - self.assertEqual(config.read_text(), written) - - def test_an_x86_vm_keeps_the_provision_scripts_it_has(self) -> None: - own = {"mode": "ready", "script": "echo ready"} - config = self.x86_vm(provision=[own]) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(yaml.safe_load(config.read_text())["provision"], [own, {"mode": "after-boot", "script": I386_OFF}]) - - def test_an_x86_vm_with_the_handler_already_off_or_absent_is_not_written_to(self) -> None: - for handler in ("disabled", None): - with self.subTest(handler=handler): - shutil.rmtree(self.stub / "vm", ignore_errors=True) - self.x86_vm(provision=[{"mode": "after-boot", "script": I386_OFF}], handler=handler) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.i386_writes(), []) - - def test_a_check_run_on_an_x86_vm_reports_the_handler_and_writes_nothing(self) -> None: - config = self.x86_vm() - written = config.read_text() - result = self.run_role("--check", github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertIn(f"echo 0 > {I386_ENTRY} in the VM", result.stdout) - self.assertEqual(self.i386_writes(), []) - self.assertEqual(self.vm_file(I386_ENTRY).read_text().splitlines()[0], "enabled") - self.assertEqual(config.read_text(), written) - - def test_an_aarch64_vm_keeps_its_i386_handler_and_its_profile(self) -> None: - self.state("runtime-up") - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.i386_writes(), []) - self.assertFalse((self.home / ".colima").exists()) - - def test_the_end_checks_pass_with_the_runtime_up_and_the_container_running(self) -> None: - self.state("runtime-up") - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - - def test_the_end_checks_fail_when_the_container_is_not_running(self) -> None: - self.state("runtime-up") - for state in ("exited", "restarting", ""): - with self.subTest(state=state): - (self.stub / "github-runner-k3s.state").write_text(state) - result = self.run_role(github_runner_cluster_runtime_autostart=False) - self.assertNotEqual(result.returncode, 0) - self.assertEqual(failed_task(result.stdout), "Fail unless this node's k3s container is running") - self.assertIn("The k3s container github-runner-k3s on node1 is", result.stdout) - self.assertIn("docker logs github-runner-k3s", result.stdout) - - def test_the_end_checks_catch_a_runtime_that_went_down_during_the_run(self) -> None: - result = self.run_role(tasks="end_checks", github_runner_cluster_runtime_autostart=False, github_runner_cluster_effective_runtime={"kind": "colima", "colima_profile": "default"}, github_runner_cluster_runtime_environment={"PATH": f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin", "DOCKER_CONTEXT": "colima"}, github_runner_cluster_runtime_down_message="the runtime is down") - self.assertNotEqual(result.returncode, 0) - self.assertEqual(failed_task(result.stdout), "Fail unless the container runtime is up") - self.assertIn("the runtime is down", result.stdout) - - def test_an_agent_host_is_checked_for_the_agent_container(self) -> None: - self.state("runtime-up") - result = self.run_role(github_runner_cluster_runtime_autostart=False, github_runner_cluster_docker_role="agent") - self.assertNotEqual(result.returncode, 0) - self.assertIn("The k3s container github-runner-k3s-agent on node1 is", result.stdout) - (self.stub / "github-runner-k3s-agent.state").write_text("running") - self.assertEqual(self.run_role(github_runner_cluster_runtime_autostart=False, github_runner_cluster_docker_role="agent").returncode, 0) - - def test_a_container_renamed_by_an_extra_compose_file_is_the_one_checked(self) -> None: - self.state("runtime-up") - (self.stub / "example-k3s.state").write_text("running") - result = self.run_role(github_runner_cluster_runtime_autostart=False, github_runner_cluster_container_name="example-k3s") - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - - # The watchdog's launchd job. - - def watchdog_calls(self) -> list[str]: - """The launchctl calls that load or unload the watchdog, without the Docker context each is logged under. """ - return [call.split(" ", 1)[1] for call in self.calls() if re.match(r"\S+ launchctl (bootstrap|bootout)", call) and "watchdog" in call] - - def test_the_watchdog_is_installed_beside_the_agent_and_loaded_into_the_login_session(self) -> None: - self.state("session", "runtime-up") - result = self.run_role(github_runner_cluster_runtime_watchdog=True) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - job = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima-watchdog.default.plist" - self.assertEqual(plistlib.loads(job.read_bytes())["StartInterval"], DEFAULTS["github_runner_cluster_runtime_watchdog_interval"]) - directory = self.home / ".local" / "share" / "exadev-github-runner" / "colima-watchdog-default" - for name in ("colima-watchdog.sh", "run_bounded.pl"): - self.assertTrue(os.access(directory / name, os.X_OK), name) - self.assertTrue((directory / "state").is_dir()) - self.assertEqual(self.watchdog_calls(), [f"launchctl bootstrap gui/{UID} {job}"]) - - def test_the_node_profile_gets_the_watchdog_as_a_daemon(self) -> None: - self.state("runtime-up") - result = self.run_role(context="colima-node", github_runner_cluster_runtime_watchdog=True) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - job = self.daemons / "com.exadev.github-runner.colima-watchdog.node.plist" - self.assertEqual(plistlib.loads(job.read_bytes())["UserName"], "example") - self.assertEqual(self.watchdog_calls(), [f"launchctl bootstrap system {job}"]) - - def test_a_second_run_changes_nothing_and_a_changed_job_is_unloaded_before_it_is_loaded_again(self) -> None: - self.state("session", "runtime-up") - self.assertEqual(self.run_role(github_runner_cluster_runtime_watchdog=True).returncode, 0) - before = self.watchdog_calls() - self.assertEqual(self.run_role(github_runner_cluster_runtime_watchdog=True).returncode, 0) - self.assertEqual(self.watchdog_calls(), before) - result = self.run_role(github_runner_cluster_runtime_watchdog=True, github_runner_cluster_runtime_watchdog_interval=120) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual([call.split()[1] for call in self.watchdog_calls()[len(before):]], ["bootout", "bootstrap"]) - - def test_off_installs_nothing(self) -> None: - self.state("session", "runtime-up") - result = self.run_role() - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - self.assertEqual(self.watchdog_calls(), []) - self.assertFalse((self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima-watchdog.default.plist").exists()) - - def test_turning_it_off_unloads_and_removes_an_installed_job(self) -> None: - self.state("session", "runtime-up") - self.assertEqual(self.run_role(github_runner_cluster_runtime_watchdog=True).returncode, 0) - job = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima-watchdog.default.plist" - self.assertEqual(self.run_role().returncode, 0) - self.assertFalse(job.exists()) - self.assertEqual(self.watchdog_calls()[-1], f"launchctl bootout gui/{UID}/com.exadev.github-runner.colima-watchdog.default") - - if __name__ == "__main__": unittest.main() diff --git a/tests/unit/test_runtime_autostart_launchd.py b/tests/unit/test_runtime_autostart_launchd.py new file mode 100644 index 0000000..6335648 --- /dev/null +++ b/tests/unit/test_runtime_autostart_launchd.py @@ -0,0 +1,304 @@ +"""Tests for the launchd daemon or agent the cluster role installs to start the runtime, the Colima home and context it runs with, and the other runtimes and check mode, run through the role against stand-ins (runtime_autostart_support.py).""" + +from __future__ import annotations + +import os +import plistlib +import re +import unittest + +from runtime_autostart_support import UID, RoleFixture, failed_task + + +class LaunchdJobTest(RoleFixture): + def test_the_node_profile_is_started_by_a_daemon_at_boot_with_nobody_logged_in(self) -> None: + # The state of a Mac that has rebooted to the login window: no session, so no gui domain to load an agent into. + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), ["colima-node colima start --profile node --activate=false", f"colima-node launchctl bootstrap system {self.node_daemon}"]) + daemon = plistlib.loads(self.node_daemon.read_bytes()) + self.assertEqual((daemon["Label"], daemon["UserName"], daemon["RunAtLoad"]), (self.LABEL, "example", True)) + self.assertEqual(daemon["EnvironmentVariables"], {"PATH": f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin", "HOME": str(self.home), "COLIMA_HOME": self.node_home}) + self.assertEqual(self.node_daemon.stat().st_mode & 0o777, 0o644) + self.assertTrue((self.stub / "daemon-loaded").exists()) + self.assertFalse(self.node_agent.exists()) + self.assertFalse((self.home / "Library" / "LaunchAgents").exists()) + self.assertNotIn("loads at the next login", result.stdout) + + def test_the_daemon_is_written_and_loaded_as_root_and_nothing_else_is(self) -> None: + self.run_node() + sudo = (self.stub / "sudo.log").read_text().splitlines() + self.assertTrue(any(f"{self.LABEL}.plist" in line or "ansible" in line for line in sudo), sudo) + # The stand-in launchctl refuses the system domain without root, and the run passed, so the load and any unload went through sudo; the read-only calls and the colima start did not need it. + self.assertEqual(len(self.system_calls()), 1) + + def test_the_daemon_is_also_installed_for_a_user_with_a_login_session_and_the_agent_never_is(self) -> None: + self.state("session") + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes()[-1], f"colima-node launchctl bootstrap system {self.node_daemon}") + self.assertFalse((self.stub / "loaded").exists()) + self.assertEqual([call for call in self.calls() if "gui/" in call], []) + + def test_a_running_node_profile_is_not_started_again_when_the_daemon_is_installed(self) -> None: + self.state("runtime-up") + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), [f"colima-node launchctl bootstrap system {self.node_daemon}"]) + + def test_a_host_the_previous_release_set_up_moves_from_the_agent_to_the_daemon(self) -> None: + self.state("session", "runtime-up") + self.v2_19_agent() + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), [f"colima-node launchctl bootstrap system {self.node_daemon}", f"colima-node launchctl bootout gui/{UID}/{self.LABEL}"]) + self.assertFalse(self.node_agent.exists()) + self.assertFalse((self.stub / "loaded").exists()) + self.assertTrue((self.stub / "daemon-loaded").exists()) + self.assertTrue(self.node_daemon.exists()) + + def test_an_agent_that_was_never_loaded_because_nobody_logged_in_is_only_deleted(self) -> None: + # What m1 looked like after its reboot: the agent file on disk, the login window up. + self.state("runtime-up") + self.v2_19_agent() + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertFalse(self.node_agent.exists()) + self.assertEqual([call for call in self.calls() if "gui/" in call and "launchctl print gui/" not in call], []) + self.assertEqual(self.changes(), [f"colima-node launchctl bootstrap system {self.node_daemon}"]) + + def test_the_agent_of_another_profile_is_left_alone(self) -> None: + self.state("session", "runtime-up") + other = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima.default.plist" + other.parent.mkdir(parents=True) + other.write_text("") + self.run_node() + self.assertEqual(other.read_text(), "") + + def test_a_second_run_with_the_daemon_in_place_changes_nothing_and_loads_nothing(self) -> None: + self.state("runtime-up") + self.run_node() + before = self.calls() + sudo_before = (self.stub / "sudo.log").read_text() + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.recap(result)["changed"], 0, result.stdout) + self.assertEqual([call for call in self.calls()[len(before):] if not re.match(r"\S+ (docker (info|ps|context inspect)|launchctl print |colima ssh --profile \S+ -- (cat|test|uname|sysctl -n|systemctl is-active|dpkg-query) )", call)], []) + # The template runs as root to compare ownership; it is the only thing that does, and it changes nothing. + self.assertEqual(self.system_calls(), [call for call in before if "launchctl bootstrap system" in call]) + self.assertTrue((self.stub / "sudo.log").read_text().startswith(sudo_before)) + + def test_a_changed_daemon_is_unloaded_before_it_is_loaded_again(self) -> None: + self.state("runtime-up") + self.run_node() + self.node_daemon.write_text(self.node_daemon.read_text().replace("start", "stop")) + before = len(self.changes()) + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes()[before:], [f"colima-node launchctl bootout system/{self.LABEL}", f"colima-node launchctl bootstrap system {self.node_daemon}"]) + self.assertIn("start", self.node_daemon.read_text()) + + def test_a_daemon_that_is_in_place_but_not_loaded_is_loaded(self) -> None: + self.state("runtime-up") + self.run_node() + (self.stub / "daemon-loaded").unlink() + result = self.run_node() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes()[-1], f"colima-node launchctl bootstrap system {self.node_daemon}") + + def test_check_mode_installs_and_loads_nothing_and_removes_nothing(self) -> None: + self.state("session", "runtime-up") + self.v2_19_agent() + result = self.run_node("--check", "--diff") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), []) + self.assertFalse(self.node_daemon.exists()) + self.assertTrue(self.node_agent.exists()) + self.assertIn("UserName", result.stdout, "the diff shows the daemon's property list") + self.assertGreater(self.recap(result)["changed"], 0) + + def test_a_host_set_back_to_login_retires_the_daemon(self) -> None: + self.state("session", "runtime-up") + self.run_node() + result = self.run_node(github_runner_cluster_runtime_autostart_at="login") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes()[-2:], [f"colima-node launchctl bootstrap gui/{UID} {self.node_agent}", f"colima-node launchctl bootout system/{self.LABEL}"]) + self.assertFalse(self.node_daemon.exists()) + self.assertFalse((self.stub / "daemon-loaded").exists()) + self.assertTrue(self.node_agent.exists()) + + def test_a_host_can_ask_for_a_daemon_for_any_profile(self) -> None: + self.state("runtime-up") + result = self.run_role(github_runner_cluster_runtime_autostart_at="boot") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(plistlib.loads((self.daemons / "com.exadev.github-runner.colima.default.plist").read_bytes())["UserName"], "example") + self.assertFalse(self.plist.exists()) + + def test_a_value_that_is_not_a_choice_is_refused_before_anything_changes(self) -> None: + self.state("session") + result = self.run_node(github_runner_cluster_runtime_autostart_at="sometimes") + self.assertNotEqual(result.returncode, 0) + self.assertIn("must be auto, login or boot, not sometimes", result.stdout) + self.assertEqual(self.calls(), []) + + def test_the_default_profile_keeps_its_login_agent_and_never_touches_the_system_domain(self) -> None: + self.state("session") + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), ["colima colima start --profile default --activate=false", f"colima launchctl bootstrap gui/{UID} {self.plist}"]) + self.assertEqual(list(self.daemons.iterdir()), []) + self.assertFalse((self.stub / "sudo.log").exists()) + # The VM's own systemd units live under /etc/systemd/system, which is not launchd's system domain. + self.assertEqual([call for call in self.calls() if "system" in call and "colima ssh" not in call], []) + + def test_autostart_off_leaves_an_installed_daemon_and_agent_as_they_are(self) -> None: + self.state("runtime-up") + self.node_daemon.write_text("") + self.v2_19_agent() + result = self.run_node(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual((self.node_daemon.read_text(), self.node_agent.read_text()), ("", "")) + self.assertEqual(self.changes(), []) + + def test_the_variable_wins_over_the_context_and_the_context_is_not_read(self) -> None: + # A profile that is stopped never reaches the stop's own read of the context, so the home comes from the variable alone. + self.state("session") + result = self.run_role(context="colima-node", github_runner_cluster_colima_home="/elsewhere") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_colima_ran_in("/elsewhere") + self.assertFalse([call for call in self.calls() if " docker context " in call]) + + def test_a_profile_in_the_default_home_runs_with_no_variable(self) -> None: + self.state("session") + self.run_role() + self.assert_colima_ran_in("-") + self.assertNotIn("COLIMA_HOME", plistlib.loads(self.plist.read_bytes())["EnvironmentVariables"]) + + def test_a_context_that_is_not_the_profiles_socket_fails_before_anything_changes(self) -> None: + self.state("session") + result = self.run_role(context="colima-node", context_host="tcp://127.0.0.1:2375") + self.assertNotEqual(result.returncode, 0) + self.assertIn("set github_runner_cluster_colima_home", result.stdout) + self.assertEqual(self.changes(), []) + + def test_a_stopped_profile_in_a_home_of_its_own_is_started_under_check_mode_reading_only(self) -> None: + self.state("session") + result = self.run_role("--check", context="colima-node", context_host=f"unix://{self.home}/.colima-node/node/docker.sock") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), []) + + def test_docker_desktop_and_other_runtimes_read_no_context(self) -> None: + for context in ("desktop-linux", "orbstack"): + with self.subTest(context=context): + self.run_role(context=context) + self.assertFalse([call for call in self.calls() if " docker context " in call]) + + def test_a_second_run_changes_nothing(self) -> None: + self.assert_a_second_run_changes_nothing("colima", None) + + def test_a_second_run_changes_nothing_for_a_profile_in_a_home_of_its_own(self) -> None: + self.assert_a_second_run_changes_nothing("colima-node", f"unix://{self.home}/.colima-node/node/docker.sock") + + def test_a_running_runtime_is_not_started_again_but_still_gets_the_agent(self) -> None: + self.state("session", "runtime-up") + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), [f"colima launchctl bootstrap gui/{UID} {self.plist}"]) + self.assertTrue(self.plist.exists()) + + def test_a_changed_definition_is_unloaded_before_it_is_loaded(self) -> None: + self.state("session") + self.run_role() + self.plist.write_text(self.plist.read_text().replace("start", "stop")) + before = len(self.changes()) + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes()[before:], [f"colima launchctl bootout gui/{UID}/com.exadev.github-runner.colima.default", f"colima launchctl bootstrap gui/{UID} {self.plist}"]) + self.assertIn("start", self.plist.read_text()) + + def test_without_a_login_session_the_agent_is_installed_and_left_for_the_next_login(self) -> None: + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertTrue(self.plist.exists()) + self.assertNotIn("bootstrap", " ".join(self.calls())) + self.assertIn("loads at the next login", result.stdout) + + def test_a_malformed_property_list_never_replaces_the_installed_one(self) -> None: + self.state("session") + self.run_role() + installed = self.plist.read_bytes() + (self.bin / "plutil").write_text("#!/bin/sh\nexit 1\n") + result = self.run_role("-e", "github_runner_cluster_runtime_path=" + f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin{os.pathsep}/changed") + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.plist.read_bytes(), installed) + + def test_a_colima_that_will_not_start_fails_the_run_at_that_task(self) -> None: + self.state("session", "colima-start-fails") + result = self.run_role() + self.assertNotEqual(result.returncode, 0) + self.assertEqual(failed_task(result.stdout), "Start the Colima profile if it is stopped") + self.assertFalse(self.plist.exists()) + + def test_autostart_off_installs_nothing_and_a_stopped_runtime_fails_with_the_fix(self) -> None: + self.state("session") + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(failed_task(result.stdout), "Fail unless the container runtime is up") + self.assertIn("Colima profile default is not running on node1. Start it with `colima start --profile default`", result.stdout) + self.assertEqual(self.changes(), []) + self.assertFalse(self.plist.exists()) + + def test_autostart_off_with_a_running_runtime_passes(self) -> None: + self.state("runtime-up") + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), []) + + def test_docker_desktop_is_never_started_and_a_stopped_one_says_which_setting_to_turn_on(self) -> None: + self.state("session") + result = self.run_role(context="desktop-linux") + self.assertNotEqual(result.returncode, 0) + self.assertIn("Docker Desktop is not running on node1, and this role cannot start it", result.stdout) + self.assertIn("Settings > General > Start Docker Desktop when you sign in to your computer", result.stdout) + self.assertEqual(self.changes(), []) + self.assertFalse(self.plist.parent.exists()) + + def test_a_running_docker_desktop_installs_nothing(self) -> None: + self.state("session", "runtime-up") + result = self.run_role(context="desktop-linux") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), []) + self.assertFalse(self.plist.parent.exists()) + + def test_another_runtime_is_only_checked(self) -> None: + result = self.run_role(context="orbstack") + self.assertNotEqual(result.returncode, 0) + self.assertIn("The container runtime is not running on node1", result.stdout) + self.assertEqual(self.changes(), []) + + def test_a_linux_host_is_not_touched(self) -> None: + result = self.run_role(system="Linux") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.calls(), []) + self.assertFalse((self.home / "Library").exists()) + + def test_check_mode_starts_and_installs_nothing_and_does_not_fail_on_a_stopped_runtime(self) -> None: + self.state("session") + result = self.run_role("--check", "--diff") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), []) + self.assertFalse(self.plist.exists()) + self.assertIn("com.exadev.github-runner.colima.default", result.stdout, "the diff shows the property list") + + def test_check_mode_reports_a_changed_definition(self) -> None: + self.state("session") + self.run_role() + self.plist.write_text(self.plist.read_text().replace("start", "stop")) + result = self.run_role("--check", "--diff") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertGreater(self.recap(result)["changed"], 0) + self.assertIn("stop", self.plist.read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_runtime_autostart_vm.py b/tests/unit/test_runtime_autostart_vm.py new file mode 100644 index 0000000..df43777 --- /dev/null +++ b/tests/unit/test_runtime_autostart_vm.py @@ -0,0 +1,303 @@ +"""Tests for what the cluster role prepares inside the Colima VM, its end checks and its watchdog job, run through the role against stand-ins (runtime_autostart_support.py).""" + +from __future__ import annotations + +import os +import plistlib +import shutil +import subprocess +import unittest + +import yaml +from runtime_autostart_support import DEFAULTS, I386_ENTRY, I386_OFF, MODULES_FILE, ROLE, SYSCTL_FILE, UID, RoleFixture, failed_task + + +class ColimaVmTest(RoleFixture): + def test_a_colima_vm_without_the_module_gets_the_files_that_load_it_and_the_module(self) -> None: + self.state("runtime-up") + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.vm_changes(), [f"sudo tee {MODULES_FILE}", f"sudo tee {SYSCTL_FILE}", "sudo modprobe -- br_netfilter"]) + self.assertEqual(self.vm_file(MODULES_FILE).read_text().splitlines()[-1], "br_netfilter") + self.assertEqual(self.vm_file(SYSCTL_FILE).read_text().splitlines()[1:], ["net.bridge.bridge-nf-call-iptables = 1", "net.bridge.bridge-nf-call-ip6tables = 1"]) + self.assertTrue(self.vm_file("/proc/sys/net/bridge").is_dir()) + + def test_a_second_run_changes_nothing_in_the_vm(self) -> None: + self.state("runtime-up") + self.run_role(github_runner_cluster_runtime_autostart=False) + before = self.calls() + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.recap(result)["changed"], 0, result.stdout) + self.assertEqual([call for call in self.calls()[len(before) :] if " sudo " in call], []) + + def test_the_route_guard_is_installed_in_the_vm_with_its_timer_and_started(self) -> None: + script, unit = DEFAULTS["github_runner_cluster_colima_route_guard_script"], DEFAULTS["github_runner_cluster_colima_route_guard_unit"] + self.state("runtime-up") + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual( + self.route_guard_changes(), + ["sudo apt-get update", "sudo apt-get install -y --no-install-recommends iputils-ping", f"sudo tee {script}", f"sudo tee /etc/systemd/system/{unit}.service", f"sudo tee /etc/systemd/system/{unit}.timer", f"sudo chmod 0755 {script}", "sudo systemctl daemon-reload", f"sudo systemctl enable --now {unit}.timer"], + ) + self.assertEqual(self.vm_file(script).read_text().strip(), (ROLE / "files" / "route-guard.sh").read_text().strip()) + self.assertEqual(self.vm_file(script).stat().st_mode & 0o777, 0o755) + timer = self.vm_file(f"/etc/systemd/system/{unit}.timer").read_text() + self.assertIn(f"OnBootSec={DEFAULTS['github_runner_cluster_colima_route_guard_interval_seconds']}s", timer) + # systemd's default accuracy of a minute would let a tick slip far past the interval. + self.assertIn("AccuracySec=1s", timer) + self.assertIn(f"ExecStart={script}", self.vm_file(f"/etc/systemd/system/{unit}.service").read_text()) + + def test_a_second_run_leaves_the_route_guard_alone(self) -> None: + self.state("runtime-up") + self.run_role(github_runner_cluster_runtime_autostart=False) + before = len(self.route_guard_changes()) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.route_guard_changes()[before:], []) + + def test_a_stopped_route_guard_timer_is_started_again_without_rewriting_the_files(self) -> None: + unit = DEFAULTS["github_runner_cluster_colima_route_guard_unit"] + self.state("runtime-up") + self.run_role(github_runner_cluster_runtime_autostart=False) + (self.stub / "vm" / "active-units").write_text("") + before = len(self.route_guard_changes()) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.route_guard_changes()[before:], [f"sudo systemctl enable --now {unit}.timer"]) + + def test_a_changed_route_guard_script_is_rewritten_and_systemd_reloaded(self) -> None: + script = DEFAULTS["github_runner_cluster_colima_route_guard_script"] + self.state("runtime-up") + self.run_role(github_runner_cluster_runtime_autostart=False) + self.vm_file(script).write_text("#!/bin/sh\nexit 0\n") + before = len(self.route_guard_changes()) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.route_guard_changes()[before:], [f"sudo tee {script}", f"sudo chmod 0755 {script}", "sudo systemctl daemon-reload"]) + + def test_the_module_is_loaded_again_when_a_restarted_vm_has_lost_it_and_the_files_are_left_alone(self) -> None: + self.state("runtime-up") + self.run_role(github_runner_cluster_runtime_autostart=False) + shutil.rmtree(self.vm_file("/proc")) + before = len(self.vm_changes()) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.vm_changes()[before:], ["sudo modprobe -- br_netfilter"]) + + def test_a_loaded_module_is_not_loaded_again_but_the_files_are_still_written(self) -> None: + self.state("runtime-up") + self.vm_file("/proc/sys/net/bridge").mkdir(parents=True) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.vm_changes(), [f"sudo tee {MODULES_FILE}", f"sudo tee {SYSCTL_FILE}"]) + + def test_the_file_a_person_wrote_by_hand_is_replaced_by_the_managed_one(self) -> None: + self.state("runtime-up") + self.vm_file(MODULES_FILE).parent.mkdir(parents=True) + self.vm_file(MODULES_FILE).write_text("br_netfilter\n") + self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertIn(f"sudo tee {MODULES_FILE}", self.vm_changes()) + self.assertIn("Managed by the exadev.github_runner collection", self.vm_file(MODULES_FILE).read_text()) + + def test_a_bridge_sysctl_that_is_off_is_set_after_the_module_is_loaded(self) -> None: + self.state("runtime-up") + (self.stub / "vm" / "sysctl").mkdir(parents=True) + (self.stub / "vm" / "sysctl" / "net.bridge.bridge-nf-call-iptables").write_text("0") + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.vm_changes()[2:], ["sudo modprobe -- br_netfilter", "sudo sysctl -w net.bridge.bridge-nf-call-iptables=1"]) + + def test_the_vm_of_the_hosts_profile_is_the_one_prepared(self) -> None: + self.state("runtime-up") + self.run_role(context="colima-example", github_runner_cluster_runtime_autostart=False) + ssh_calls = [call for call in self.calls() if " colima ssh " in call] + self.assertTrue(ssh_calls) + self.assertTrue(all(call.startswith("colima-example colima ssh --profile example -- ") for call in ssh_calls), ssh_calls) + + def test_the_vm_is_prepared_with_the_agent_installed_as_well(self) -> None: + self.state("session") + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), ["colima colima start --profile default --activate=false", f"colima launchctl bootstrap gui/{UID} {self.plist}"]) + self.assertEqual(self.vm_changes()[-1], "sudo modprobe -- br_netfilter") + + def test_check_mode_reports_what_the_vm_needs_and_changes_none_of_it(self) -> None: + self.state("runtime-up") + result = self.run_role("--check", github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.vm_changes(), []) + self.assertFalse((self.stub / "vm").exists()) + for reported in (f"write {MODULES_FILE} in the VM", f"write {SYSCTL_FILE} in the VM", "modprobe br_netfilter in the VM"): + self.assertIn(reported, result.stdout) + + def test_a_vm_that_would_only_be_started_by_a_check_run_is_not_read(self) -> None: + self.state("session") + result = self.run_role("--check") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([call for call in self.calls() if " colima ssh " in call], []) + + def test_a_runtime_that_is_not_colima_leaves_the_kernel_alone(self) -> None: + self.state("runtime-up") + for context in ("desktop-linux", "orbstack"): + with self.subTest(context=context): + result = self.run_role(context=context, github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([call for call in self.calls() if " colima " in call], []) + + def test_a_stopped_runtime_that_is_not_started_fails_before_the_vm_is_touched(self) -> None: + self.state("session") + self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(self.vm_changes(), []) + self.assertEqual([call for call in self.calls() if " colima " in call], []) + + def test_an_x86_vm_switches_the_i386_handler_off_now_and_after_every_start(self) -> None: + config = self.x86_vm() + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.i386_writes(), [f"sudo tee {I386_ENTRY}"]) + self.assertEqual(self.vm_file(I386_ENTRY).read_text().strip(), "0") + settings = yaml.safe_load(config.read_text()) + self.assertEqual(settings["provision"], [{"mode": "after-boot", "script": I386_OFF}]) + # Only the provision list changes: Colima's binfmt setting stays on, so the foreign-architecture handler is kept. + self.assertEqual({key: value for key, value in settings.items() if key != "provision"}, {"cpu": 8, "arch": "x86_64", "binfmt": True}) + + def test_the_provision_script_switches_off_only_the_i386_entry_and_tolerates_its_absence(self) -> None: + self.assertEqual(I386_ENTRY, "/proc/sys/fs/binfmt_misc/qemu-i386") + self.assertEqual(I386_OFF, f"test ! -e {I386_ENTRY} || echo 0 | sudo tee {I386_ENTRY} > /dev/null") + for present in (True, False): + with self.subTest(present=present): + entry = self.work / f"entry-{present}" + if present: + entry.write_text("enabled\n") + script = I386_OFF.replace(I386_ENTRY, str(entry)).replace("sudo ", "") + self.assertEqual(subprocess.run(["sh", "-c", script], check=False).returncode, 0) + self.assertEqual(entry.read_text().strip() if present else entry.exists(), "0" if present else False) + + def test_a_second_run_on_an_x86_vm_changes_nothing(self) -> None: + config = self.x86_vm() + self.run_role(github_runner_cluster_runtime_autostart=False) + before, written = len(self.vm_changes()), config.read_text() + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.recap(result)["changed"], 0, result.stdout) + self.assertEqual(self.vm_changes()[before:], []) + self.assertEqual(config.read_text(), written) + + def test_an_x86_vm_keeps_the_provision_scripts_it_has(self) -> None: + own = {"mode": "ready", "script": "echo ready"} + config = self.x86_vm(provision=[own]) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(yaml.safe_load(config.read_text())["provision"], [own, {"mode": "after-boot", "script": I386_OFF}]) + + def test_an_x86_vm_with_the_handler_already_off_or_absent_is_not_written_to(self) -> None: + for handler in ("disabled", None): + with self.subTest(handler=handler): + shutil.rmtree(self.stub / "vm", ignore_errors=True) + self.x86_vm(provision=[{"mode": "after-boot", "script": I386_OFF}], handler=handler) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.i386_writes(), []) + + def test_a_check_run_on_an_x86_vm_reports_the_handler_and_writes_nothing(self) -> None: + config = self.x86_vm() + written = config.read_text() + result = self.run_role("--check", github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(f"echo 0 > {I386_ENTRY} in the VM", result.stdout) + self.assertEqual(self.i386_writes(), []) + self.assertEqual(self.vm_file(I386_ENTRY).read_text().splitlines()[0], "enabled") + self.assertEqual(config.read_text(), written) + + def test_an_aarch64_vm_keeps_its_i386_handler_and_its_profile(self) -> None: + self.state("runtime-up") + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.i386_writes(), []) + self.assertFalse((self.home / ".colima").exists()) + + def test_the_end_checks_pass_with_the_runtime_up_and_the_container_running(self) -> None: + self.state("runtime-up") + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_the_end_checks_fail_when_the_container_is_not_running(self) -> None: + self.state("runtime-up") + for state in ("exited", "restarting", ""): + with self.subTest(state=state): + (self.stub / "github-runner-k3s.state").write_text(state) + result = self.run_role(github_runner_cluster_runtime_autostart=False) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(failed_task(result.stdout), "Fail unless this node's k3s container is running") + self.assertIn("The k3s container github-runner-k3s on node1 is", result.stdout) + self.assertIn("docker logs github-runner-k3s", result.stdout) + + def test_the_end_checks_catch_a_runtime_that_went_down_during_the_run(self) -> None: + result = self.run_role(tasks="end_checks", github_runner_cluster_runtime_autostart=False, github_runner_cluster_effective_runtime={"kind": "colima", "colima_profile": "default"}, github_runner_cluster_runtime_environment={"PATH": f"{self.bin}{os.pathsep}/usr/bin{os.pathsep}/bin", "DOCKER_CONTEXT": "colima"}, github_runner_cluster_runtime_down_message="the runtime is down") + self.assertNotEqual(result.returncode, 0) + self.assertEqual(failed_task(result.stdout), "Fail unless the container runtime is up") + self.assertIn("the runtime is down", result.stdout) + + def test_an_agent_host_is_checked_for_the_agent_container(self) -> None: + self.state("runtime-up") + result = self.run_role(github_runner_cluster_runtime_autostart=False, github_runner_cluster_docker_role="agent") + self.assertNotEqual(result.returncode, 0) + self.assertIn("The k3s container github-runner-k3s-agent on node1 is", result.stdout) + (self.stub / "github-runner-k3s-agent.state").write_text("running") + self.assertEqual(self.run_role(github_runner_cluster_runtime_autostart=False, github_runner_cluster_docker_role="agent").returncode, 0) + + def test_a_container_renamed_by_an_extra_compose_file_is_the_one_checked(self) -> None: + self.state("runtime-up") + (self.stub / "example-k3s.state").write_text("running") + result = self.run_role(github_runner_cluster_runtime_autostart=False, github_runner_cluster_container_name="example-k3s") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_the_watchdog_is_installed_beside_the_agent_and_loaded_into_the_login_session(self) -> None: + self.state("session", "runtime-up") + result = self.run_role(github_runner_cluster_runtime_watchdog=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + job = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima-watchdog.default.plist" + self.assertEqual(plistlib.loads(job.read_bytes())["StartInterval"], DEFAULTS["github_runner_cluster_runtime_watchdog_interval"]) + directory = self.home / ".local" / "share" / "exadev-github-runner" / "colima-watchdog-default" + for name in ("colima-watchdog.sh", "run_bounded.pl"): + self.assertTrue(os.access(directory / name, os.X_OK), name) + self.assertTrue((directory / "state").is_dir()) + self.assertEqual(self.watchdog_calls(), [f"launchctl bootstrap gui/{UID} {job}"]) + + def test_the_node_profile_gets_the_watchdog_as_a_daemon(self) -> None: + self.state("runtime-up") + result = self.run_role(context="colima-node", github_runner_cluster_runtime_watchdog=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + job = self.daemons / "com.exadev.github-runner.colima-watchdog.node.plist" + self.assertEqual(plistlib.loads(job.read_bytes())["UserName"], "example") + self.assertEqual(self.watchdog_calls(), [f"launchctl bootstrap system {job}"]) + + def test_a_second_run_changes_nothing_and_a_changed_job_is_unloaded_before_it_is_loaded_again(self) -> None: + self.state("session", "runtime-up") + self.assertEqual(self.run_role(github_runner_cluster_runtime_watchdog=True).returncode, 0) + before = self.watchdog_calls() + self.assertEqual(self.run_role(github_runner_cluster_runtime_watchdog=True).returncode, 0) + self.assertEqual(self.watchdog_calls(), before) + result = self.run_role(github_runner_cluster_runtime_watchdog=True, github_runner_cluster_runtime_watchdog_interval=120) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([call.split()[1] for call in self.watchdog_calls()[len(before):]], ["bootout", "bootstrap"]) + + def test_off_installs_nothing(self) -> None: + self.state("session", "runtime-up") + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.watchdog_calls(), []) + self.assertFalse((self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima-watchdog.default.plist").exists()) + + def test_turning_it_off_unloads_and_removes_an_installed_job(self) -> None: + self.state("session", "runtime-up") + self.assertEqual(self.run_role(github_runner_cluster_runtime_watchdog=True).returncode, 0) + job = self.home / "Library" / "LaunchAgents" / "com.exadev.github-runner.colima-watchdog.default.plist" + self.assertEqual(self.run_role().returncode, 0) + self.assertFalse(job.exists()) + self.assertEqual(self.watchdog_calls()[-1], f"launchctl bootout gui/{UID}/com.exadev.github-runner.colima-watchdog.default") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_runtime_autostart_wedged.py b/tests/unit/test_runtime_autostart_wedged.py new file mode 100644 index 0000000..0acc4e3 --- /dev/null +++ b/tests/unit/test_runtime_autostart_wedged.py @@ -0,0 +1,280 @@ +"""Tests for how the cluster role starts a stopped Colima profile and recovers one listed as running whose runtime does not answer, run through the role against stand-ins (runtime_autostart_support.py).""" + +from __future__ import annotations + +import os +import plistlib +import re +import time +import unittest + +from runtime_autostart_support import UID, RoleFixture + + +class WedgedRuntimeTest(RoleFixture): + def test_a_stopped_colima_is_started_and_the_agent_installed_and_loaded(self) -> None: + self.state("session") + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.changes(), ["colima colima start --profile default --activate=false".replace("colima colima", "colima colima"), f"colima launchctl bootstrap gui/{UID} {self.plist}"]) + self.assertEqual(plistlib.loads(self.plist.read_bytes())["ProgramArguments"][3:5], ["--profile", "default"]) + self.assertEqual(self.plist.stat().st_mode & 0o777, 0o644) + self.assertTrue((self.stub / "loaded").exists()) + + def test_a_vm_whose_runtime_stays_silent_and_whose_guest_and_agent_confirm_it_is_stopped_cleanly_and_started_again(self) -> None: + self.listed_running() + result = self.run_role(**self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), ["colima colima stop --profile default"]) + self.assertEqual(self.starts(), ["colima colima start --profile default --activate=false"]) + self.assertLess(self.calls().index(self.stops()[0]), self.calls().index(self.starts()[0])) + # The first probe and every further try. + self.assertGreaterEqual(len(self.info_calls()), 4) + self.assertTrue((self.stub / "runtime-up").exists()) + + def test_a_clean_stop_that_fails_is_followed_by_a_forced_one(self) -> None: + self.listed_running() + self.state("clean-stop-fails") + result = self.run_role(**self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), ["colima colima stop --profile default", "colima colima stop --profile default --force"]) + self.assertEqual(len(self.starts()), 1) + + def test_only_the_hosts_own_profile_is_stopped_while_another_listed_profile_runs(self) -> None: + self.listed_running() + self.run_role(**self.FAST) + self.assertEqual([call for call in self.stops() if "--profile other" in call], []) + self.assertTrue(self.stops()) + + def test_a_daemon_that_answers_on_a_later_try_is_never_stopped(self) -> None: + # The first probe and one further try fail, as on a loaded host or while dockerd restarts, and the next answers. + self.listed_running() + (self.stub / "docker-answers-after").write_text("2") + result = self.run_role(**self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), []) + self.assertEqual(self.starts(), []) + + def test_a_guest_that_answers_a_command_is_left_alone_although_docker_is_silent(self) -> None: + self.listed_running() + self.state("guest-answers") + self.assert_left_alone(self.run_role(**self.FAST), "a command in the guest succeeded") + + def test_a_vm_whose_agent_started_moments_ago_is_left_alone_however_old_its_pid_file_is(self) -> None: + # The pid file is a week old, from a boot long gone, and the process it names started thirty seconds ago. + self.listed_running(agent_age=30) + self.assert_left_alone(self.run_role(**self.FAST), "for less than 600 seconds") + + def test_a_pid_file_naming_no_running_process_leaves_the_age_unknown_and_nothing_is_stopped(self) -> None: + # An old pid file whose process is gone, as after a reboot: its date says the agent is old, and that must not count. + self.listed_running(stale_file=True) + self.assert_left_alone(self.run_role(**self.FAST), "could not be read") + + def test_a_pid_file_naming_another_program_leaves_the_age_unknown(self) -> None: + self.listed_running(command="/usr/sbin/cron -f") + self.assert_left_alone(self.run_role(**self.FAST), "could not be read") + + def test_a_pid_file_naming_a_program_whose_path_merely_contains_hostagent_leaves_the_age_unknown(self) -> None: + self.listed_running(command="/opt/hostagent/bin/cron -f") + self.assert_left_alone(self.run_role(**self.FAST), "could not be read") + + def test_a_report_of_an_old_agent_does_not_say_ago_twice(self) -> None: + self.listed_running(command="/usr/local/bin/limactl hostagent x", agent_age=7200) + self.state("guest-answers") + result = self.run_role(**self.FAST) + self.assertIn("for more than 600 seconds;", result.stdout) + self.assertNotIn("seconds ago", result.stdout) + + # The Docker context, which the stop reads for its socket check on its own. + + def test_a_host_that_names_its_colima_home_and_has_no_readable_context_still_runs(self) -> None: + # The README's route for a host whose context does not say where the profile is (DOCKER_HOST, say): the variable gives the home and the context cannot be read. Nothing is listed as running, so the play starts the profile as before. + for label, variables in (("an empty context", {"context": ""}), ("an unknown context", {})): + with self.subTest(label=label): + self.forget() + self.state("session") + if not variables: + self.state("context-unknown") + result = self.run_role(github_runner_cluster_colima_home="/elsewhere", github_runner_cluster_runtime="colima", **variables) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_colima_ran_in("/elsewhere") + self.assertEqual(self.stops(), []) + + def test_a_context_that_cannot_be_read_never_leads_to_a_stop_and_the_report_says_so(self) -> None: + for label, variables in (("an empty context", {"context": ""}), ("an unknown context", {"unknown": True})): + with self.subTest(label=label): + self.forget() + self.listed_running() + if variables.get("unknown"): + self.state("context-unknown") + result = self.run_role(github_runner_cluster_colima_home=f"{self.home}/.colima", github_runner_cluster_runtime="colima", **{k: v for k, v in variables.items() if k != "unknown"}, **self.FAST) + self.assert_left_alone(result, "so its socket is not proven to belong to the profile") + + def test_a_context_whose_endpoint_is_another_runtime_never_leads_to_a_stop(self) -> None: + for endpoint in ("tcp://remote.example.invalid:2375", "unix:///var/run/docker.sock"): + with self.subTest(endpoint=endpoint): + self.forget() + self.listed_running() + result = self.run_role(context_host=endpoint, github_runner_cluster_colima_home=f"{self.home}/.colima", **self.FAST) + self.assert_left_alone(result, "does not point at the socket of the profile") + + # The supervisor failing is not a failed probe. + + def test_a_supervisor_that_cannot_run_the_command_fails_the_run_naming_it_and_is_not_evidence(self) -> None: + for code in (127, 255): + with self.subTest(code=code): + self.forget() + self.listed_running() + (self.stub / "docker-exit").write_text(str(code)) + result = self.run_role(**self.FAST) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn("run_bounded.pl", result.stdout) + self.assertEqual(self.stops(), []) + + def test_a_host_without_perl_fails_the_run_naming_the_supervisor(self) -> None: + self.listed_running() + result = self.run_role(github_runner_cluster_runtime_path=str(self.bin), **self.FAST) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn("run_bounded.pl", result.stdout) + self.assertEqual(self.stops(), []) + + def test_a_perl_that_is_not_executable_fails_the_run_naming_the_supervisor(self) -> None: + # The command module reports this with the OS error number as its rc (13), not 2: the message identifies it. + self.listed_running() + perl_dir = self.work / "no-perl" + perl_dir.mkdir() + (perl_dir / "perl").write_text("#!/bin/sh\n") + (perl_dir / "perl").chmod(0o644) + result = self.run_role(github_runner_cluster_runtime_path=f"{perl_dir}{os.pathsep}{self.bin}", **self.FAST) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn("run_bounded.pl", result.stdout) + self.assertEqual(self.stops(), []) + + def test_a_tool_that_fails_by_itself_still_counts_as_a_failed_probe(self) -> None: + # docker exiting 1 (cannot connect) is the daemon's answer, not the supervisor's. + self.listed_running() + (self.stub / "docker-exit").write_text("1") + result = self.run_role(**self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(len(self.stops()), 1) + + def test_an_agent_that_has_run_for_days_counts_as_old(self) -> None: + self.listed_running(agent_age=3 * 86400 + 3600 + 61) + result = self.run_role(**self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(len(self.stops()), 1) + + def test_an_agent_whose_age_cannot_be_read_does_not_count_as_old(self) -> None: + self.listed_running(agent_age=None) + self.assert_left_alone(self.run_role(**self.FAST), "could not be read") + + def test_a_colima_home_that_is_not_where_the_context_points_never_leads_to_a_stop(self) -> None: + # The variable names another Colima home than the one the Docker context's socket is in: the probes measured one runtime and a stop would act on another's profile. (A context whose endpoint is no Colima socket at all fails earlier, in the filter that reads the home from it.) + self.listed_running() + result = self.run_role(github_runner_cluster_colima_home="/elsewhere", **self.FAST) + self.assert_left_alone(result, "does not point at the socket of the profile") + + def test_with_the_stop_switched_off_a_confirmed_wedge_fails_naming_the_switch(self) -> None: + self.listed_running() + self.assert_left_alone(self.run_role(github_runner_cluster_runtime_force_stop_wedged=False, **self.FAST), "github_runner_cluster_runtime_force_stop_wedged is off") + + def test_the_stop_switch_is_independent_of_autostart(self) -> None: + self.listed_running() + result = self.run_role(github_runner_cluster_runtime_force_stop_wedged=False, github_runner_cluster_runtime_autostart=True, **self.FAST) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(self.stops(), []) + + def test_a_second_run_after_the_recovery_stops_and_starts_nothing(self) -> None: + self.listed_running() + self.run_role(**self.FAST) + before = len(self.calls()) + result = self.run_role(**self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual([call for call in self.calls()[before:] if re.match(r"\S+ colima (stop|start)", call)], []) + + def test_a_stopped_profile_is_started_without_being_stopped_first(self) -> None: + self.state("session") + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), []) + + def test_a_running_runtime_is_neither_listed_nor_stopped(self) -> None: + self.state("session", "runtime-up", "colima-listed-running") + result = self.run_role() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), []) + self.assertEqual([call for call in self.calls() if re.match(r"\S+ colima list", call)], []) + + def test_probes_that_never_reply_and_ignore_sigalrm_are_ended_and_the_vm_is_stopped_and_started(self) -> None: + # docker info and the guest command never reply and ignore SIGALRM, as Go programs do; the clean stop never ends and ignores TERM too. + self.listed_running() + self.state("docker-hangs", "guest-hangs", "clean-stop-hangs", "ignore-term") + began = time.monotonic() + result = self.run_role(**self.HANG) + elapsed = time.monotonic() - began + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), ["colima colima stop --profile default", "colima colima stop --profile default --force"]) + self.assertEqual(len(self.starts()), 1) + # Unbounded, each stand-in sleeps for 300 seconds. + self.assertLess(elapsed, 120) + self.assertGreaterEqual(len(self.hung_pids()), 5) + self.assert_all_ended() + + def test_a_hung_docker_with_a_guest_that_answers_fails_the_run_within_the_bound_and_stops_nothing(self) -> None: + self.listed_running() + self.state("docker-hangs", "guest-answers") + began = time.monotonic() + result = self.run_role(**self.HANG) + self.assertLess(time.monotonic() - began, 120) + self.assert_left_alone(result, "a command in the guest succeeded") + self.assert_all_ended() + + def test_a_hung_first_probe_counts_as_the_runtime_not_answering(self) -> None: + # A stopped profile whose Docker socket accepts and never replies: the start follows, as for a socket that refuses. + self.state("session", "docker-hangs") + began = time.monotonic() + result = self.run_role(**self.HANG) + self.assertLess(time.monotonic() - began, 120) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(len(self.starts()), 1) + self.assert_all_ended() + + def test_check_mode_reads_everything_stops_nothing_and_says_what_a_real_run_would_do(self) -> None: + self.listed_running() + result = self.run_role("--check", **self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), []) + self.assertTrue((self.stub / "colima-listed-running").exists()) + self.assertIn("A real run would stop the profile", result.stdout) + + def test_check_mode_on_a_vm_that_is_not_shown_to_be_wedged_says_nothing_would_be_stopped(self) -> None: + self.listed_running() + self.state("guest-answers") + result = self.run_role("--check", **self.FAST) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.stops(), []) + self.assertIn("A real run would stop nothing and fail here", result.stdout) + + def test_every_docker_call_uses_the_hosts_docker_context(self) -> None: + self.state("session") + self.run_role(context="colima-example") + docker_calls = [call for call in self.calls() if " docker " in call] + self.assertTrue(docker_calls) + self.assertTrue(all(call.startswith("colima-example ") for call in docker_calls), docker_calls) + self.assertIn("colima-example colima start --profile example --activate=false", self.calls()) + + def test_a_profile_in_a_home_of_its_own_is_started_and_loaded_with_that_home(self) -> None: + # The bridged node profile: context colima-node, profile node, in ~/.colima-node. Without COLIMA_HOME colima would start a new profile of that name in ~/.colima. A login agent is chosen here, since the node profile is started at boot by default. + self.state("session") + node_home = f"{self.home}/.colima-node" + result = self.run_role(context="colima-node", context_host=f"unix://{node_home}/node/docker.sock", github_runner_cluster_runtime_autostart_at="login") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_colima_ran_in(node_home) + agent = plistlib.loads(self.home.joinpath("Library/LaunchAgents/com.exadev.github-runner.colima.node.plist").read_bytes()) + self.assertEqual(agent["EnvironmentVariables"]["COLIMA_HOME"], node_home) + self.assertEqual(agent["ProgramArguments"][3:6], ["--profile", "node", "--activate=false"]) + self.assertEqual(list(self.daemons.iterdir()), []) + + +if __name__ == "__main__": + unittest.main()