instances: root ExecStop sends one SIGTERM to MAINPID (#528)
Under PrivatePIDs systemd sometimes marks an instance's main process 'not our child', and a KillMode=mixed stop then SIGKILLs it right after its SIGTERM. A root ExecStop (carlos instance-stop) now signals the main process once through a pidfd, waits up to 18 s, then SIGKILLs; TimeoutStopFailureMode=kill. KillMode and the trampoline are unchanged (Paul's option 2). Root-runner witness 20261108T183451-994df0 PASS incl. old/new unit and binary mixes; Astra R1 READY; census approved on #280. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from instance-stop-execstop-528 into main.
19 files changed,
+1,642
−2
docs/site/cli.md+7 −0docs/superpowers/notes/census-proposal-instance-stop-execstop-528.md+29 −0docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md+260 −0internal/host/claimunit_template.go+2 −0internal/host/execstop_probe_rootrunner_linux_test.go+926 −0internal/host/plan14_generation_registry_root_linux_test.go+9 −0internal/host/units/carlos-instance-gen@.service+10 −0internal/host/units/carlos-instance-sidecar@.service+10 −0internal/host/units/carlos-instance@.service+10 −0internal/host/units_execstop_test.go+65 −0internal/instanceexec/stop.go+14 −0internal/instanceexec/stop_linux.go+124 −0internal/instanceexec/stop_linux_test.go+141 −0internal/instanceexec/stop_other.go+14 −0internal/provision/agent_start_demo_3_census_test.go+1 −1internal/provision/plan14_e_write_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-instance-stop-execstop-528.tsv+16 −0main.go+2 −0
CI passed — run details
diff --git a/docs/site/cli.md b/docs/site/cli.md| index b82b6c34c..421f56a9b 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -3288,6 +3288,13 @@ exit record in the instance's run directory from the four variables |
| systemd provides; the agent proves termination from the unit's state and |
| its cgroup, not from this file. |
| +### carlos instance-stop |
| + |
| +`ExecStop=` of the run, generation and sidecar templates, run as root. It |
| +sends the unit's main process one SIGTERM, waits up to 18 seconds for it to |
| +exit, then sends SIGKILL. systemd passes it `$MAINPID`, and it signals only |
| +a process in the unit's own cgroup. |
| + |
| ### carlos instance-probe |
| The isolation probe, run under the same namespace text as the instance |
diff --git a/docs/superpowers/notes/census-proposal-instance-stop-execstop-528.md b/docs/superpowers/notes/census-proposal-instance-stop-execstop-528.md| new file mode 100644 |
| index 000000000..e0ab96e42 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-instance-stop-execstop-528.md |
| @@ -0,0 +1,29 @@ |
| +# Census approval: instance-stop-execstop-528 |
| + |
| +Ruling `census-ruling-instance-stop-execstop-528`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/claimunit_template.go` `const claimBoundTemplate` | body | unchanged (1) | one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added | |
| +| `internal/host/units/carlos-instance-gen@.service` `external` | body | unchanged (1) | one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added | |
| +| `internal/host/units/carlos-instance-sidecar@.service` `external` | body | unchanged (1) | one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added | |
| +| `internal/host/units/carlos-instance@.service` `external` | body | unchanged (1) | one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added | |
| + |
| +Envelopes re-pinned: `.`, `internal/host`, `internal/host/units`, `internal/instanceexec`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/host/claimunit_template.go` `const claimBoundTemplate`: authority, task E2. Basis: PROPOSED E51: Root-only bound-unit template is held inside the claim renderer; ordinary bootstrap never enumerates or installs it. |
| +- `internal/host/units/carlos-instance-gen@.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else;rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates) |
| +- `internal/host/units/carlos-instance-sidecar@.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else;rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates) |
| +- `internal/host/units/carlos-instance@.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: one namespace-block line added after TemporaryFileSystem=/dev/mqueue:ro, TemporaryFileSystem=/dev/pts:ro (with its comment): PID 1 mounts an empty read-only tmpfs over the private /dev/pts, hiding the host devpts PrivateDevices= binds in; no bind source, Exec line, user or path read by root added; the block stays byte-identical across the binary templates (TestInstanceTemplatesShareOneNamespace);rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates) |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/instanceexec/stop_linux.go:procCgroup`: reads +file:ReadFile; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `b970bb28c5a633d2572a1da549030e9258cfdabb6322ddffdd0ebf41b56c464c` → `75fb3eb24d0bf3a8405b929675d919ec88f15386d43e9ff687ce138a7ed968a4`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-instance-stop-execstop-528.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md b/docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md| new file mode 100644 |
| index 000000000..7ae5d4f2b |
| --- /dev/null |
| +++ b/docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md |
| @@ -0,0 +1,260 @@ |
| +# Instance stops under PrivatePIDs: a root ExecStop (#528, option 2) |
| + |
| +Date: 2026-11-08. Status: design for Paul's option (2), relayed by the |
| +coordinator. Supersedes branch `instance-stop-528` (KillMode=control-group |
| +plus a stop-policy gate), which is parked unmerged. |
| + |
| +## Problem and cause (unchanged from the first branch) |
| + |
| +Some instance stops end `Result=signal`: the app is SIGKILLed with no |
| +SIGTERM grace. Cause, from the systemd v257.9 source and the dev journals: |
| + |
| +- Under `PrivatePIDs=yes`, systemd forks once more inside the new PID |
| + namespace. If the manager reads the child's pidref before the intermediate |
| + parent has exited, it marks the main process alien ("not our child"). |
| +- At stop, `unit_kill_context_one()` sends SIGTERM to an alien main but |
| + returns 0 ("nothing to wait for"), and `KillMode=mixed` signals nothing |
| + else in that phase. So `service_enter_signal()` escalates straight to |
| + SIGKILL. The trampoline never gets to forward the SIGTERM. |
| +- Every `signal` failure on dev belongs to an alien invocation (demo box |
| + 17/17, sophie generations 73/73); no non-alien stop failed. |
| + |
| +## Fix |
| + |
| +Add, to the binary run, generation and sidecar templates and the claim-bound |
| +template: |
| + |
| + ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID |
| + TimeoutStopFailureMode=kill |
| + |
| +`instance-stop` is a new root-run verb. It sends exactly one SIGTERM (and a |
| +SIGCONT) to the main process and waits for it to exit, for up to 18 s. If |
| +the main process is still alive at that deadline, the helper sends SIGKILL, |
| +waits up to 1 s more for the exit, and returns: at most 19 s, inside the |
| +unit's `TimeoutStopSec=20`. |
| + |
| +`TimeoutStopFailureMode=kill` closes the remaining gap (Astra spec R1 P1). |
| +systemd arms its stop timer before it spawns the helper, so a slow helper |
| +start could still let the timer fire while the main process is alive. With |
| +the default mode (`terminate`), a timeout in `SERVICE_STOP` enters |
| +`SERVICE_STOP_SIGTERM` and signals the main process again: a second SIGTERM. |
| +With `kill` it enters `SERVICE_STOP_SIGKILL` (service.c, |
| +`service_dispatch_timer`, case `SERVICE_STOP`). The mode changes two |
| +timeouts only: |
| +- ExecStop running past 20 s: SIGKILL instead of a second SIGTERM. |
| +- ExecStopPost (`instance-exit`) running past 20 s: SIGKILL to what is left |
| + instead of SIGTERM. |
| +The SIGTERM phase's own timeout already ends in SIGKILL in both modes. If |
| +the helper stalled for 20 s before it signalled (three syscalls; this would |
| +be pathological), the app gets SIGKILL with no SIGTERM. That cell is listed |
| +below. |
| + |
| +Then: |
| + |
| +- `KillMode=mixed`, `TimeoutStopSec=20`, `SuccessExitStatus=` and the |
| + trampoline are unchanged. No pins, locks or rollback state. |
| +- The trampoline forwards the SIGTERM to the app as it does today (the |
| + trampoline is unchanged, so "old" and "new" trampolines behave alike). |
| +- When `ExecStop` returns, systemd enters its own SIGTERM phase. In every |
| + case the helper saw the exit, the main process is gone: systemd signals no |
| + main process, and under `mixed` it goes straight to the final SIGKILL of |
| + anything left in the cgroup, then `ExecStopPost`. The result comes from |
| + the main process's exit: 0 or 143 is `success`. If the helper returned |
| + without seeing the exit (a main process stuck in an uninterruptible wait |
| + after its SIGKILL), systemd's phases go on as today. Its SIGTERM to a |
| + process with a SIGKILL pending is never handled. The activator's own |
| + observer decides completion, as below. |
| + |
| +The phases, kept apart: |
| +- **Graceful wait:** up to 18 s from the helper's SIGTERM. |
| +- **Kill request:** SIGKILL through the pidfd. |
| +- **Observed exit:** the pidfd polls readable, up to 1 s later. |
| +- **Completed unit stop:** systemd's own phases and `ExecStopPost`, not |
| + bounded by the helper. A main process stuck in an uninterruptible wait |
| + with its SIGKILL pending does not keep systemd waiting forever: its |
| + kill-phase timer runs out, it runs `ExecStopPost`, and the unit ends |
| + failed with processes left. The safeguard is the activator's unit |
| + observer (`unitproc.go`). It holds the stop as unproven while the unit's |
| + cgroup is populated, and does not release the instance. |
| + |
| +### How the helper finds and signals the main process |
| + |
| +Settled on a real box (root runner, run 20261108T174833-c5142a, probe |
| +`TestRootExecStopProbe`). A `+` ExecStop in the shipped |
| +`carlos-instance@.service`: |
| + |
| +- runs as uid 0 with full capabilities, **in the host PID namespace** |
| + (`/proc/self/ns/pid` equals PID 1's), so systemd's `$MAINPID` names the |
| + right process. The `+` prefix turns PrivatePIDs off for that command; |
| +- runs in the unit's own mount namespace: the template's explicit mounts |
| + are kept, `/opt/carlos/carlos` is present, and `/proc` shows host PIDs; |
| +- runs in the unit's own cgroup (it is the unit's control process); |
| +- has **no seccomp filter** (`Seccomp: 0`). The tenant syscall filter from |
| + f4d9b095 does not apply to it, so pidfd calls are never filtered. |
| + |
| +The helper: |
| + |
| +1. takes `$MAINPID` from argv (systemd expands it; empty when there is no |
| + main process, for example after the main process has already exited). |
| + With no PID it exits 0 and does nothing; |
| +2. `pidfd_open(MAINPID)`. A failure (`ESRCH`: already gone) exits 0; |
| +3. reads `/proc/self/cgroup` and `/proc/<MAINPID>/cgroup`, and refuses |
| + unless they are the same cgroup, then checks the pidfd is still alive |
| + (`pidfd_send_signal(fd, 0)`). Because the pidfd holds the PID until |
| + that process is reaped, a live pidfd after the read means the cgroup |
| + read was of the same process. A PID reused by a stranger can never be |
| + signalled; |
| +4. `pidfd_send_signal(fd, SIGTERM)` once, then `SIGCONT`. As systemd's own |
| + stop does, a stopped main process must run to forward the SIGTERM; |
| +5. polls the pidfd for exit, up to 18 s. On timeout it sends |
| + `pidfd_send_signal(fd, SIGKILL)`, waits up to 1 s for the exit, and |
| + returns. |
| + |
| +It reads nothing a tenant writes: argv from systemd, its own and the main |
| +process's `/proc/.../cgroup` (kernel-provided), and a pidfd. It always exits |
| +0 once its arguments parse; the `-` prefix makes any failure harmless. |
| + |
| +`systemctl kill --kill-whom=main` was evaluated. It does reach the main |
| +process (15/15 on the runner; none of those starts was alien, so alien reach |
| +is unproven). It is not chosen: it puts a D-Bus round trip to the manager |
| +inside the manager's own stop job, and it still needs a separate way to wait |
| +for the exit. |
| + |
| +### Why the SIGKILL comes from the helper |
| + |
| +An app that ignores SIGTERM has two possible endings: |
| + |
| +- **The helper returns at its deadline with the main process alive.** |
| + systemd's own SIGTERM phase then signals the main process again, so the |
| + app gets a second SIGTERM. Then it waits a further `TimeoutStopSec` (40 s |
| + in all), or SIGKILLs at once if the main process is alien. The two |
| + endings are inconsistent, and a draining app can be hit by the second |
| + SIGTERM. |
| +- **The helper SIGKILLs at its deadline (chosen).** The app gets exactly |
| + one SIGTERM and 18 s, then SIGKILL, whether or not the main process is |
| + alien. The helper is done within 19 s, inside today's 20 s. A process that |
| + dies on its SIGKILL ends the stop there; one stuck in the kernel is |
| + bounded by systemd's own phases, as today. The unit's |
| + result is `signal` (main killed by 9). Today the same app ends `timeout`. |
| + Both say "did not stop on SIGTERM". |
| + |
| +## The mix matrix |
| + |
| +Unit **old** = today's template (no `ExecStop`). Unit **new** = this |
| +branch's. Binary **old** = a `/opt/carlos/carlos` without the |
| +`instance-stop` verb: it prints usage and exits 2. Binary **new** has the |
| +verb. The trampoline is the same code in both, and every row is the same |
| +for the run, generation and sidecar templates. |
| + |
| +The binary that matters for ExecStop is the one on disk at stop time. |
| +systemd runs `/opt/carlos/carlos` fresh, via the unit's bind of it. The |
| +trampoline that matters is the one that started the instance. |
| + |
| +| unit | binary at stop | main | app | what the app gets | |
| +| --- | --- | --- | --- | --- | |
| +| old | any | non-alien | drains / fast / ignores | today: one forwarded SIGTERM; an app that ignores it gets SIGKILL after 20 s (`timeout`) | |
| +| old | any | alien | any | today: SIGTERM then SIGKILL at once (`signal`, #528) | |
| +| new | new | non-alien or alien | drains | one SIGTERM from the helper, forwarded by the trampoline; exits 0 or 143 (`success`) | |
| +| new | new | non-alien or alien | exits fast | one SIGTERM; exits; `success` (the helper's poll returns at once) | |
| +| new | new | non-alien or alien | ignores | one SIGTERM; SIGKILL from the helper at 18 s (`signal`) | |
| +| new | new | any | stopped (SIGSTOP) trampoline | one SIGTERM, then SIGCONT; drains as above | |
| +| new | new | any | helper stalls 20 s before signalling | no SIGTERM; SIGKILL at 20 s (`TimeoutStopFailureMode=kill`); pathological, never a second SIGTERM | |
| +| new | old | any | any | ExecStop exits 2 (unknown verb), which `-` ignores; then today's row for its alien state | |
| + |
| +The cases around a roll: |
| + |
| +- **A roll's `daemon-reload` with instances running** (new units over old): |
| + ExecStop is read at stop time, so a running instance started under the |
| + old unit stops through the helper, with whatever binary is on disk. That |
| + is the "new unit" rows: one SIGTERM, or today's behaviour if the binary |
| + on disk is old. The edge restart that ends every apply stops instances |
| + this way. |
| +- **Rollback** (old units back over new, old binary back): a running |
| + instance loses its ExecStop at the reload and stops as today. In the |
| + window where the binary is already old and the units are still new, the |
| + "new unit, old binary" row applies: today's behaviour. |
| +- **A box whose binary is older than its units** (any order a manual roll |
| + script uses): "new unit, old binary", today's behaviour. |
| + |
| +No cell gives the app two SIGTERMs. Once the helper has signalled, the app |
| +gets exactly one. The only cells with no SIGTERM to a live main process are |
| +today's (old units, or an old binary) and the pathological stall where |
| +systemd's timer fires before the helper signals; there the app gets SIGKILL |
| +and no SIGTERM, never a second. Every other cell is either exactly one |
| +SIGTERM or today's behaviour. |
| + |
| +## Stop paths (when ExecStop runs, and when it does not) |
| + |
| +From `service.c` v257.9 (Astra spec R1 P2): |
| + |
| +| path | ExecStop? | what the app gets | |
| +| --- | --- | --- | |
| +| `systemctl stop` of an active unit (hibernate, deploy swap, demo takedown, `BindsTo=` edge stop) | yes (`service_stop` → `service_enter_stop`) | the matrix above | |
| +| `RuntimeMaxSec=` expiry | yes (`service_enter_stop`). Seen on the runner: one SIGTERM, drained, `Result=timeout` | demos keep their bound: SIGTERM, at most 18 s, SIGKILL | |
| +| main process exits cleanly by itself | yes, with `$MAINPID` empty (`service_enter_running` → `service_enter_stop`) | nothing: the helper has no PID and exits 0 | |
| +| main process fails, crashes, is OOM-killed | per systemd's normal failure paths, signal phases or stop with no main process | today's behaviour; the helper, if run, has no live PID | |
| +| `systemctl stop` while the unit is still starting (start/start-post) | no (`service_stop` signals directly) | today's behaviour (Type=simple is active almost at once) | |
| +| instance-control's `killGen` (SIGKILL, then stop) | the stop runs it with the main process already dead | today's: an intentional kill | |
| +| `systemctl kill` | no | unchanged | |
| + |
| +## Scope |
| + |
| +- **In scope:** the binary `carlos-instance@`, `carlos-instance-gen@` and |
| + `carlos-instance-sidecar@` templates and `claimBoundTemplate`. Demo |
| + instances are binary instances, so they are covered. |
| +- **Out of scope, recorded on #528:** |
| + - The oneshot templates (seed, cmd, tty). A oneshot's stop while it runs |
| + goes straight to the SIGTERM phase, without ExecStop. |
| + - The rootfs templates. `+` under `RootImage=` is unproven on a real |
| + box, and the rootfs witness needs an image. They keep today's |
| + behaviour, and get a follow-up. |
| + |
| +## Tests |
| + |
| +- **Unit:** the verb's argument handling (empty, junk, own PID), the |
| + cgroup-match refusal, signal-once-then-wait, kill-at-deadline, and |
| + continuing a stopped main process. All run against real child processes. |
| +- **Templates:** an invariant. Every template in scope carries exactly |
| + `ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID`, keeps |
| + `KillMode=mixed`, and its `TimeoutStopSec=` exceeds the helper's budget. |
| +- **Root-runner witness** `TestRootInstanceStopExecStop`, on the shipped |
| + template with only its `[Unit]` couplings removed. It requires: |
| + - **old unit, new binary:** the race reproduces (at least one alien start |
| + ends `Result=signal`); |
| + - **new unit, new binary:** 40 draining and 40 fast-exit stops, all |
| + `success` with exactly one SIGTERM, with at least one alien start in |
| + each set; |
| + - **ignores SIGTERM:** one SIGTERM, then a kill within the bound; |
| + - **new unit, old binary:** the old binary (built from origin/main) at |
| + `/opt/carlos/carlos`, under the new unit, behaves as today, with no |
| + second SIGTERM; |
| + - **old trampoline started, new unit at stop:** start under the old unit |
| + with the old binary, then install the new unit and binary and |
| + `daemon-reload`; the stop delivers one SIGTERM; |
| + - **rollback:** start under the new unit and binary, then put the old unit |
| + back and `daemon-reload`; the stop behaves as today; |
| + - **RuntimeMaxSec=:** the unit expires through the helper, with one |
| + SIGTERM; |
| + - **stopped main:** the trampoline is SIGSTOPped, then the unit is |
| + stopped; the app drains on one SIGTERM; |
| + - **main exits by itself:** ExecStop runs with no `$MAINPID` and the unit |
| + ends `success`; |
| + - **manager timeout before the helper signals** (a stalled ExecStop under |
| + a 3 s `TimeoutStopSec=`): no SIGTERM, SIGKILL at the timer, empty |
| + cgroup; |
| + - **manager timeout after the helper's SIGTERM** (an app that ignores |
| + it, 3 s `TimeoutStopSec=`): exactly one SIGTERM, then SIGKILL, empty |
| + cgroup; |
| + - for every stop, the final unit result, `ExecMainStatus`, the |
| + ExecStopPost exit record in the run directory, and an empty cgroup. |
| + The activator's completion and retention are unchanged code |
| + (`unitproc.go`), which the unit tests of that package already cover. |
| + The witness drives systemd directly. |
| + |
| +## Census |
| + |
| +`instance-stop` is a new root-run unit. It reads only argv (systemd's |
| +`$MAINPID`), `/proc/self/cgroup` and `/proc/<MAINPID>/cgroup`, and acts only |
| +through a pidfd. The three templates and the claim-bound template change by |
| +one ExecStop line each. `make census-card`, CLAIMS, `census-propose`, then |
| +Astra's cross-family verdict on #280. |
diff --git a/internal/host/claimunit_template.go b/internal/host/claimunit_template.go| index 62de03963..748319fde 100644 |
| --- a/internal/host/claimunit_template.go |
| +++ b/internal/host/claimunit_template.go |
| @@ -8,6 +8,7 @@ After=data-instances.mount run-carlos-instances.mount run-carlos-logs.mount |
| [Service] |
| Type=simple |
| ExecStart=/opt/carlos/carlos instance-exec run %I |
| +ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID |
| ExecStopPost=/opt/carlos/carlos instance-exit run %I |
| User=carlos |
| Group=carlos |
| @@ -15,6 +16,7 @@ Slice=carlos-instances-%i.slice |
| Restart=no |
| KillMode=mixed |
| TimeoutStopSec=20 |
| +TimeoutStopFailureMode=kill |
| SuccessExitStatus=129 130 141 143 |
| StandardOutput=file:/run/carlos/logs/%I.run.sock |
| StandardError=inherit |
diff --git a/internal/host/execstop_probe_rootrunner_linux_test.go b/internal/host/execstop_probe_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..d9c16ac18 |
| --- /dev/null |
| +++ b/internal/host/execstop_probe_rootrunner_linux_test.go |
| @@ -0,0 +1,926 @@ |
| +//go:build linux && rootrunner |
| + |
| +package host |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io/fs" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/instanceexec" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// instanceStopTenantArg is the tenant's argv[1]; the rootrunner TestMain |
| +// dispatches it to instanceStopTenant. |
| +const instanceStopTenantArg = "instance-stop-tenant" |
| + |
| +// instanceStopTenant is the app inside the witness unit, under the real |
| +// trampoline. It writes "up" once its SIGTERM handler is in place and |
| +// appends a line to "terms" for every SIGTERM it gets. STOPWIT_MODE picks |
| +// what a SIGTERM does: "drain" keeps counting SIGTERMs for 300 ms, writes |
| +// "drained" and exits 0; "fast" exits 0 at once; "ignore" never exits on |
| +// its own, so only systemd's SIGKILL ends it. |
| +func instanceStopTenant() { |
| + sigs := make(chan os.Signal, 8) |
| + signal.Notify(sigs, syscall.SIGTERM) |
| + if err := os.WriteFile("up", []byte(strconv.Itoa(os.Getpid())), 0o644); err != nil { |
| + os.Exit(3) |
| + } |
| + term := func() { |
| + f, err := os.OpenFile("terms", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644) |
| + if err == nil { |
| + _, _ = f.WriteString("term\n") |
| + _ = f.Close() |
| + } |
| + } |
| + mode := os.Getenv("STOPWIT_MODE") |
| + if mode == "exit" { |
| + time.Sleep(300 * time.Millisecond) |
| + os.Exit(0) |
| + } |
| + <-sigs |
| + term() |
| + switch mode { |
| + case "fast": |
| + os.Exit(0) |
| + case "drain": |
| + drain := time.After(300 * time.Millisecond) |
| + for { |
| + select { |
| + case <-sigs: |
| + term() |
| + case <-drain: |
| + _ = os.WriteFile("drained", nil, 0o644) |
| + os.Exit(0) |
| + } |
| + } |
| + } |
| + for range sigs { |
| + term() |
| + } |
| +} |
| + |
| +func TestRootExecStopProbe(t *testing.T) { |
| + if os.Geteuid() != 0 { |
| + t.Fatal("needs real root") |
| + } |
| + if pid1, err := os.ReadFile("/proc/1/comm"); err != nil || strings.TrimSpace(string(pid1)) != "systemd" { |
| + t.Fatalf("needs systemd as PID 1: %q %v", pid1, err) |
| + } |
| + var st unix.Statfs_t |
| + if err := unix.Statfs("/sys/fs/cgroup", &st); err != nil || st.Type != unix.CGROUP2_SUPER_MAGIC { |
| + t.Fatalf("needs cgroup v2: %#x %v", st.Type, err) |
| + } |
| + for _, p := range []string{"/opt/carlos/carlos", "/etc/carlos", "/data/instances", "/run/carlos", "/run/carlos-control"} { |
| + if _, err := os.Lstat(p); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("%s exists: this witness runs only on a fresh runner (%v)", p, err) |
| + } |
| + } |
| + uid, gid := generationRunnerRegistryUser(t) |
| + |
| + ctl := func(args ...string) (string, error) { |
| + out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + return strings.TrimSpace(string(out)), err |
| + } |
| + must := func(args ...string) string { |
| + t.Helper() |
| + out, err := ctl(args...) |
| + if err != nil { |
| + t.Fatalf("systemctl %s: %v: %s", strings.Join(args, " "), err, out) |
| + } |
| + return out |
| + } |
| + |
| + // Every path this test makes, removed in reverse on cleanup once the |
| + // unit has stopped (cleanups run last-registered first). |
| + var made []string |
| + t.Cleanup(func() { |
| + for i := len(made) - 1; i >= 0; i-- { |
| + if err := os.RemoveAll(made[i]); err != nil { |
| + t.Errorf("cleanup %s: %v", made[i], err) |
| + } |
| + } |
| + if out, err := ctl("daemon-reload"); err != nil { |
| + t.Errorf("daemon-reload: %v %s", err, out) |
| + } |
| + }) |
| + mkdirs := func(path string, owner bool) { |
| + t.Helper() |
| + var missing []string |
| + for d := path; ; d = filepath.Dir(d) { |
| + if _, err := os.Lstat(d); err == nil { |
| + break |
| + } |
| + missing = append(missing, d) |
| + } |
| + for i := len(missing) - 1; i >= 0; i-- { |
| + if err := os.Mkdir(missing[i], 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, missing[i]) |
| + } |
| + if owner { |
| + if err := os.Chown(path, uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + write := func(path string, data []byte, mode os.FileMode) { |
| + t.Helper() |
| + mkdirs(filepath.Dir(path), false) |
| + if err := os.WriteFile(path, data, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, path) |
| + } |
| + |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bin, err := os.ReadFile(self) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + host := "stopwit.example.com" |
| + iid := provision.InstanceID(host) |
| + data, rundir := "/data/instances/"+iid, "/run/carlos/instances/"+iid |
| + write("/opt/carlos/carlos", bin, 0o755) |
| + mkdirs("/etc/carlos", false) |
| + mkdirs(data, true) |
| + mkdirs(rundir, true) |
| + mkdirs("/run/carlos/logs", false) |
| + exe := "/run/carlos-control/exe/" + iid |
| + // As ensureExe lays it out: app is a link PID 1 chases to the build, |
| + // which must sit on an exec mount (/run is noexec). |
| + if _, err := os.Lstat("/opt/carlos-stopwit-app"); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("/opt/carlos-stopwit-app exists (%v)", err) |
| + } |
| + write("/opt/carlos-stopwit-app", bin, 0o755) |
| + mkdirs(exe, false) |
| + if err := os.Symlink("/opt/carlos-stopwit-app", exe+"/app"); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, exe+"/app") |
| + mkdirs(exe+"/live", false) |
| + if err := os.Symlink("../app", exe+"/live/"+host); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, exe+"/live/"+host) |
| + |
| + // The shipped template, couplings removed: BindsTo= the edge and |
| + // Requires= the three mounts are the box's, not the stop's. |
| + raw, err := unitsFS.ReadFile("units/carlos-instance@.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var lines []string |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + if strings.HasPrefix(line, "BindsTo=") || strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") { |
| + continue |
| + } |
| + lines = append(lines, line) |
| + } |
| + if !hasDirective(string(raw), "PrivatePIDs=yes") { |
| + t.Fatal("embedded template is not a PrivatePIDs template") |
| + } |
| + template := "carlos-stopwit@.service" |
| + for _, dir := range []string{"/etc/systemd/system", "/run/systemd/system", "/usr/lib/systemd/system"} { |
| + if _, err := os.Lstat(filepath.Join(dir, template)); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("%s already present in %s (%v)", template, dir, err) |
| + } |
| + } |
| + write("/run/systemd/system/"+template, []byte(strings.Join(lines, "\n")), 0o644) |
| + unit := strings.Replace(instancectl.UnitName(instancectl.RoleRun, host), "carlos-instance@", "carlos-stopwit@", 1) |
| + dropDir := "/run/systemd/system/" + template + ".d" |
| + // Starting a unit in a per-host slice starts its parents too; stop on |
| + // cleanup the ones this test found inactive. |
| + var stopSlices []string |
| + for _, s := range []string{instancectl.InstancesSlice, "carlos.slice"} { |
| + if out, _ := ctl("show", "-p", "ActiveState", "--value", s); out == "inactive" { |
| + stopSlices = append(stopSlices, s) |
| + } |
| + } |
| + t.Cleanup(func() { |
| + for _, s := range stopSlices { |
| + _, _ = ctl("stop", s) |
| + } |
| + }) |
| + t.Cleanup(func() { |
| + _, _ = ctl("stop", unit) |
| + _, _ = ctl("reset-failed", unit) |
| + _, _ = ctl("stop", instancectl.SliceName(host)) |
| + }) |
| + |
| + launch := func(mode string) { |
| + t.Helper() |
| + l := instancectl.Launch{Schema: instancectl.LaunchSchema, Host: host, Argv: []string{"/opt/carlos/live/" + host, instanceStopTenantArg}, Env: []string{"STOPWIT_MODE=" + mode}} |
| + b, _ := json.Marshal(l) |
| + p := filepath.Join(data, instancectl.LaunchFileName(instancectl.RoleRun)) |
| + if err := os.WriteFile(p, b, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + dropIn := func(name, body string) { |
| + t.Helper() |
| + write(filepath.Join(dropDir, name), []byte("[Service]\n"+body+"\n"), 0o644) |
| + must("daemon-reload") |
| + } |
| + undrop := func(name string) { |
| + t.Helper() |
| + if err := os.Remove(filepath.Join(dropDir, name)); err != nil { |
| + t.Fatal(err) |
| + } |
| + must("daemon-reload") |
| + } |
| + |
| + type outcome struct { |
| + result, mainCode, mainStatus string |
| + alien, drained bool |
| + terms int |
| + stop time.Duration |
| + } |
| + // ExecMainCode is a CLD_* number: 2 killed, 3 dumped. A clean exit |
| + // reads 1, or 0 once the unit has gone inactive on systemd 257. |
| + killedOrDumped := func(code string) bool { return code == "2" || code == "3" } |
| + var signalMain func(pid string) |
| + _ = killedOrDumped |
| + cycle := func() outcome { |
| + t.Helper() |
| + for _, f := range []string{"up", "terms", "drained"} { |
| + _ = os.Remove(filepath.Join(data, f)) |
| + } |
| + _, _ = ctl("reset-failed", unit) |
| + must("start", unit) |
| + inv := must("show", "-p", "InvocationID", "--value", unit) |
| + deadline := time.Now().Add(15 * time.Second) |
| + for { |
| + if _, err := os.Stat(filepath.Join(data, "up")); err == nil { |
| + break |
| + } |
| + if s, _ := ctl("show", "-p", "ActiveState", "--value", unit); s != "active" && s != "activating" { |
| + log, _ := exec.Command("journalctl", "-o", "cat", "--no-pager", "-n", "30", "-u", unit).CombinedOutput() |
| + out, _ := os.ReadFile("/run/carlos/logs/" + iid + ".run.sock") |
| + t.Fatalf("unit %s before the tenant was up: %s\ntrampoline and tenant output: %s", s, log, out) |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("tenant never came up") |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + cg := must("show", "-p", "ControlGroup", "--value", unit) |
| + if cg == "" { |
| + t.Fatal("running unit has no ControlGroup") |
| + } |
| + began := time.Now() |
| + if signalMain != nil { |
| + signalMain(must("show", "-p", "MainPID", "--value", unit)) |
| + } else { |
| + must("stop", unit) |
| + } |
| + o := outcome{stop: time.Since(began)} |
| + o.result = must("show", "-p", "Result", "--value", unit) |
| + o.mainCode = must("show", "-p", "ExecMainCode", "--value", unit) |
| + o.mainStatus = must("show", "-p", "ExecMainStatus", "--value", unit) |
| + if b, err := os.ReadFile(filepath.Join(data, "terms")); err == nil { |
| + o.terms = strings.Count(string(b), "term\n") |
| + } |
| + if _, err := os.Stat(filepath.Join(data, "drained")); err == nil { |
| + o.drained = true |
| + } |
| + // The "not our child" line is logged at start; journald may lag. |
| + for i := 0; i < 20; i++ { |
| + out, _ := exec.Command("journalctl", "-o", "cat", "--no-pager", "_PID=1", "INVOCATION_ID="+inv).CombinedOutput() |
| + if strings.Contains(string(out), "not our child") { |
| + o.alien = true |
| + break |
| + } |
| + if strings.Contains(string(out), "Stopped ") { |
| + break |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + // The cgroup the unit ran in, read while it ran: gone, or empty. |
| + events, err := os.ReadFile(filepath.Join("/sys/fs/cgroup", cg, "cgroup.events")) |
| + switch { |
| + case errors.Is(err, fs.ErrNotExist): |
| + case err != nil: |
| + t.Fatalf("cgroup %s after stop: %v", cg, err) |
| + case !strings.Contains(string(events), "populated 0"): |
| + t.Fatalf("cgroup %s still populated after stop: %s", cg, events) |
| + } |
| + return o |
| + } |
| + |
| + // The probe: a "+" ExecStop that reports where it runs and signals |
| + // MAINPID through a pidfd. Its report goes to the unit's stdout file. |
| + logPath := "/run/carlos/logs/" + iid + ".run.sock" |
| + dropIn("60-probe.conf", "ExecStop=\nExecStop=-+/opt/carlos/carlos "+execStopProbeArg+" $MAINPID") |
| + launch("drain") |
| + for i := 0; i < 12; i++ { |
| + _ = os.Truncate(logPath, 0) |
| + o := cycle() |
| + out, _ := os.ReadFile(logPath) |
| + t.Logf("probe cycle %d: %+v\n%s", i, o, out) |
| + } |
| + // RuntimeMaxSec: does the expiry stop run ExecStop? |
| + dropIn("61-runtime.conf", "RuntimeMaxSec=3") |
| + _ = os.Truncate(logPath, 0) |
| + for _, f := range []string{"up", "terms", "drained"} { |
| + _ = os.Remove(filepath.Join(data, f)) |
| + } |
| + _, _ = ctl("reset-failed", unit) |
| + must("start", unit) |
| + time.Sleep(6 * time.Second) |
| + out, _ := os.ReadFile(logPath) |
| + b, _ := os.ReadFile(filepath.Join(data, "terms")) |
| + t.Logf("runtime-max: state %s result %s terms %q\n%s", must("show", "-p", "ActiveState", "--value", unit), must("show", "-p", "Result", "--value", unit), b, out) |
| + jl, _ := exec.Command("journalctl", "-o", "cat", "--no-pager", "-n", "20", "-u", unit).CombinedOutput() |
| + t.Logf("journal:\n%s", jl) |
| + undrop("61-runtime.conf") |
| + // systemctl kill --kill-whom=main from root outside: reaches an alien main? |
| + launch("drain") |
| + undrop("60-probe.conf") |
| + for i := 0; i < 15; i++ { |
| + _, _ = ctl("reset-failed", unit) |
| + for _, f := range []string{"up", "terms", "drained"} { |
| + _ = os.Remove(filepath.Join(data, f)) |
| + } |
| + must("start", unit) |
| + for deadline := time.Now().Add(10 * time.Second); ; { |
| + if _, err := os.Stat(filepath.Join(data, "up")); err == nil || time.Now().After(deadline) { |
| + break |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + inv := must("show", "-p", "InvocationID", "--value", unit) |
| + _, kerr := ctl("kill", "--kill-whom=main", "--signal=SIGTERM", unit) |
| + time.Sleep(800 * time.Millisecond) |
| + jo, _ := exec.Command("journalctl", "-o", "cat", "--no-pager", "_PID=1", "INVOCATION_ID="+inv).CombinedOutput() |
| + b, _ := os.ReadFile(filepath.Join(data, "terms")) |
| + t.Logf("kill-whom=main %d: err %v alien %v state %s terms %q", i, kerr, strings.Contains(string(jo), "not our child"), must("show", "-p", "ActiveState", "--value", unit), b) |
| + _, _ = ctl("stop", unit) |
| + } |
| +} |
| + |
| +// execStopProbeArg is the probe ExecStop's argv[1]. |
| +const execStopProbeArg = "instance-stop-probe" |
| + |
| +// execStopProbe reports where a "+" ExecStop runs, then signals MAINPID |
| +// once through a pidfd and waits up to 5 s for it to exit. |
| +func execStopProbe(args []string) { |
| + fmt.Printf("probe: args %q uid %d pid %d\n", args, os.Getuid(), os.Getpid()) |
| + self, _ := os.Readlink("/proc/self/ns/pid") |
| + init, _ := os.Readlink("/proc/1/ns/pid") |
| + mnt, _ := os.Readlink("/proc/self/ns/mnt") |
| + initMnt, _ := os.Readlink("/proc/1/ns/mnt") |
| + fmt.Printf("probe: pidns self %s /proc/1 %s; mntns self %s /proc/1 %s\n", self, init, mnt, initMnt) |
| + if st, err := os.ReadFile("/proc/self/status"); err == nil { |
| + for _, l := range strings.Split(string(st), "\n") { |
| + if strings.HasPrefix(l, "Seccomp") || strings.HasPrefix(l, "NoNewPrivs") || strings.HasPrefix(l, "CapEff") { |
| + fmt.Println("probe:", l) |
| + } |
| + } |
| + } |
| + cg, _ := os.ReadFile("/proc/self/cgroup") |
| + fmt.Printf("probe: cgroup %s", cg) |
| + _, err := os.Stat("/opt/carlos/carlos") |
| + fmt.Println("probe: /opt/carlos/carlos stat:", err) |
| + if len(args) < 1 || args[0] == "" { |
| + fmt.Println("probe: no MAINPID") |
| + return |
| + } |
| + pid, err := strconv.Atoi(args[0]) |
| + if err != nil { |
| + fmt.Println("probe: MAINPID", err) |
| + return |
| + } |
| + comm, _ := os.ReadFile("/proc/" + args[0] + "/comm") |
| + tcg, _ := os.ReadFile("/proc/" + args[0] + "/cgroup") |
| + fmt.Printf("probe: /proc/MAINPID comm %q cgroup %q\n", strings.TrimSpace(string(comm)), strings.TrimSpace(string(tcg))) |
| + fd, err := unix.PidfdOpen(pid, 0) |
| + fmt.Println("probe: pidfd_open:", fd, err) |
| + if err != nil { |
| + return |
| + } |
| + err = unix.PidfdSendSignal(fd, unix.SIGTERM, nil, 0) |
| + fmt.Println("probe: pidfd_send_signal SIGTERM:", err) |
| + began := time.Now() |
| + n, perr := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, 5000) |
| + fmt.Printf("probe: poll %d %v after %s\n", n, perr, time.Since(began)) |
| +} |
| + |
| +func TestRootInstanceStopExecStop(t *testing.T) { |
| + if os.Geteuid() != 0 { |
| + t.Fatal("needs real root") |
| + } |
| + if pid1, err := os.ReadFile("/proc/1/comm"); err != nil || strings.TrimSpace(string(pid1)) != "systemd" { |
| + t.Fatalf("needs systemd as PID 1: %q %v", pid1, err) |
| + } |
| + var st unix.Statfs_t |
| + if err := unix.Statfs("/sys/fs/cgroup", &st); err != nil || st.Type != unix.CGROUP2_SUPER_MAGIC { |
| + t.Fatalf("needs cgroup v2: %#x %v", st.Type, err) |
| + } |
| + for _, p := range []string{"/opt/carlos/carlos", "/etc/carlos", "/data/instances", "/run/carlos", "/run/carlos-control"} { |
| + if _, err := os.Lstat(p); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("%s exists: this witness runs only on a fresh runner (%v)", p, err) |
| + } |
| + } |
| + uid, gid := generationRunnerRegistryUser(t) |
| + |
| + ctl := func(args ...string) (string, error) { |
| + out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + return strings.TrimSpace(string(out)), err |
| + } |
| + must := func(args ...string) string { |
| + t.Helper() |
| + out, err := ctl(args...) |
| + if err != nil { |
| + t.Fatalf("systemctl %s: %v: %s", strings.Join(args, " "), err, out) |
| + } |
| + return out |
| + } |
| + |
| + // Every path this test makes, removed in reverse on cleanup once the |
| + // unit has stopped (cleanups run last-registered first). |
| + var made []string |
| + t.Cleanup(func() { |
| + for i := len(made) - 1; i >= 0; i-- { |
| + if err := os.RemoveAll(made[i]); err != nil { |
| + t.Errorf("cleanup %s: %v", made[i], err) |
| + } |
| + } |
| + if out, err := ctl("daemon-reload"); err != nil { |
| + t.Errorf("daemon-reload: %v %s", err, out) |
| + } |
| + }) |
| + mkdirs := func(path string, owner bool) { |
| + t.Helper() |
| + var missing []string |
| + for d := path; ; d = filepath.Dir(d) { |
| + if _, err := os.Lstat(d); err == nil { |
| + break |
| + } |
| + missing = append(missing, d) |
| + } |
| + for i := len(missing) - 1; i >= 0; i-- { |
| + if err := os.Mkdir(missing[i], 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, missing[i]) |
| + } |
| + if owner { |
| + if err := os.Chown(path, uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + write := func(path string, data []byte, mode os.FileMode) { |
| + t.Helper() |
| + mkdirs(filepath.Dir(path), false) |
| + if err := os.WriteFile(path, data, mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, path) |
| + } |
| + |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bin, err := os.ReadFile(self) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + host := "stopwit.example.com" |
| + iid := provision.InstanceID(host) |
| + data, rundir := "/data/instances/"+iid, "/run/carlos/instances/"+iid |
| + carlosNew, err := os.ReadFile("/root/carlos-new") |
| + if err != nil { |
| + t.Fatalf("needs this branch's carlos at /root/carlos-new: %v", err) |
| + } |
| + carlosOld, err := os.ReadFile("/root/carlos-old") |
| + if err != nil { |
| + t.Fatalf("needs origin/main's carlos at /root/carlos-old: %v", err) |
| + } |
| + write("/opt/carlos/carlos", carlosNew, 0o755) |
| + // installBinary replaces /opt/carlos/carlos by rename, as a roll does: a |
| + // running trampoline keeps the inode it started from. |
| + installBinary := func(b []byte) { |
| + t.Helper() |
| + tmp := "/opt/carlos/.carlos.next" |
| + if err := os.WriteFile(tmp, b, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Rename(tmp, "/opt/carlos/carlos"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + mkdirs("/etc/carlos", false) |
| + mkdirs(data, true) |
| + mkdirs(rundir, true) |
| + mkdirs("/run/carlos/logs", false) |
| + exe := "/run/carlos-control/exe/" + iid |
| + // As ensureExe lays it out: app is a link PID 1 chases to the build, |
| + // which must sit on an exec mount (/run is noexec). |
| + if _, err := os.Lstat("/opt/carlos-stopwit-app"); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("/opt/carlos-stopwit-app exists (%v)", err) |
| + } |
| + write("/opt/carlos-stopwit-app", bin, 0o755) |
| + mkdirs(exe, false) |
| + if err := os.Symlink("/opt/carlos-stopwit-app", exe+"/app"); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, exe+"/app") |
| + mkdirs(exe+"/live", false) |
| + if err := os.Symlink("../app", exe+"/live/"+host); err != nil { |
| + t.Fatal(err) |
| + } |
| + made = append(made, exe+"/live/"+host) |
| + |
| + // The shipped template, couplings removed: BindsTo= the edge and |
| + // Requires= the three mounts are the box's, not the stop's. |
| + raw, err := unitsFS.ReadFile("units/carlos-instance@.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var lines []string |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + if strings.HasPrefix(line, "BindsTo=") || strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") { |
| + continue |
| + } |
| + lines = append(lines, line) |
| + } |
| + if !hasDirective(string(raw), "PrivatePIDs=yes") || !hasDirective(string(raw), execStopLine) || !hasDirective(string(raw), "TimeoutStopFailureMode=kill") { |
| + t.Fatal("embedded template is not the PrivatePIDs template with #528's ExecStop") |
| + } |
| + // The old unit: the shipped one less exactly #528's two lines. |
| + var oldLines []string |
| + for _, line := range lines { |
| + if line == execStopLine || line == "TimeoutStopFailureMode=kill" { |
| + continue |
| + } |
| + oldLines = append(oldLines, line) |
| + } |
| + if len(oldLines) != len(lines)-2 { |
| + t.Fatalf("expected to remove 2 lines for the old unit, removed %d", len(lines)-len(oldLines)) |
| + } |
| + template := "carlos-stopwit@.service" |
| + for _, dir := range []string{"/etc/systemd/system", "/run/systemd/system", "/usr/lib/systemd/system"} { |
| + if _, err := os.Lstat(filepath.Join(dir, template)); !errors.Is(err, fs.ErrNotExist) { |
| + t.Fatalf("%s already present in %s (%v)", template, dir, err) |
| + } |
| + } |
| + write("/run/systemd/system/"+template, []byte(strings.Join(lines, "\n")), 0o644) |
| + unit := strings.Replace(instancectl.UnitName(instancectl.RoleRun, host), "carlos-instance@", "carlos-stopwit@", 1) |
| + dropDir := "/run/systemd/system/" + template + ".d" |
| + // Starting a unit in a per-host slice starts its parents too; stop on |
| + // cleanup the ones this test found inactive. |
| + var stopSlices []string |
| + for _, s := range []string{instancectl.InstancesSlice, "carlos.slice"} { |
| + if out, _ := ctl("show", "-p", "ActiveState", "--value", s); out == "inactive" { |
| + stopSlices = append(stopSlices, s) |
| + } |
| + } |
| + t.Cleanup(func() { |
| + for _, s := range stopSlices { |
| + _, _ = ctl("stop", s) |
| + } |
| + }) |
| + t.Cleanup(func() { |
| + _, _ = ctl("stop", unit) |
| + _, _ = ctl("reset-failed", unit) |
| + _, _ = ctl("stop", instancectl.SliceName(host)) |
| + }) |
| + |
| + launch := func(mode string) { |
| + t.Helper() |
| + l := instancectl.Launch{Schema: instancectl.LaunchSchema, Host: host, Argv: []string{"/opt/carlos/live/" + host, instanceStopTenantArg}, Env: []string{"STOPWIT_MODE=" + mode}} |
| + b, _ := json.Marshal(l) |
| + p := filepath.Join(data, instancectl.LaunchFileName(instancectl.RoleRun)) |
| + if err := os.WriteFile(p, b, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + dropIn := func(name, body string) { |
| + t.Helper() |
| + write(filepath.Join(dropDir, name), []byte("[Service]\n"+body+"\n"), 0o644) |
| + must("daemon-reload") |
| + } |
| + undrop := func(name string) { |
| + t.Helper() |
| + if err := os.Remove(filepath.Join(dropDir, name)); err != nil { |
| + t.Fatal(err) |
| + } |
| + must("daemon-reload") |
| + } |
| + |
| + type outcome struct { |
| + result, mainCode, mainStatus string |
| + alien, drained, record bool |
| + terms int |
| + stop time.Duration |
| + } |
| + // ExecMainCode is a CLD_* number: 2 killed, 3 dumped. A clean exit |
| + // reads 1, or 0 once the unit has gone inactive on systemd 257. |
| + killedOrDumped := func(code string) bool { return code == "2" || code == "3" } |
| + // between runs once the tenant is up, before the stop (a roll's unit and |
| + // binary swap, a SIGSTOP); stopWith replaces `systemctl stop`. |
| + var between func(mainPID string) |
| + var stopWith func() |
| + cycle := func() outcome { |
| + t.Helper() |
| + for _, f := range []string{"up", "terms", "drained"} { |
| + _ = os.Remove(filepath.Join(data, f)) |
| + } |
| + _, _ = ctl("reset-failed", unit) |
| + must("start", unit) |
| + inv := must("show", "-p", "InvocationID", "--value", unit) |
| + deadline := time.Now().Add(15 * time.Second) |
| + for { |
| + if _, err := os.Stat(filepath.Join(data, "up")); err == nil { |
| + break |
| + } |
| + if s, _ := ctl("show", "-p", "ActiveState", "--value", unit); s != "active" && s != "activating" { |
| + log, _ := exec.Command("journalctl", "-o", "cat", "--no-pager", "-n", "30", "-u", unit).CombinedOutput() |
| + out, _ := os.ReadFile("/run/carlos/logs/" + iid + ".run.sock") |
| + t.Fatalf("unit %s before the tenant was up: %s\ntrampoline and tenant output: %s", s, log, out) |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("tenant never came up") |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + cg := must("show", "-p", "ControlGroup", "--value", unit) |
| + if cg == "" { |
| + t.Fatal("running unit has no ControlGroup") |
| + } |
| + if between != nil { |
| + between(must("show", "-p", "MainPID", "--value", unit)) |
| + } |
| + began := time.Now() |
| + if stopWith != nil { |
| + stopWith() |
| + } else { |
| + must("stop", unit) |
| + } |
| + o := outcome{stop: time.Since(began)} |
| + o.result = must("show", "-p", "Result", "--value", unit) |
| + o.mainCode = must("show", "-p", "ExecMainCode", "--value", unit) |
| + o.mainStatus = must("show", "-p", "ExecMainStatus", "--value", unit) |
| + if b, err := os.ReadFile(filepath.Join(data, "terms")); err == nil { |
| + o.terms = strings.Count(string(b), "term\n") |
| + } |
| + if _, err := os.Stat(filepath.Join(data, "drained")); err == nil { |
| + o.drained = true |
| + } |
| + // instance-exit's record (ExecStopPost), whichever binary ran it. |
| + if _, err := os.Stat(filepath.Join(rundir, instancectl.ExitRecordName(instancectl.RoleRun, strings.ReplaceAll(inv, "-", "")))); err == nil { |
| + o.record = true |
| + } else if _, err := os.Stat(filepath.Join(rundir, instancectl.ExitRecordName(instancectl.RoleRun, inv))); err == nil { |
| + o.record = true |
| + } |
| + // The "not our child" line is logged at start; journald may lag. |
| + for i := 0; i < 20; i++ { |
| + out, _ := exec.Command("journalctl", "-o", "cat", "--no-pager", "_PID=1", "INVOCATION_ID="+inv).CombinedOutput() |
| + if strings.Contains(string(out), "not our child") { |
| + o.alien = true |
| + break |
| + } |
| + if strings.Contains(string(out), "Stopped ") { |
| + break |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + // The cgroup the unit ran in, read while it ran: gone, or empty. |
| + events, err := os.ReadFile(filepath.Join("/sys/fs/cgroup", cg, "cgroup.events")) |
| + switch { |
| + case errors.Is(err, fs.ErrNotExist): |
| + case err != nil: |
| + t.Fatalf("cgroup %s after stop: %v", cg, err) |
| + case !strings.Contains(string(events), "populated 0"): |
| + t.Fatalf("cgroup %s still populated after stop: %s", cg, events) |
| + } |
| + return o |
| + } |
| + |
| + installUnit := func(ls []string) { |
| + t.Helper() |
| + if err := os.WriteFile("/run/systemd/system/"+template, []byte(strings.Join(ls, "\n")), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + use := func(unitLines []string, bin []byte) { |
| + t.Helper() |
| + installUnit(unitLines) |
| + installBinary(bin) |
| + must("daemon-reload") |
| + } |
| + const n = 40 |
| + clean := func(o outcome) bool { |
| + return o.result == "success" && !killedOrDumped(o.mainCode) && o.mainStatus == "0" && o.terms == 1 && o.record |
| + } |
| + |
| + // A. Old unit, new binary: today's behaviour, and the race reproduces. |
| + use(oldLines, carlosNew) |
| + launch("drain") |
| + var aAlien, aSignal int |
| + for i := 0; i < n; i++ { |
| + o := cycle() |
| + if o.alien { |
| + aAlien++ |
| + } |
| + if o.result == "signal" { |
| + aSignal++ |
| + } |
| + if o.terms > 1 { |
| + t.Errorf("old unit cycle %d: %d SIGTERMs", i, o.terms) |
| + } |
| + } |
| + t.Logf("verdict: A old unit, new binary: %d/%d alien, %d/%d Result=signal", aAlien, n, aSignal, n) |
| + if aSignal == 0 { |
| + t.Fatalf("the race did not reproduce under the old unit in %d cycles (%d alien)", n, aAlien) |
| + } |
| + |
| + // B. New unit, new binary: draining and fast-exit apps, one SIGTERM each. |
| + use(lines, carlosNew) |
| + for _, mode := range []string{"drain", "fast"} { |
| + launch(mode) |
| + alien := 0 |
| + for i := 0; i < n; i++ { |
| + o := cycle() |
| + if o.alien { |
| + alien++ |
| + } |
| + if !clean(o) || (mode == "drain" && !o.drained) { |
| + t.Errorf("B %s cycle %d: %+v", mode, i, o) |
| + } |
| + } |
| + t.Logf("verdict: B new/new %s: %d/%d alien, all clean unless an error above", mode, alien, n) |
| + if alien == 0 { |
| + t.Fatalf("no alien start in %d %s cycles: the helper was not exercised against the race", n, mode) |
| + } |
| + } |
| + |
| + // C. An app that ignores SIGTERM: one SIGTERM, SIGKILL from the helper |
| + // at its budget, inside TimeoutStopSec. |
| + launch("ignore") |
| + o := cycle() |
| + t.Logf("verdict: C ignores SIGTERM: %+v", o) |
| + if o.terms != 1 || o.stop < instanceexec.StopBudget-time.Second || o.stop > 20*time.Second+500*time.Millisecond || o.result != "signal" || o.mainCode != "2" || o.mainStatus != "9" || !o.record { |
| + t.Errorf("ignore-SIGTERM stop not bounded as designed: %+v", o) |
| + } |
| + |
| + // D. New unit, old binary (a rollback window): the unknown verb exits 2, |
| + // "-" ignores it, and the stop is today's; never a second SIGTERM. |
| + use(lines, carlosOld) |
| + launch("drain") |
| + var dAlien int |
| + for i := 0; i < 20; i++ { |
| + o := cycle() |
| + if o.alien { |
| + dAlien++ |
| + } |
| + if o.terms > 1 || (!o.alien && !clean(o)) { |
| + t.Errorf("D new unit, old binary, cycle %d: %+v", i, o) |
| + } |
| + } |
| + t.Logf("verdict: D new unit, old binary: %d/20 alien, today's behaviour", dAlien) |
| + |
| + // E. A roll under a running instance: started by the old unit and the old |
| + // binary's trampoline, stopped after the new unit and binary are in and |
| + // reloaded: one SIGTERM through the helper. |
| + launch("drain") |
| + var eAlien int |
| + for i := 0; i < 20; i++ { |
| + use(oldLines, carlosOld) |
| + between = func(string) { use(lines, carlosNew) } |
| + o := cycle() |
| + between = nil |
| + if o.alien { |
| + eAlien++ |
| + } |
| + if !clean(o) || !o.drained { |
| + t.Errorf("E roll under a running instance, cycle %d: %+v", i, o) |
| + } |
| + } |
| + t.Logf("verdict: E roll under running instances: %d/20 alien, all clean unless an error above", eAlien) |
| + |
| + // F. Rollback under a running instance: started new/new, stopped after |
| + // the old unit and binary are back: today's behaviour. |
| + for i := 0; i < 10; i++ { |
| + use(lines, carlosNew) |
| + between = func(string) { use(oldLines, carlosOld) } |
| + o := cycle() |
| + between = nil |
| + if o.terms > 1 || (!o.alien && !clean(o)) { |
| + t.Errorf("F rollback under a running instance, cycle %d: %+v", i, o) |
| + } |
| + } |
| + t.Logf("verdict: F rollback under running instances: today's behaviour unless an error above") |
| + |
| + // G-I on the new unit and binary. |
| + use(lines, carlosNew) |
| + |
| + // G. RuntimeMaxSec= expiry goes through the helper. |
| + dropIn("61-runtime.conf", "RuntimeMaxSec=3") |
| + launch("drain") |
| + stopWith = func() { |
| + deadline := time.Now().Add(30 * time.Second) |
| + for { |
| + if s, _ := ctl("show", "-p", "ActiveState", "--value", unit); s == "inactive" || s == "failed" { |
| + return |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("unit outlived its RuntimeMaxSec") |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + } |
| + o = cycle() |
| + stopWith = nil |
| + undrop("61-runtime.conf") |
| + t.Logf("verdict: G RuntimeMaxSec: %+v", o) |
| + if o.terms != 1 || !o.drained || o.result != "timeout" || killedOrDumped(o.mainCode) || o.mainStatus != "0" || !o.record { |
| + t.Errorf("RuntimeMaxSec expiry: %+v", o) |
| + } |
| + |
| + // H. A stopped (SIGSTOP) trampoline still drains on one SIGTERM. |
| + launch("drain") |
| + between = func(pid string) { |
| + p, err := strconv.Atoi(pid) |
| + if err != nil || p <= 1 { |
| + t.Fatalf("MainPID %q", pid) |
| + } |
| + if err := syscall.Kill(p, syscall.SIGSTOP); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + o = cycle() |
| + between = nil |
| + t.Logf("verdict: H stopped main: %+v", o) |
| + if !clean(o) || !o.drained { |
| + t.Errorf("stopped main: %+v", o) |
| + } |
| + |
| + // J. systemd's stop timer fires before the helper has signalled (a |
| + // helper stalled at start): TimeoutStopFailureMode=kill makes it a |
| + // SIGKILL, so the app gets no SIGTERM, never a second one. |
| + dropIn("62-stall.conf", "ExecStop=\nExecStop=-+/bin/sleep 30\nTimeoutStopSec=3") |
| + launch("drain") |
| + o = cycle() |
| + undrop("62-stall.conf") |
| + t.Logf("verdict: J manager timeout before the helper signals: %+v", o) |
| + if o.terms != 0 || o.stop < 2500*time.Millisecond || o.stop > 8*time.Second || o.result != "timeout" || o.mainCode != "2" || o.mainStatus != "9" || !o.record { |
| + t.Errorf("timeout before signalling: %+v", o) |
| + } |
| + |
| + // K. The timer fires after the helper's one SIGTERM (an app that ignores |
| + // it, a stop budget shorter than the helper's): SIGKILL, no second |
| + // SIGTERM. |
| + dropIn("63-short.conf", "TimeoutStopSec=3") |
| + launch("ignore") |
| + o = cycle() |
| + undrop("63-short.conf") |
| + t.Logf("verdict: K manager timeout after the helper's SIGTERM: %+v", o) |
| + if o.terms != 1 || o.stop < 2500*time.Millisecond || o.stop > 8*time.Second || o.result != "timeout" || o.mainCode != "2" || o.mainStatus != "9" || !o.record { |
| + t.Errorf("timeout after signalling: %+v", o) |
| + } |
| + |
| + // I. A main process that exits by itself: ExecStop runs with no |
| + // $MAINPID and the unit ends clean. |
| + launch("exit") |
| + stopWith = func() { |
| + deadline := time.Now().Add(10 * time.Second) |
| + for { |
| + if s, _ := ctl("show", "-p", "ActiveState", "--value", unit); s == "inactive" || s == "failed" { |
| + return |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("self-exiting tenant never ended") |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + } |
| + o = cycle() |
| + stopWith = nil |
| + t.Logf("verdict: I main exits by itself: %+v", o) |
| + if o.result != "success" || o.mainStatus != "0" || o.terms != 0 || !o.record { |
| + t.Errorf("self exit: %+v", o) |
| + } |
| +} |
diff --git a/internal/host/plan14_generation_registry_root_linux_test.go b/internal/host/plan14_generation_registry_root_linux_test.go| index 20de50ce6..b75fc274b 100644 |
| --- a/internal/host/plan14_generation_registry_root_linux_test.go |
| +++ b/internal/host/plan14_generation_registry_root_linux_test.go |
| @@ -76,9 +76,18 @@ func TestMain(m *testing.M) { |
| case "instance-exit": |
| instanceexec.RunExit(os.Args[2:]) |
| return |
| + case "instance-stop": |
| + instanceexec.RunStop(os.Args[2:]) |
| + return |
| case "plan14-tenant": |
| plan14InstalledTenant() |
| return |
| + case instanceStopTenantArg: |
| + instanceStopTenant() |
| + return |
| + case execStopProbeArg: |
| + execStopProbe(os.Args[2:]) |
| + return |
| } |
| } |
| if len(os.Args) > 1 && os.Args[1] == registryChildCommand { |
diff --git a/internal/host/units/carlos-instance-gen@.service b/internal/host/units/carlos-instance-gen@.service| index cb8707654..e73106010 100644 |
| --- a/internal/host/units/carlos-instance-gen@.service |
| +++ b/internal/host/units/carlos-instance-gen@.service |
| @@ -19,6 +19,13 @@ After=carlos-edge.service data-instances.mount run-carlos-instances.mount run-ca |
| [Service] |
| Type=simple |
| ExecStart=/opt/carlos/carlos instance-exec run %I |
| +# #528 (Paul's option 2): under PrivatePIDs= systemd sometimes takes the |
| +# main process for "not our child", and a mixed stop then SIGKILLs it right |
| +# after its SIGTERM. This runs first, as root ("+": host PID namespace, so |
| +# $MAINPID is right): one SIGTERM to the main process through a pidfd, a |
| +# wait, SIGKILL at its 18 s budget. The "-" makes a binary without the verb |
| +# (a rollback window) fall back to the stop below, as before. |
| +ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID |
| # The tenant runs in its own data directory (#256 D). %I here is |
| # <id>:<n>, not the host's id, so the real directory comes from the |
| # generation's runtime drop-in, which overrides this line. This one only |
| @@ -33,6 +40,9 @@ Group=carlos |
| Restart=no |
| KillMode=mixed |
| TimeoutStopSec=20 |
| +# A stop that outlives TimeoutStopSec while the helper runs goes straight |
| +# to SIGKILL, never to a second SIGTERM. |
| +TimeoutStopFailureMode=kill |
| # The main process is the trampoline, which stays as the namespace's init |
| # and runs the app as its child (#126): it forwards the SIGTERM and exits |
| # 128+n when the app dies by signal n. These are SIGHUP, SIGINT, SIGPIPE |
diff --git a/internal/host/units/carlos-instance-sidecar@.service b/internal/host/units/carlos-instance-sidecar@.service| index 24046330a..e82694a2f 100644 |
| --- a/internal/host/units/carlos-instance-sidecar@.service |
| +++ b/internal/host/units/carlos-instance-sidecar@.service |
| @@ -18,6 +18,13 @@ After=carlos-edge.service data-instances.mount run-carlos-instances.mount run-ca |
| [Service] |
| Type=simple |
| ExecStart=/opt/carlos/carlos instance-exec sidecar %I |
| +# #528 (Paul's option 2): under PrivatePIDs= systemd sometimes takes the |
| +# main process for "not our child", and a mixed stop then SIGKILLs it right |
| +# after its SIGTERM. This runs first, as root ("+": host PID namespace, so |
| +# $MAINPID is right): one SIGTERM to the main process through a pidfd, a |
| +# wait, SIGKILL at its 18 s budget. The "-" makes a binary without the verb |
| +# (a rollback window) fall back to the stop below, as before. |
| +ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID |
| # Runs inside the same namespace, as carlos, after this invocation's |
| # processes have been signalled: leaves an ADVISORY exit record in the |
| # instance's own run directory (§6.5). Not "+": the "+" prefix drops User= |
| @@ -38,6 +45,9 @@ Restart=no |
| # TimeoutStopSec; the activator's stop budget is 20s. |
| KillMode=mixed |
| TimeoutStopSec=20 |
| +# A stop that outlives TimeoutStopSec while the helper runs goes straight |
| +# to SIGKILL, never to a second SIGTERM. |
| +TimeoutStopFailureMode=kill |
| # The main process is the trampoline, which stays as the namespace's init |
| # and runs the app as its child (#126): it forwards the SIGTERM and exits |
| # 128+n when the app dies by signal n. These are SIGHUP, SIGINT, SIGPIPE |
diff --git a/internal/host/units/carlos-instance@.service b/internal/host/units/carlos-instance@.service| index 1e093f647..db2369f0f 100644 |
| --- a/internal/host/units/carlos-instance@.service |
| +++ b/internal/host/units/carlos-instance@.service |
| @@ -18,6 +18,13 @@ After=carlos-edge.service data-instances.mount run-carlos-instances.mount run-ca |
| [Service] |
| Type=simple |
| ExecStart=/opt/carlos/carlos instance-exec run %I |
| +# #528 (Paul's option 2): under PrivatePIDs= systemd sometimes takes the |
| +# main process for "not our child", and a mixed stop then SIGKILLs it right |
| +# after its SIGTERM. This runs first, as root ("+": host PID namespace, so |
| +# $MAINPID is right): one SIGTERM to the main process through a pidfd, a |
| +# wait, SIGKILL at its 18 s budget. The "-" makes a binary without the verb |
| +# (a rollback window) fall back to the stop below, as before. |
| +ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID |
| # Runs inside the same namespace, as carlos, after this invocation's |
| # processes have been signalled: leaves an ADVISORY exit record in the |
| # instance's own run directory (§6.5). Not "+": the "+" prefix drops User= |
| @@ -38,6 +45,9 @@ Restart=no |
| # TimeoutStopSec; the activator's stop budget is 20s. |
| KillMode=mixed |
| TimeoutStopSec=20 |
| +# A stop that outlives TimeoutStopSec while the helper runs goes straight |
| +# to SIGKILL, never to a second SIGTERM. |
| +TimeoutStopFailureMode=kill |
| # The main process is the trampoline, which stays as the namespace's init |
| # and runs the app as its child (#126): it forwards the SIGTERM and exits |
| # 128+n when the app dies by signal n. These are SIGHUP, SIGINT, SIGPIPE |
diff --git a/internal/host/units_execstop_test.go b/internal/host/units_execstop_test.go| new file mode 100644 |
| index 000000000..213e72811 |
| --- /dev/null |
| +++ b/internal/host/units_execstop_test.go |
| @@ -0,0 +1,65 @@ |
| +package host |
| + |
| +import ( |
| + "strconv" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/instanceexec" |
| +) |
| + |
| +// execStopLine is #528's root ExecStop (Paul's option 2): one SIGTERM to |
| +// the main process through a pidfd, a wait, SIGKILL at the helper's budget. |
| +const execStopLine = "ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID" |
| + |
| +// The long-running binary templates and the claim-bound template carry the |
| +// helper exactly once, keep KillMode=mixed, and give it a stop budget it |
| +// fits inside; no other template carries it. |
| +func TestInstanceStopExecStopTemplates(t *testing.T) { |
| + t.Parallel() |
| + in := map[string]string{ |
| + "carlos-instance@.service": readUnit(t, "carlos-instance@.service"), |
| + "carlos-instance-gen@.service": readUnit(t, "carlos-instance-gen@.service"), |
| + "carlos-instance-sidecar@.service": readUnit(t, "carlos-instance-sidecar@.service"), |
| + "claimBoundTemplate": claimBoundTemplate, |
| + } |
| + for name, u := range in { |
| + ds := directives(u) |
| + n, stop := 0, time.Duration(0) |
| + for _, d := range ds { |
| + if strings.HasPrefix(d, "ExecStop=") { |
| + n++ |
| + if d != execStopLine { |
| + t.Errorf("%s: %q, want %q", name, d, execStopLine) |
| + } |
| + } |
| + if v, ok := strings.CutPrefix(d, "TimeoutStopSec="); ok { |
| + s, err := strconv.Atoi(v) |
| + if err != nil { |
| + t.Fatalf("%s: TimeoutStopSec=%s", name, v) |
| + } |
| + stop = time.Duration(s) * time.Second |
| + } |
| + } |
| + if n != 1 { |
| + t.Errorf("%s: %d ExecStop= lines, want 1", name, n) |
| + } |
| + // A stop that outlives TimeoutStopSec while the helper runs goes to |
| + // SIGKILL, never to a second SIGTERM (Astra spec R1 P1). |
| + if !hasDirective(u, "TimeoutStopFailureMode=kill") { |
| + t.Errorf("%s lacks TimeoutStopFailureMode=kill", name) |
| + } |
| + if !hasDirective(u, "KillMode=mixed") { |
| + t.Errorf("%s lost KillMode=mixed", name) |
| + } |
| + if stop <= instanceexec.StopBudget+instanceexec.KillWait { |
| + t.Errorf("%s: TimeoutStopSec %s does not exceed the helper's %s budget plus its %s kill wait", name, stop, instanceexec.StopBudget, instanceexec.KillWait) |
| + } |
| + } |
| + for _, name := range []string{"carlos-instance-seed@.service", "carlos-instance-cmd@.service", "carlos-instance-tty@.service", "carlos-instance-probe.service"} { |
| + if strings.Contains(readUnit(t, name), "instance-stop") { |
| + t.Errorf("%s carries the stop helper; it is out of scope (spec)", name) |
| + } |
| + } |
| +} |
diff --git a/internal/instanceexec/stop.go b/internal/instanceexec/stop.go| new file mode 100644 |
| index 000000000..68d599d5f |
| --- /dev/null |
| +++ b/internal/instanceexec/stop.go |
| @@ -0,0 +1,14 @@ |
| +package instanceexec |
| + |
| +import "time" |
| + |
| +// StopBudget is how long instance-stop waits for the main process after |
| +// its SIGTERM before it SIGKILLs it, and killWait how long it then waits |
| +// to see the exit. Together they end inside the templates' |
| +// TimeoutStopSec=20; should systemd's timer still fire first, the |
| +// templates' TimeoutStopFailureMode=kill makes that a SIGKILL, never a |
| +// second SIGTERM (#528). |
| +const ( |
| + StopBudget = 18 * time.Second |
| + KillWait = time.Second |
| +) |
diff --git a/internal/instanceexec/stop_linux.go b/internal/instanceexec/stop_linux.go| new file mode 100644 |
| index 000000000..fb9e0412a |
| --- /dev/null |
| +++ b/internal/instanceexec/stop_linux.go |
| @@ -0,0 +1,124 @@ |
| +//go:build linux |
| + |
| +package instanceexec |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "os" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// RunStop is `carlos instance-stop $MAINPID`, the root ExecStop (the "+" |
| +// prefix) of the binary run, generation and sidecar templates and the |
| +// claim-bound template (#528, Paul's option 2). Under PrivatePIDs= systemd |
| +// sometimes takes the unit's main process for "not our child", and then a |
| +// KillMode=mixed stop SIGKILLs it straight after its SIGTERM. This runs |
| +// first: one SIGTERM to the main process (the trampoline, which forwards |
| +// it to the app), a wait for its exit, and SIGKILL at StopBudget. When it |
| +// has seen the exit, systemd's own SIGTERM phase finds no main process to |
| +// signal, so the app gets exactly one SIGTERM whatever systemd thinks of |
| +// its parent. When it has not (a process stuck in the kernel with its |
| +// SIGKILL pending), systemd's phases run on as before and the activator's |
| +// populated-cgroup check decides when the stop is complete. |
| +// |
| +// It runs as root in the host PID namespace (a "+" command gets no |
| +// PrivatePIDs= of its own), so $MAINPID names the right process. It reads |
| +// only that argument and two kernel-written cgroup files, and acts only |
| +// through a pidfd. Its exit is 0 whenever its argument parses, and the |
| +// template's "-" ignores any other. |
| +func RunStop(args []string) { os.Exit(stopMain(args, StopBudget, procCgroup)) } |
| + |
| +// procCgroup is /proc/<pid>/cgroup, or /proc/self/cgroup for pid 0. |
| +func procCgroup(pid int) (string, error) { |
| + p := "/proc/self/cgroup" |
| + if pid != 0 { |
| + p = "/proc/" + strconv.Itoa(pid) + "/cgroup" |
| + } |
| + b, err := os.ReadFile(p) |
| + return strings.TrimSpace(string(b)), err |
| +} |
| + |
| +// stopMain is RunStop with its budget and cgroup reader as seams. |
| +func stopMain(args []string, budget time.Duration, cgroupOf func(pid int) (string, error)) int { |
| + if len(args) > 1 { |
| + fmt.Fprintln(os.Stderr, "usage: carlos instance-stop <main-pid>") |
| + return 2 |
| + } |
| + if len(args) == 0 || args[0] == "" { |
| + return 0 // no main process: nothing to stop |
| + } |
| + pid, err := strconv.Atoi(args[0]) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "usage: carlos instance-stop <main-pid>") |
| + return 2 |
| + } |
| + if pid <= 1 || pid == os.Getpid() { |
| + return 0 |
| + } |
| + fd, err := unix.PidfdOpen(pid, 0) |
| + if err != nil { |
| + if !errors.Is(err, unix.ESRCH) { |
| + fmt.Fprintln(os.Stderr, "instance-stop: pidfd:", err) |
| + } |
| + return 0 |
| + } |
| + defer unix.Close(fd) |
| + // The PID must be a process of this unit: the helper is the unit's |
| + // control process, so both sit in its cgroup. Read the cgroup, then |
| + // prove the pidfd's process is still alive: a pidfd holds its PID until |
| + // that process is reaped, so the read was of the same process and a PID |
| + // reused by a stranger is never signalled. |
| + own, err := cgroupOf(0) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "instance-stop: own cgroup:", err) |
| + return 0 |
| + } |
| + theirs, err := cgroupOf(pid) |
| + if err != nil || theirs != own { |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + fmt.Fprintln(os.Stderr, "instance-stop: main cgroup:", err) |
| + } |
| + return 0 |
| + } |
| + if err := unix.PidfdSendSignal(fd, 0, nil, 0); err != nil { |
| + return 0 |
| + } |
| + if err := unix.PidfdSendSignal(fd, unix.SIGTERM, nil, 0); err != nil { |
| + return 0 |
| + } |
| + // As systemd's own stop does: a main process someone stopped must run |
| + // to forward the SIGTERM and let the app drain. |
| + _ = unix.PidfdSendSignal(fd, unix.SIGCONT, nil, 0) |
| + if waitPidfd(fd, budget) { |
| + return 0 |
| + } |
| + _ = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) |
| + waitPidfd(fd, KillWait) |
| + return 0 |
| +} |
| + |
| +// waitPidfd reports whether fd's process exited within d. |
| +func waitPidfd(fd int, d time.Duration) bool { |
| + deadline := time.Now().Add(d) |
| + for { |
| + left := time.Until(deadline) |
| + if left <= 0 { |
| + return false |
| + } |
| + n, err := unix.Poll([]unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}, int(left.Milliseconds())+1) |
| + if err == unix.EINTR { |
| + continue |
| + } |
| + if err != nil { |
| + return false |
| + } |
| + if n > 0 { |
| + return true |
| + } |
| + } |
| +} |
diff --git a/internal/instanceexec/stop_linux_test.go b/internal/instanceexec/stop_linux_test.go| new file mode 100644 |
| index 000000000..5852cb2c3 |
| --- /dev/null |
| +++ b/internal/instanceexec/stop_linux_test.go |
| @@ -0,0 +1,141 @@ |
| +//go:build linux |
| + |
| +package instanceexec |
| + |
| +import ( |
| + "os" |
| + "os/exec" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// stopChild starts a shell that records each SIGTERM in its own file and, |
| +// unless ignore, exits 0 on the first one. |
| +func stopChild(t *testing.T, ignore bool) (*exec.Cmd, string, chan struct{}) { |
| + t.Helper() |
| + got := t.TempDir() + "/terms" |
| + on := `echo term >>"$0"; exit 0` |
| + if ignore { |
| + on = `echo term >>"$0"` |
| + } |
| + child := exec.Command("sh", "-c", "trap '"+on+"' TERM; : >\"$0.up\"; while :; do sleep 0.02; done", got) |
| + if err := child.Start(); err != nil { |
| + t.Skip("no sh:", err) |
| + } |
| + reaped := make(chan struct{}) |
| + go func() { _ = child.Wait(); close(reaped) }() |
| + t.Cleanup(func() { _ = child.Process.Kill(); <-reaped }) |
| + for deadline := time.Now().Add(5 * time.Second); ; { |
| + if _, err := os.Stat(got + ".up"); err == nil { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("child never set its trap") |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + return child, got, reaped |
| +} |
| + |
| +func terms(t *testing.T, path string) int { |
| + b, _ := os.ReadFile(path) |
| + return strings.Count(string(b), "term\n") |
| +} |
| + |
| +func sameCgroup(int) (string, error) { return "0::/unit", nil } |
| + |
| +// One SIGTERM, then the helper waits for the exit and returns. |
| +func TestStopMainSignalsOnceAndWaits(t *testing.T) { |
| + child, got, reaped := stopChild(t, false) |
| + began := time.Now() |
| + if code := stopMain([]string{strconv.Itoa(child.Process.Pid)}, 5*time.Second, sameCgroup); code != 0 { |
| + t.Fatalf("exit %d", code) |
| + } |
| + <-reaped |
| + if n := terms(t, got); n != 1 { |
| + t.Errorf("child got %d SIGTERMs, want 1", n) |
| + } |
| + if time.Since(began) > 3*time.Second { |
| + t.Errorf("the helper did not return when the main process exited: %s", time.Since(began)) |
| + } |
| +} |
| + |
| +// A main process that ignores SIGTERM gets one, then SIGKILL at the |
| +// deadline (#528: never a second SIGTERM from systemd's own phase). |
| +func TestStopMainKillsAtTheDeadline(t *testing.T) { |
| + child, got, reaped := stopChild(t, true) |
| + began := time.Now() |
| + if code := stopMain([]string{strconv.Itoa(child.Process.Pid)}, 700*time.Millisecond, sameCgroup); code != 0 { |
| + t.Fatalf("exit %d", code) |
| + } |
| + <-reaped |
| + if el := time.Since(began); el < 600*time.Millisecond || el > 4*time.Second { |
| + t.Errorf("killed after %s, want about the 700ms budget", el) |
| + } |
| + if n := terms(t, got); n != 1 { |
| + t.Errorf("child got %d SIGTERMs, want 1", n) |
| + } |
| + if ws := child.ProcessState.Sys().(syscall.WaitStatus); !ws.Signaled() || ws.Signal() != syscall.SIGKILL { |
| + t.Errorf("child ended %v, want SIGKILL", child.ProcessState) |
| + } |
| +} |
| + |
| +// A process in another cgroup is never signalled: the PID is not this |
| +// unit's main process (reused, or a wrong argument). |
| +func TestStopMainRefusesAnotherCgroup(t *testing.T) { |
| + child, got, _ := stopChild(t, false) |
| + other := func(pid int) (string, error) { |
| + if pid == child.Process.Pid { |
| + return "0::/elsewhere", nil |
| + } |
| + return "0::/unit", nil |
| + } |
| + if code := stopMain([]string{strconv.Itoa(child.Process.Pid)}, time.Second, other); code != 0 { |
| + t.Fatalf("exit %d", code) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + if n := terms(t, got); n != 0 { |
| + t.Errorf("a process in another cgroup got %d SIGTERMs", n) |
| + } |
| + if child.ProcessState != nil { |
| + t.Error("a process in another cgroup was stopped") |
| + } |
| +} |
| + |
| +// No main process (systemd expands an empty $MAINPID), a gone one, the |
| +// helper's own PID, PID 1 and junk: nothing is signalled and the stop |
| +// carries on as today. |
| +func TestStopMainArguments(t *testing.T) { |
| + gone := exec.Command("true") |
| + _ = gone.Run() |
| + for _, args := range [][]string{nil, {""}, {strconv.Itoa(gone.Process.Pid)}, {strconv.Itoa(os.Getpid())}, {"1"}, {"0"}, {"-5"}} { |
| + if code := stopMain(args, time.Second, sameCgroup); code != 0 { |
| + t.Errorf("%q: exit %d, want 0 (nothing to stop)", args, code) |
| + } |
| + } |
| + for _, args := range [][]string{{"x"}, {"1", "2"}} { |
| + if code := stopMain(args, time.Second, sameCgroup); code != 2 { |
| + t.Errorf("%q: exit %d, want the usage code 2", args, code) |
| + } |
| + } |
| +} |
| + |
| +// A main process someone has stopped (SIGSTOP) is continued after its |
| +// SIGTERM, as systemd's own stop does, so it can still forward and drain. |
| +func TestStopMainContinuesAStoppedMain(t *testing.T) { |
| + child, got, reaped := stopChild(t, false) |
| + if err := child.Process.Signal(syscall.SIGSTOP); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + if code := stopMain([]string{strconv.Itoa(child.Process.Pid)}, 3*time.Second, sameCgroup); code != 0 { |
| + t.Fatalf("exit %d", code) |
| + } |
| + <-reaped |
| + if n := terms(t, got); n != 1 { |
| + t.Errorf("stopped child handled %d SIGTERMs, want 1 (it was never continued)", n) |
| + } |
| +} |
diff --git a/internal/instanceexec/stop_other.go b/internal/instanceexec/stop_other.go| new file mode 100644 |
| index 000000000..a8d86588a |
| --- /dev/null |
| +++ b/internal/instanceexec/stop_other.go |
| @@ -0,0 +1,14 @@ |
| +//go:build !linux |
| + |
| +package instanceexec |
| + |
| +import ( |
| + "fmt" |
| + "os" |
| +) |
| + |
| +// RunStop is Linux only: no instance unit runs elsewhere. |
| +func RunStop([]string) { |
| + fmt.Fprintln(os.Stderr, "instance-stop: linux only") |
| + os.Exit(2) |
| +} |
diff --git a/internal/provision/agent_start_demo_3_census_test.go b/internal/provision/agent_start_demo_3_census_test.go| index 6ec2a9a8a..5d74dbe96 100644 |
| --- a/internal/provision/agent_start_demo_3_census_test.go |
| +++ b/internal/provision/agent_start_demo_3_census_test.go |
| @@ -27,7 +27,7 @@ func agentStartDemo3WriteCensusInventory() []censusEntry { |
| for _, next := range []censusEntry{ |
| {"internal/release/changeindex.go", "BumpChangeIndex", "nonrecord", "sel:Put", "857da9ea14d535d0362ab1b5878efc577e45f4bbf655a33e59baa1a40b8ff132"}, |
| {"internal/console/demo_claim_moved.go", "Server.publishDemoMoved", "nonrecord", "sel:Put", "f229655ba4a335ab5c48bea6132270f1c3ab1fc1cbe1fa8c220894b860e02c74"}, |
| - {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "10fd9b177a6bfbf46dac51134a3b1db2212c234ff9e35035c08de329bf505545"}, |
| + {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "e55ddb4789e94b01b2d2cf001d2904cbacdfdf6cd4e5bb560ed849033db4c4cf"}, |
| {"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "e31dcb19a6022bbaf69e69736666a2f48991db5d5bfd1c8ed5b4680f0c738ed1"}, |
| {"internal/console/plancaps.go", "Server.runningThings", "key-site", "key:ParseRecordKey,key:RecordsPrefix", "5079fd758e620905ab39fdfe6b44ac1214ab155abb988b0edfa395a2a6d83aab"}, |
| {"internal/console/seedfinish.go", "Server.finishSeedOnce", "key-site", "key:RecordKey", "a6b0b3fa6002e4266dda8d97338fd087b48bb405a437ce0b43f8f72a5b580772"}, |
diff --git a/internal/provision/plan14_e_write_census_test.go b/internal/provision/plan14_e_write_census_test.go| index 6ba6fe579..ff99fa9f3 100644 |
| --- a/internal/provision/plan14_e_write_census_test.go |
| +++ b/internal/provision/plan14_e_write_census_test.go |
| @@ -3,7 +3,7 @@ package provision |
| // Track E overlays the reviewed Part 1 write census without changing its baseline. |
| var plan14EWriteCensusOverlay = []censusEntry{ |
| {"internal/hostbox/journalservice.go", "journalRequestHash", "key-site", "key:RecordKey", "b6248a416cb57046d014a95b22f3798f156e0cde5aba189f5f82c36d4c7a5e78"}, |
| - {"internal/host/claimunit_template.go", "const claimBoundTemplate", "key-site", "lit:instances", "9ff0f84071165eb2d642596f1c4b28241f872fea99f7bf8e3d77f51785ad270a"}, |
| + {"internal/host/claimunit_template.go", "const claimBoundTemplate", "key-site", "lit:instances", "c0095f6293bba755efb9e85a6585babd96a0a4f100a260c80a0a6120db2a9031"}, |
| {"internal/hostbox/inventory_expected.go", "StopInventoryDB.writeExpected", "key-site", "key:RecordKey", "6bd77e75ff73ac8e461bb0687b183e031e2864d8455f58513b71aade995cb2b1"}, |
| {"internal/hostbox/journalservice.go", "type JournalRequest", "key-site", "key:RecordKey", "be65901745c9d840a1f6cbb7c82f2443482f85b652b7b1635f38fc0524aec38c"}, |
| {"internal/host/rootgeneration_requirements.go", "generationLocalObligations", "key-site", "key:RecordKey", "7bf08b3afdf12e81188123e0257ef90cea91091a8ab3bfb975e9a0200619dd1b"}, |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 78806e37c..5217f22f9 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -128,3 +128,4 @@ plan14-root-reads-fix-activator-backoff-flake.tsv feba66806ddfcbdfaf369d72413bb1 |
| plan14-root-reads-region-ha-dr5.tsv f19eb78c1da1475cbf8e11a3d6c394d828aa1c8f88ae24469fe8d473581b934b |
| plan14-root-reads-instance-syscall-filter.tsv b970bb28c5a633d2572a1da549030e9258cfdabb6322ddffdd0ebf41b56c464c |
| plan14-root-reads-instance-restore-658-cli.tsv b970bb28c5a633d2572a1da549030e9258cfdabb6322ddffdd0ebf41b56c464c |
| +plan14-root-reads-instance-stop-execstop-528.tsv 75fb3eb24d0bf3a8405b929675d919ec88f15386d43e9ff687ce138a7ed968a4 |
diff --git a/internal/provision/testdata/plan14-root-reads-instance-stop-execstop-528.tsv b/internal/provision/testdata/plan14-root-reads-instance-stop-execstop-528.tsv| new file mode 100644 |
| index 000000000..f44c7313c |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-instance-stop-execstop-528.tsv |
| @@ -0,0 +1,16 @@ |
| +# Census overlay instance-stop-execstop-528, written by census-propose (#369). census-ruling-instance-stop-execstop-528, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-instance-stop-execstop-528.md. |
| +# 4 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 747f3acb9f0af10ee2e7b9d1fec899f05bd4e6e234bb6f17d46dc6bf0ba8716c internal/host/units/carlos-instance-gen@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else;rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates);rev3=census-ruling-instance-stop-execstop-528;basis=one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added file:external@0 adcdd2d7607773ae7260dd956dba4ee225f2a499c60615de3b7ab3fa2b797368 |
| +@legacy 97f6024558f9a59aac8bd8e2d44606ea76199933f39e9ccbbe571629d972ee98 internal/host/units/carlos-instance-sidecar@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else;rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates);rev3=census-ruling-instance-stop-execstop-528;basis=one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added file:external@0 8f62d8d6510292bbc1cb6b013082d50bc538a51d1703b290f91ffc2a8dbcde17 |
| +@legacy a19f6cda46e904c9fccab3d1ba83f294dba3302e70e23582c4023f4518f0d6c9 internal/host/units/carlos-instance@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: one namespace-block line added after TemporaryFileSystem=/dev/mqueue:ro, TemporaryFileSystem=/dev/pts:ro (with its comment): PID 1 mounts an empty read-only tmpfs over the private /dev/pts, hiding the host devpts PrivateDevices= binds in; no bind source, Exec line, user or path read by root added; the block stays byte-identical across the binary templates (TestInstanceTemplatesShareOneNamespace);rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates);rev3=census-ruling-instance-stop-execstop-528;basis=one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added file:external@0 ee4538e3c0361b569aaa8abab24ebae79d3144fc7859e518270ea2aa2f143574 |
| +@legacy 6690649e0b537a7ba242100eb2c6cded1ac473e3dd5144d83256e80a41c57990 internal/instanceexec/stop_linux.go procCgroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-instance-stop-execstop-528;basis=new (#528, Paul's option 2): instance-stop, run by PID 1 as root (ExecStop=-+) at a unit stop, reads /proc/self/cgroup and /proc/<pid>/cgroup, where pid is $MAINPID from systemd's own argv (parsed as an integer > 1, never this process); both files are written by the kernel, so a tenant can name neither the path nor its contents beyond its own cgroup; the read only decides whether to signal the pidfd it already holds (equal cgroups), refusing on any error file:ReadFile@145 ee95a7fe4e904caa391e04e36bcf1da913bd3a235b7f13c97139c4d8062125e9 |
| +internal/host/claimunit_template.go const claimBoundTemplate authority E2 PROPOSED E51: Root-only bound-unit template is held inside the claim renderer; ordinary bootstrap never enumerates or installs it.;rev3=census-ruling-instance-stop-execstop-528;basis=one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added data-literal@27 c0095f6293bba755efb9e85a6585babd96a0a4f100a260c80a0a6120db2a9031 |
| +internal/host/units/carlos-instance-gen@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else;rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates);rev3=census-ruling-instance-stop-execstop-528;basis=one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added file:external@0 adcdd2d7607773ae7260dd956dba4ee225f2a499c60615de3b7ab3fa2b797368 |
| +internal/host/units/carlos-instance-sidecar@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else;rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates);rev3=census-ruling-instance-stop-execstop-528;basis=one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added file:external@0 8f62d8d6510292bbc1cb6b013082d50bc538a51d1703b290f91ffc2a8dbcde17 |
| +internal/host/units/carlos-instance@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: one namespace-block line added after TemporaryFileSystem=/dev/mqueue:ro, TemporaryFileSystem=/dev/pts:ro (with its comment): PID 1 mounts an empty read-only tmpfs over the private /dev/pts, hiding the host devpts PrivateDevices= binds in; no bind source, Exec line, user or path read by root added; the block stays byte-identical across the binary templates (TestInstanceTemplatesShareOneNamespace);rev3=census-ruling-instance-syscall-filter;basis=the tenant syscall filter (#527 Q5): three [Service] lines after SystemCallArchitectures=native (SystemCallFilter=@system-service; SystemCallFilter=~@keyring io_uring_setup io_uring_enter io_uring_register userfaultfd; SystemCallErrorNumber=ENOSYS), applied by PID 1 as a seccomp filter on the unit's own process as carlos; no bind source, Exec line, user, mount or path read by root added, with its comment, inside the shared namespace block (byte-identical across the binary templates);rev3=census-ruling-instance-stop-execstop-528;basis=one line added after ExecStart=, ExecStop=-+/opt/carlos/carlos instance-stop $MAINPID (#528, Paul's option 2), plus TimeoutStopFailureMode=kill after TimeoutStopSec=20: PID 1 runs the platform binary's instance-stop as root (the + prefix) at a stop with $MAINPID, a value systemd supplies; instance-stop reads only that argument, /proc/self/cgroup and /proc/<MAINPID>/cgroup (kernel-written), and acts only through a pidfd on the unit's own main process (refused unless in the unit's own cgroup); no bind source, user, mount or tenant-writable path read added file:external@0 ee4538e3c0361b569aaa8abab24ebae79d3144fc7859e518270ea2aa2f143574 |
| +internal/instanceexec/stop_linux.go procCgroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-instance-stop-execstop-528;basis=new (#528, Paul's option 2): instance-stop, run by PID 1 as root (ExecStop=-+) at a unit stop, reads /proc/self/cgroup and /proc/<pid>/cgroup, where pid is $MAINPID from systemd's own argv (parsed as an integer > 1, never this process); both files are written by the kernel, so a tenant can name neither the path nor its contents beyond its own cgroup; the read only decides whether to signal the pidfd it already holds (equal cgroups), refusing on any error file:ReadFile@145 ee95a7fe4e904caa391e04e36bcf1da913bd3a235b7f13c97139c4d8062125e9 |
| +@coverage . 1523897095768fb1b0c71a56056bd9182e52b71a961b07d001e034631c6deba3 |
| +@coverage internal/host b9e219bc73844a2926892b6e254ec64312ec4fa03d0df38fb955e1774884cb9d |
| +@coverage internal/host/units 649e7fe2ece8a3acf4a202d64d0936a65077b287b8cdc307c13dc940db6f5c6f |
| +@coverage internal/instanceexec fa59150895c4932e6287b0f2ad2f37cad2167b6513293f326cee9bc7b42ac1bf |
diff --git a/main.go b/main.go| index 5c19f423b..a483cfae8 100644 |
| --- a/main.go |
| +++ b/main.go |
| @@ -219,6 +219,8 @@ func main() { |
| instanceexec.RunExec(args) |
| case "instance-exit": |
| instanceexec.RunExit(args) |
| + case "instance-stop": |
| + instanceexec.RunStop(args) |
| case "instance-probe": |
| instanceexec.RunProbe(args) |
| case "vet": |