From d8c55d5e685bc3ad14d4cfc1dea2eecfc2fca906 Mon Sep 17 00:00:00 2001 From: Joseph Mearman Date: Thu, 26 Nov 2026 00:27:17 +0000 Subject: [PATCH] fix(cluster): run 32-bit x86 programs natively in an x86_64 Colima VM With its binfmt setting on, Colima runs `binfmt --install 386,` at every start, so an x86_64 VM also gets a qemu-i386 handler for its own architecture's 32-bit programs. binfmt_misc takes precedence over the kernel's loader, so every 32-bit program in a pod on such a node runs under qemu user emulation, where Wine's 32-bit side never finishes creating a prefix and a Windows installer build hangs. On a Colima host whose VM is x86_64 the role now switches off only the qemu-i386 entry: at once in the running VM, which restarts nothing, and after every start through an after-boot provision script it adds to the profile's colima.yaml, which Colima runs after its own binfmt setup and before the container runtime. Colima's binfmt setting stays on, so the foreign-architecture handler is kept, and an aarch64 VM is left alone. --- docs/non-obvious-behaviour.md | 1 + roles/github_runner_cluster/README.md | 2 + roles/github_runner_cluster/defaults/main.yml | 3 + .../tasks/colima_binfmt.yml | 69 ++++++++++++ roles/github_runner_cluster/tasks/runtime.yml | 9 ++ tests/unit/test_runtime_autostart.py | 100 +++++++++++++++++- 6 files changed, 180 insertions(+), 4 deletions(-) create mode 100644 roles/github_runner_cluster/tasks/colima_binfmt.yml diff --git a/docs/non-obvious-behaviour.md b/docs/non-obvious-behaviour.md index 2265376..eaed7d2 100644 --- a/docs/non-obvious-behaviour.md +++ b/docs/non-obvious-behaviour.md @@ -5,6 +5,7 @@ - **A scale-set's listener pod can crash-loop forever with `ephemeralrunnersets... not found` after a Helm upgrade, even though the release itself succeeds.** ARC names the `EphemeralRunnerSet` it creates for a release with a spec hash suffix, and gives it a new name whenever the pod template changes (a `helm upgrade` that touches resource limits, `nodeSelector`, or similar). The `AutoscalingListener` is supposed to track this rename, but can be left pointing at the old, now-deleted name - it then restarts every second or two, each time failing at startup with `could not patch ephemeral runner set ... not found`, and the scale set's own job queue never gets serviced even though every other release's listener stays healthy. Diagnose with `kubectl get autoscalinglisteners -n actions-runner-controller -o custom-columns='NAME:.metadata.name,ERS:.spec.ephemeralRunnerSetName'` against `kubectl get ephemeralrunnersets -A` - a mismatch confirms it. Fix: `kubectl delete autoscalinglistener -n actions-runner-controller`; the controller recreates it immediately with the current `EphemeralRunnerSet` name. - **k3s cannot overwrite an existing kubeconfig through Colima's macOS share.** The container-root-to-Mac-user file mapping leaves `/output/kubeconfig.yaml` owner-read-only, so k3s crash-loops with "permission denied" on every restart (for example after a Mac reboot) unless the file is removed first. `k3s/node-entrypoint.sh` deletes it before starting k3s each time — do not remove that step. - **Pods can lose every cluster service IP, cluster DNS included, whenever the Colima Linux VM has not loaded `br_netfilter` (a restarted VM, after a host reboot for example).** Without the module (`/proc/sys/net/bridge` is missing in the VM) packets bridged between pods never traverse iptables, so the service DNAT never applies: a pod reaches another pod's IP and the node's resolver directly but times out on `10.43.0.10` when the Service's only backend pod (CoreDNS, say) is on the same node as the caller, since a bridged hairpin reply skips the reverse NAT; backends on other nodes still answer, which is why it can stay latent until such a pod is rescheduled onto the node. Nothing looks wrong at first, because ARC keeps working from cached state; it fails only when it next needs a fresh GitHub token, when the controller logs `lookup api.github.com: i/o timeout`, a scale set's listener is not recreated, its `AutoscalingRunnerSet` stays `Pending` and the heartbeat reports `has no running listener`. The cluster role does this on every run for a Colima host (`tasks/colima_kernel.yml`, see its README's Colima kernel paragraph): it loads the module, writes `/etc/modules-load.d/br_netfilter.conf` and a sysctl file in the VM and sets the bridge sysctls. To repair a host before the playbook has run, load it with `colima ssh -- sudo modprobe br_netfilter`; check with `colima ssh -- ls /proc/sys/net/bridge`. +- **A Windows installer build (Wine) hangs on a node whose Colima VM is x86_64 when the VM runs 32-bit programs under qemu.** Colima's `binfmt` setting registers `qemu-i386` even in an x86_64 VM, and binfmt_misc then runs every 32-bit program there under emulation (`ps` shows `/usr/bin/qemu-i386` in front of the program), where `wineboot --init` never finishes. The role switches that entry off now and after every start (`tasks/colima_binfmt.yml`); by hand, `echo 0 | sudo tee /proc/sys/fs/binfmt_misc/qemu-i386` in the VM (a `colima ssh` shell) lasts until the next start. - **The k3s node name must stay stable across container recreations.** Without a pinned `hostname`, k3s derives the node name from the container's hostname (its ID), so every recreation (for example on an image pull) registers a new node and leaves the old one stale in etcd. The cluster role's `docker-compose.yml` pins every server host's own hostname to `${K3S_NODE_NAME:-k3s-server}`, Ansible-templated per host (defaulting to that host's own inventory name; `github_runner_cluster_node_name` overrides it, for example to keep a pre-existing device identity rather than forcing a disruptive rename). - **`kubectl get nodes` can succeed with zero nodes.** It returns an empty, still-successful list before the node object has registered. The role polls for at least one node before calling `kubectl wait`, which fails outright ("no matching resources found") against zero nodes. It then waits for the inventory's nodes by name, never for every node of the cluster, so a node outside the inventory that is `NotReady` is reported and does not fail the run. - **Zero runner pods in an `arc-runners-` namespace (or its per-profile `-` variant) when idle is expected, not a bug** — `minRunners: 0` means pods exist only while a job is running. diff --git a/roles/github_runner_cluster/README.md b/roles/github_runner_cluster/README.md index 4aacf65..a639b34 100644 --- a/roles/github_runner_cluster/README.md +++ b/roles/github_runner_cluster/README.md @@ -197,6 +197,8 @@ A restart stops every container on the host until the VM is back, which the node **Colima kernel.** On every Colima host, whether or not `github_runner_cluster_runtime_autostart` is on, once the VM answers (`tasks/colima_kernel.yml`), the role makes the VM's kernel pass bridged pod traffic through iptables, now and at every VM boot: it writes `/etc/modules-load.d/br_netfilter.conf` and `/etc/sysctl.d/90-github-runner-br-netfilter.conf` in the VM, runs `modprobe br_netfilter` when the VM has no `/proc/sys/net/bridge`, and sets `net.bridge.bridge-nf-call-iptables` and `net.bridge.bridge-nf-call-ip6tables` to 1 when they differ. Without the module a pod that talks to a Service whose only backend pod is on the same node gets no reply, because the Service's reverse NAT never applies to the bridged hairpin traffic; pods on other nodes keep working, so it stays latent until a single-backend Service such as CoreDNS lands on the node (the `br_netfilter` note in `docs/non-obvious-behaviour.md` has the symptoms). Everything runs in the VM through `colima ssh --profile `, as the VM's user with `sudo`, and no `become` on the host. A file is written only when its content differs, so a rerun changes nothing, and the module file takes the name the br_netfilter note in `docs/non-obvious-behaviour.md` told people to create by hand, so an existing one is replaced by the managed one. Under `--check` each change is reported and none is made, and nothing is read from a VM that a check run would only have started. Docker Desktop's VM is not reachable by the role and other runtimes are not touched. +**Colima 32-bit programs.** On every Colima host whose VM is x86_64, once the VM answers (`tasks/colima_binfmt.yml`), the role switches off the VM's `qemu-i386` binfmt_misc entry (`github_runner_cluster_colima_i386_binfmt_entry`), now and after every `colima start`. With Colima's `binfmt` setting on (its default), every start runs `binfmt --install 386,` in the VM ([`core.SetupBinfmt`](https://github.com/abiosoft/colima/blob/v0.10.3/core/core.go)), so an x86_64 VM also gets a handler for its own architecture's 32-bit programs. A binfmt_misc handler takes precedence over the kernel's own loader, so each 32-bit program in a pod on the node then runs under qemu user emulation, where Wine's 32-bit side never finishes creating a prefix and a Windows installer build on the node hangs. Now: the role writes `0` to the entry in the VM when it reads `enabled`, which restarts nothing; a 32-bit program already running under qemu stays there, and every one started afterwards runs natively. After every start: the role adds an `after-boot` provision script to the profile's `colima.yaml` (`github_runner_cluster_colima_i386_binfmt_off`), which Colima runs after its own binfmt setup and before the container runtime starts ([`colimaApp.Start`](https://github.com/abiosoft/colima/blob/v0.10.3/app/app.go)), keeping any script the profile already has. The VM reads the file only at its next start, so writing it restarts nothing either; the file is written back without its comments, and Colima writes it again from its own commented template at that start, keeping the script. Only that entry changes: Colima's `binfmt` setting stays on, so the VM keeps its handler for the foreign architecture (`qemu-aarch64`). An aarch64 VM is left alone, since 32-bit x86 is foreign there. Under `--check` the handler a real run would switch off is reported and nothing is written. + **Colima route guard.** On every Colima host, once the VM answers (`tasks/colima_route_guard.yml`), the role installs `files/route-guard.sh` in the VM as `github_runner_cluster_colima_route_guard_script` with a systemd service and timer of the same name (`github_runner_cluster_colima_route_guard_unit`) that run it at every VM boot and every `github_runner_cluster_colima_route_guard_interval_seconds` seconds (30 by default). A bridged Colima interface that loses its link keeps its default routes, and when they carry a lower metric than the working interface's, the VM's outbound traffic leaves by the dead one, so the node loses its peers and, with enough nodes cut off, the cluster loses its datastore quorum. The guard removes a default route whose gateway answers neither an ICMP echo through its own interface nor ARP (a resolved neighbour entry), and only while another default route's gateway answers, so it never leaves the VM with none and never judges a route that has no gateway. A DHCP renewal may add a removed route back, and the next tick removes it again. The files are written only when their content differs, and under `--check` each change is reported and none is made. **Colima VM size.** A Colima host can set its VM's memory in GiB and its number of CPUs, `github_runner_cluster_colima_memory_gib` and `github_runner_cluster_colima_cpus`, each a positive whole number; empty, the default, keeps what the profile has (`tasks/colima_size.yml`). Instead of a memory, a host can say what it must keep: `github_runner_cluster_colima_memory_reserved_gib`, the memory its other workloads need, and `github_runner_cluster_colima_memory_host_reserve_gib`, the memory kept for macOS itself (by default macOS's wired memory plus the resident memory of every process but the node VM's, measured on node hosts and rounded to a whole GiB). The VM then gets the host's memory (`ansible_facts['memtotal_mb']`) less both, rounded down to a whole GiB, but never less than the node floor: the guest's own use with no runner pod on it, `github_runner_cluster_colima_guest_baseline_gib`, plus one runner pod's memory limit, `github_runner_cluster_colima_runner_memory_limit_gib` (which the scale set's values set, so the cluster role is told it, and which a derivation requires), rounded up to a whole GiB. A derivation below the floor sizes the VM at the floor and prints a warning that the host keeps less than its reserves. A memory set explicitly wins over the derivation, but with a reserve set it must fit the same budget: a memory above the host's memory less both reserves fails the run, naming the host's memory and both reserves, before the VM is read or the node cordoned, so a workload whose reserve grows can never leave the VM larger than the host affords. With neither a memory nor a reserve the profile's memory is left as it is. A host whose runtime is not Colima ignores all of these, so they can be set for a group that mixes runtimes, and says so under `-v`, naming the values it skips. A value of the wrong kind, or a derivation without the runner's limit, fails the run before anything is read from the VM. The role reads the size of the VM Lima runs with `colima list --profile --json`, not the profile's configuration file, since `colima start` given a size while the profile runs writes it to the file and leaves the VM as it is ([`cmd/start.go`](https://github.com/abiosoft/colima/blob/v0.10.3/cmd/start.go)). A VM that already has every size set is left alone, so a rerun changes nothing. Otherwise the resize is a planned restart of the node, made one host at a time, each in its own turn, through the same quorum guard as moving a node between networks (`tasks/restart_guard.yml`): it refuses unless the other servers with a Ready node and a healthy etcd stay a majority of all servers; it takes the `fleet-regrade` Lease that regrading steps hold (`kube-system/fleet-regrade`, as `colima-resize/`), refusing while another step holds it, so a resize never overlaps a regrade step or another resize in this run or any other; it cordons the node, waits for its runner pods to finish and drains it (the role switch's `tasks/native/drain.yml`), checks the cluster again, runs `colima stop --profile ` and `colima start --profile --activate=false --memory --cpus ` (the flags of the values set), waits for the node to be Ready on a heartbeat later than the stop and, on a server, an etcd voter, uncordons it and gives the Lease back. Colima writes the new size to the profile's configuration, so the launchd job's later starts keep it. The node's container comes back with the VM (`restart: unless-stopped`). A node whose container is not running takes nothing from the cluster, so its VM is only stopped and started. When a step fails the node is uncordoned again and the run fails, saying whether the VM was stopped, and the Lease is given back, or expires after `github_runner_cluster_colima_resize_lease_seconds` when the API that holds it does not answer. Under `--check` the host's memory, the sizes, the Lease and the cluster are read, a refusal fails as it would in a real run, and the resize is reported and not made. diff --git a/roles/github_runner_cluster/defaults/main.yml b/roles/github_runner_cluster/defaults/main.yml index 7b032bc..c4f4083 100644 --- a/roles/github_runner_cluster/defaults/main.yml +++ b/roles/github_runner_cluster/defaults/main.yml @@ -336,6 +336,9 @@ github_runner_cluster_colima_modules_load_file: /etc/modules-load.d/br_netfilter github_runner_cluster_colima_sysctl_file: /etc/sysctl.d/90-github-runner-br-netfilter.conf # Derived, never set directly: the command that runs another command in the profile's VM as the VM's user, which has passwordless sudo. github_runner_cluster_colima_vm_command: "{{ ['colima', 'ssh', '--profile', github_runner_cluster_effective_runtime.colima_profile, '--'] }}" +# Not settings: the binfmt_misc entry Colima registers for 32-bit x86 programs, and the command that switches it off (tasks/colima_binfmt.yml). Colima's binfmt setting runs `binfmt --install 386,` at every start (core.SetupBinfmt in abiosoft/colima core/core.go), so an x86_64 VM also gets a qemu-i386 handler for its own architecture's 32-bit programs, which binfmt_misc then runs under emulation instead of natively. The command is the after-boot provision script the role adds to the profile, which Colima runs as the VM's user. +github_runner_cluster_colima_i386_binfmt_entry: /proc/sys/fs/binfmt_misc/qemu-i386 +github_runner_cluster_colima_i386_binfmt_off: "test ! -e {{ github_runner_cluster_colima_i386_binfmt_entry }} || echo 0 | sudo tee {{ github_runner_cluster_colima_i386_binfmt_entry }} > /dev/null" # The default route guard the role installs in a Colima VM (tasks/colima_route_guard.yml): how often it runs, and the names of its script and its systemd unit. The interval is a setting; the names are constants, variables only so the tests can narrow them. github_runner_cluster_colima_route_guard_interval_seconds: 30 github_runner_cluster_colima_route_guard_script: /usr/local/sbin/github-runner-route-guard diff --git a/roles/github_runner_cluster/tasks/colima_binfmt.yml b/roles/github_runner_cluster/tasks/colima_binfmt.yml new file mode 100644 index 0000000..4de9f44 --- /dev/null +++ b/roles/github_runner_cluster/tasks/colima_binfmt.yml @@ -0,0 +1,69 @@ +--- +# Colima hosts only (runtime.yml includes it once the runtime answers). Makes an x86_64 VM run 32-bit x86 programs natively, now and after every `colima start`. With Colima's binfmt setting on, every start registers qemu-i386 in the VM (github_runner_cluster_colima_i386_binfmt_off in defaults/main.yml), and a binfmt_misc handler takes precedence over the kernel's own loader, so each 32-bit program in a pod on the node runs under qemu user emulation, where Wine's 32-bit side never finishes creating a prefix. Only that entry is switched off: the handler for the foreign architecture (qemu-aarch64 in an x86_64 VM) stays as Colima set it. An aarch64 VM is left alone, since 32-bit x86 is foreign there. +# +# After every start: an after-boot provision script in the profile's colima.yaml, which Colima runs after its own binfmt setup (colimaApp.Start in abiosoft/colima app/app.go: the VM's post-start actions, then the after-boot scripts, then the container runtime). Now: the entry switched off in the VM directly, which needs no restart of the VM, Docker or k3s. Under --check each change is reported and none is made. + +- name: Read the VM's architecture + ansible.builtin.command: + argv: "{{ github_runner_cluster_colima_vm_command + ['uname', '-m'] }}" + environment: "{{ github_runner_cluster_runtime_environment }}" + register: github_runner_cluster_colima_binfmt_arch + changed_when: false + check_mode: false + +- name: Switch off the 32-bit x86 handler in an x86_64 VM + when: github_runner_cluster_colima_binfmt_arch.stdout | trim == 'x86_64' + vars: + github_runner_cluster_colima_binfmt_config_path: >- + {{ github_runner_cluster_runtime_colima_home or (ansible_facts['env']['HOME'] ~ '/.colima') }}/{{ github_runner_cluster_effective_runtime.colima_profile }}/colima.yaml + github_runner_cluster_colima_binfmt_provision: + mode: after-boot + script: "{{ github_runner_cluster_colima_i386_binfmt_off }}" + block: + - name: Read the profile's configuration + # //colima.yaml, the file colima start reads, as in tasks/link.yml. + ansible.builtin.slurp: + src: "{{ github_runner_cluster_colima_binfmt_config_path }}" + register: github_runner_cluster_colima_binfmt_config + check_mode: false + + - name: Add the provision script that switches the handler off after every start + # Colima writes `provision: null` for a profile with none. The file is written back without its comments; Colima writes it again from its own commented template at the next start (yamlutil.Save in abiosoft/colima util/yamlutil/yaml.go), keeping the script. A running VM reads the file only at its next start, so writing it restarts nothing. + vars: + github_runner_cluster_colima_binfmt_settings: "{{ github_runner_cluster_colima_binfmt_config.content | b64decode | from_yaml }}" + github_runner_cluster_colima_binfmt_scripts: "{{ github_runner_cluster_colima_binfmt_settings.provision or [] }}" + ansible.builtin.copy: + dest: "{{ github_runner_cluster_colima_binfmt_config_path }}" + content: "{{ github_runner_cluster_colima_binfmt_settings | combine({'provision': github_runner_cluster_colima_binfmt_scripts | union([github_runner_cluster_colima_binfmt_provision])}) | to_nice_yaml(indent=2) }}" + mode: "0644" + backup: true + when: github_runner_cluster_colima_binfmt_provision not in github_runner_cluster_colima_binfmt_scripts + + - name: Read whether the handler is on in the VM + # The entry's first line is `enabled` or `disabled`; a VM with no such entry fails the read, which reads as neither. + ansible.builtin.command: + argv: "{{ github_runner_cluster_colima_vm_command + ['cat', github_runner_cluster_colima_i386_binfmt_entry] }}" + environment: "{{ github_runner_cluster_runtime_environment }}" + register: github_runner_cluster_colima_binfmt_state + changed_when: false + failed_when: false + check_mode: false + + - name: Switch the handler off in the VM + # A 32-bit program already running under qemu keeps running there; every one started after this runs natively. + ansible.builtin.command: + argv: "{{ github_runner_cluster_colima_vm_command + ['sudo', 'tee', github_runner_cluster_colima_i386_binfmt_entry] }}" + stdin: "0" + environment: "{{ github_runner_cluster_runtime_environment }}" + changed_when: true + when: + - github_runner_cluster_colima_binfmt_state.stdout_lines[:1] == ['enabled'] + - not ansible_check_mode + + - name: Report the handler a real run would switch off in the VM + ansible.builtin.debug: + msg: "echo 0 > {{ github_runner_cluster_colima_i386_binfmt_entry }} in the VM" + changed_when: true + when: + - github_runner_cluster_colima_binfmt_state.stdout_lines[:1] == ['enabled'] + - ansible_check_mode diff --git a/roles/github_runner_cluster/tasks/runtime.yml b/roles/github_runner_cluster/tasks/runtime.yml index 30605fb..3d85152 100644 --- a/roles/github_runner_cluster/tasks/runtime.yml +++ b/roles/github_runner_cluster/tasks/runtime.yml @@ -5,6 +5,8 @@ # # On a Colima host it also makes the VM load br_netfilter and set the bridge sysctls now and at every VM boot (tasks/colima_kernel.yml), whatever the autostart setting says. # +# On a Colima host whose VM is x86_64 it also switches off the VM's qemu-i386 binfmt_misc entry now and after every start, so 32-bit x86 programs run natively (tasks/colima_binfmt.yml), whatever the autostart setting says. +# # Publishes github_runner_cluster_effective_runtime ({kind, colima_profile}), github_runner_cluster_runtime_colima_home, github_runner_cluster_runtime_environment (what docker and colima run with), github_runner_cluster_runtime_down_message and github_runner_cluster_runtime_up, for end_checks.yml. - name: Read the connecting user and its environment @@ -115,6 +117,13 @@ - github_runner_cluster_effective_runtime.kind == 'colima' - github_runner_cluster_runtime_up | bool +- name: Make an x86_64 Colima VM run 32-bit x86 programs natively + # Colima registers a qemu-i386 handler even in a VM of that architecture, and under it Wine never finishes creating a prefix. See tasks/colima_binfmt.yml. + ansible.builtin.include_tasks: colima_binfmt.yml + when: + - github_runner_cluster_effective_runtime.kind == 'colima' + - github_runner_cluster_runtime_up | bool + - name: Install the default route guard in the Colima VM # A bridged interface that loses its link keeps default routes with a lower metric than the working one, which cuts the VM off. See tasks/colima_route_guard.yml. ansible.builtin.include_tasks: colima_route_guard.yml diff --git a/tests/unit/test_runtime_autostart.py b/tests/unit/test_runtime_autostart.py index b4206d6..3509b42 100644 --- a/tests/unit/test_runtime_autostart.py +++ b/tests/unit/test_runtime_autostart.py @@ -33,6 +33,8 @@ 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]: @@ -150,8 +152,8 @@ def test_the_vm_needs_the_module_and_both_bridge_sysctls_on(self) -> None: def test_the_vm_is_prepared_last_in_the_runtime_tasks_and_only_for_colima_once_it_answers(self) -> None: tasks = yaml.safe_load((ROLE / "tasks" / "runtime.yml").read_text()) names = [task.get("ansible.builtin.include_tasks") or ("fail" if "ansible.builtin.fail" in task else None) for task in tasks] - self.assertEqual(names[-3:], ["fail", "colima_kernel.yml", "colima_route_guard.yml"]) - for task in tasks[-2:]: + self.assertEqual(names[-4:], ["fail", "colima_kernel.yml", "colima_binfmt.yml", "colima_route_guard.yml"]) + for task in tasks[-3:]: self.assertEqual(task["when"], ["github_runner_cluster_effective_runtime.kind == 'colima'", "github_runner_cluster_runtime_up | bool"]) self.assertNotIn("github_runner_cluster_runtime_autostart", json.dumps(task)) @@ -161,6 +163,9 @@ def test_the_readmes_say_what_the_role_does_to_the_vm(self) -> None: self.assertIn(MODULES_FILE, readme) self.assertIn(SYSCTL_FILE, readme) self.assertIn("colima_kernel.yml", (ROOT / "docs" / "non-obvious-behaviour.md").read_text()) + self.assertIn("**Colima 32-bit programs.**", readme) + self.assertIn("colima_binfmt.yml", readme) + self.assertIn("colima_binfmt.yml", (ROOT / "docs" / "non-obvious-behaviour.md").read_text()) def test_both_includes_run_on_macos_only(self) -> None: tasks = yaml.safe_load((ROLE / "tasks" / "main.yml").read_text()) @@ -411,6 +416,9 @@ def sysctl_file(key): 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": @@ -1145,7 +1153,7 @@ def test_a_second_run_with_the_daemon_in_place_changes_nothing_and_loads_nothing 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|sysctl -n|systemctl is-active|dpkg-query) )", call)], []) + 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)) @@ -1262,7 +1270,7 @@ def assert_a_second_run_changes_nothing(self, context: str, context_host: str | 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|sysctl -n|systemctl is-active|dpkg-query) )", call)], []) + 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: @@ -1509,6 +1517,90 @@ def test_a_stopped_runtime_that_is_not_started_fails_before_the_vm_is_touched(se 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)