instances: instance-stop root ExecStop (#528 option 2), spec R1 fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+452
−23
docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md+63 −23internal/host/claimunit_template.go+2 −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+121 −0internal/instanceexec/stop_linux_test.go+141 −0internal/instanceexec/stop_other.go+14 −0main.go+2 −0
CI cancelled — superseded by a newer push — 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| index 41ac2e9d8..8e01e7146 100644 |
| --- 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 |
| @@ -25,11 +25,31 @@ 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: |
| + 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. |
| @@ -41,6 +61,16 @@ the deadline, it sends SIGKILL to the main process and returns. Then: |
| `ExecStopPost`. The result comes from the main process's exit: 0 or 143 |
| is `success`. |
| +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`. These |
| + are not bounded by the helper. A main process stuck in an uninterruptible |
| + wait leaves systemd in its kill phase, exactly as today. The activator's |
| + unit observer already holds such a stop as unproven (`unitproc.go`) and |
| + does not release it. |
| + |
| ### How the helper finds and signals the main process |
| Settled on a real box (root runner, run 20261108T174833-c5142a, probe |
| @@ -68,9 +98,11 @@ The helper: |
| 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. |
| +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 |
| @@ -117,6 +149,8 @@ trampoline that matters is the one that started the instance. |
| | 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: |
| @@ -138,18 +172,19 @@ 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 |
| +## Stop paths (when ExecStop runs, and when it does not) |
| + |
| +From `service.c` v257.9 (Astra spec R1 P2): |
| -- **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. |
| +| 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 |
| @@ -166,9 +201,8 @@ behaviour. |
| ## 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. |
| + 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. |
| @@ -189,7 +223,13 @@ behaviour. |
| - **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. |
| + 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`; |
| + - for every stop, the final unit result, `ExecMainStatus`, the |
| + ExecStopPost exit record in the run directory, and an empty cgroup. |
| ## Census |
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/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..32c610f8f |
| --- /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 { |
| + t.Errorf("%s: TimeoutStopSec %s does not exceed the helper's %s budget", name, stop, instanceexec.StopBudget) |
| + } |
| + } |
| + 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..efde00f5e |
| --- /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..fbe248167 |
| --- /dev/null |
| +++ b/internal/instanceexec/stop_linux.go |
| @@ -0,0 +1,121 @@ |
| +//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. By the |
| +// time systemd's own SIGTERM phase begins the main process is gone, so |
| +// the app gets exactly one SIGTERM whatever systemd thinks of its parent. |
| +// |
| +// 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/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": |