carlos / platform Public

spec: root ExecStop for instance stops under PrivatePIDs (#528 option 2)

Includes the root-runner probe that settled the + prefix, MAINPID's
namespace, the syscall filter and RuntimeMaxSec (run
20261108T174833-c5142a).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8c4a75736078f36445f7ca7501e70abab63e36cf parent 663b76b
3 files changed, +626 −0
  • docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md +200 −0
  • internal/host/execstop_probe_rootrunner_linux_test.go +420 −0
  • internal/host/plan14_generation_registry_root_linux_test.go +6 −0

CI passed — run details

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..41ac2e9d8
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md
@@ -0,0 +1,200 @@
+# 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
+
+`instance-stop` is a new root-run verb. It sends exactly one SIGTERM to the
+main process and waits for it to exit, within a budget of 18 s (the unit's
+`TimeoutStopSec=20` less a margin). If the main process is still alive at
+the deadline, it sends SIGKILL to the main process and returns. 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. The main
+ process is gone, so it 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`.
+
+### 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;
+5. polls the pidfd for exit, up to the deadline; on timeout,
+ `pidfd_send_signal(fd, SIGKILL)` 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 stop is bounded at about 18 s, under today's 20 s. 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 | 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, and none gives it none while the main
+process is alive. Every cell is either exactly one SIGTERM or today's
+behaviour.
+
+## When ExecStop does not run
+
+- **The main process exits by itself, or crashes, or is OOM-killed:** no
+ stop job, so no ExecStop. This is unchanged.
+- **`RuntimeMaxSec=` expiry:** systemd's expiry runs `service_enter_stop`,
+ which runs ExecStop. Seen on the runner: the app drained on one SIGTERM.
+ The unit then reads `Result=timeout`, as systemd always records an
+ expiry. Demos keep their bound: SIGTERM, at most 18 s, then SIGKILL.
+- **The activator's stops** (hibernate, deploy swap, demo takedown, edge
+ restart via `BindsTo=`) are all `systemctl stop`, so all of them run
+ ExecStop.
+- **A start that times out**, or `systemctl kill`: no ExecStop, 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 and kill-at-deadline. The
+ signalling and waiting run through a pidfd seam over 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.
+
+## 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/execstop_probe_rootrunner_linux_test.go b/internal/host/execstop_probe_rootrunner_linux_test.go
new file mode 100644
index 000000000..c29625cdb
--- /dev/null
+++ b/internal/host/execstop_probe_rootrunner_linux_test.go
@@ -0,0 +1,420 @@
+//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/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")
+ <-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=-+/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))
+}
diff --git a/internal/host/plan14_generation_registry_root_linux_test.go b/internal/host/plan14_generation_registry_root_linux_test.go
index 20de50ce6..da62cb88b 100644
--- a/internal/host/plan14_generation_registry_root_linux_test.go
+++ b/internal/host/plan14_generation_registry_root_linux_test.go
@@ -79,6 +79,12 @@ func TestMain(m *testing.M) {
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 {