carlos / platform Public

instances: instance-stop spec R2 fixes, docs line, timeout witnesses (#528)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ef960baf7984c0e0edd71f4daa8b00a74873e903 parent daf9848
7 files changed, +548 −14
  • docs/site/cli.md +7 −0
  • docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md +27 −9
  • internal/host/execstop_probe_rootrunner_linux_test.go +507 −1
  • internal/host/plan14_generation_registry_root_linux_test.go +3 −0
  • internal/host/units_execstop_test.go +2 −2
  • internal/instanceexec/stop.go +1 −1
  • internal/instanceexec/stop_linux.go +1 −1

CI failed — 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/specs/2026-11-08-instance-stop-execstop-528-design.md b/docs/superpowers/specs/2026-11-08-instance-stop-execstop-528-design.md
index 8e01e7146..ca4e6d982 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
@@ -55,11 +55,15 @@ Then:
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`.
+- 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.
@@ -126,7 +130,9 @@ An app that ignores SIGTERM has two possible endings:
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
+ 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".
@@ -168,9 +174,12 @@ The cases around a roll:
- **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.
+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)
@@ -228,8 +237,17 @@ From `service.c` v257.9 (Astra spec R1 P2):
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
diff --git a/internal/host/execstop_probe_rootrunner_linux_test.go b/internal/host/execstop_probe_rootrunner_linux_test.go
index c29625cdb..b234515a5 100644
--- a/internal/host/execstop_probe_rootrunner_linux_test.go
+++ b/internal/host/execstop_probe_rootrunner_linux_test.go
@@ -20,6 +20,7 @@ import (
"golang.org/x/sys/unix"
"github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/instanceexec"
"github.com/carlosframework/platform/internal/provision"
)
@@ -47,6 +48,10 @@ func instanceStopTenant() {
}
}
mode := os.Getenv("STOPWIT_MODE")
+ if mode == "exit" {
+ time.Sleep(300 * time.Millisecond)
+ os.Exit(0)
+ }
<-sigs
term()
switch mode {
@@ -324,7 +329,7 @@ func TestRootExecStopProbe(t *testing.T) {
// 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")
+ dropIn("60-probe.conf", "ExecStop=\nExecStop=-+/opt/carlos/carlos "+execStopProbeArg+" $MAINPID")
launch("drain")
for i := 0; i < 12; i++ {
_ = os.Truncate(logPath, 0)
@@ -418,3 +423,504 @@ func execStopProbe(args []string) {
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" {
+ 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) {
+ 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 {
+ 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 {
+ 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 da62cb88b..b75fc274b 100644
--- a/internal/host/plan14_generation_registry_root_linux_test.go
+++ b/internal/host/plan14_generation_registry_root_linux_test.go
@@ -76,6 +76,9 @@ 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
diff --git a/internal/host/units_execstop_test.go b/internal/host/units_execstop_test.go
index 32c610f8f..213e72811 100644
--- a/internal/host/units_execstop_test.go
+++ b/internal/host/units_execstop_test.go
@@ -53,8 +53,8 @@ func TestInstanceStopExecStopTemplates(t *testing.T) {
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)
+ 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"} {
diff --git a/internal/instanceexec/stop.go b/internal/instanceexec/stop.go
index efde00f5e..68d599d5f 100644
--- a/internal/instanceexec/stop.go
+++ b/internal/instanceexec/stop.go
@@ -10,5 +10,5 @@ import "time"
// second SIGTERM (#528).
const (
StopBudget = 18 * time.Second
- killWait = time.Second
+ KillWait = time.Second
)
diff --git a/internal/instanceexec/stop_linux.go b/internal/instanceexec/stop_linux.go
index fbe248167..d1a8857a1 100644
--- a/internal/instanceexec/stop_linux.go
+++ b/internal/instanceexec/stop_linux.go
@@ -95,7 +95,7 @@ func stopMain(args []string, budget time.Duration, cgroupOf func(pid int) (strin
return 0
}
_ = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0)
- waitPidfd(fd, killWait)
+ waitPidfd(fd, KillWait)
return 0
}