carlos / platform Public

host: root-runner witness for instance stops under PrivatePIDs (#528)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ce423ca0b7e5a99ffe489e16e311e747e8a9df29 parent e2e0684
2 files changed, +344 −0
  • internal/host/instancestop_rootrunner_linux_test.go +341 −0
  • internal/host/plan14_generation_registry_root_linux_test.go +3 −0

CI failed — run details

diff --git a/internal/host/instancestop_rootrunner_linux_test.go b/internal/host/instancestop_rootrunner_linux_test.go
new file mode 100644
index 000000000..44eff219d
--- /dev/null
+++ b/internal/host/instancestop_rootrunner_linux_test.go
@@ -0,0 +1,341 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "encoding/json"
+ "errors"
+ "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. In the default mode
+// it drains for 200 ms and exits 0; with STOPWIT_MODE=ignore it 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)
+ }
+ ignore := os.Getenv("STOPWIT_MODE") == "ignore"
+ for range sigs {
+ f, err := os.OpenFile("terms", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644)
+ if err == nil {
+ _, _ = f.WriteString("term\n")
+ _ = f.Close()
+ }
+ if !ignore {
+ time.Sleep(200 * time.Millisecond)
+ os.Exit(0)
+ }
+ }
+}
+
+// TestRootInstanceStopUnderPrivatePIDs is #528's real-box witness. It
+// installs the embedded carlos-instance@.service under a test name with
+// only its [Unit] couplings removed, so every [Service] line runs as
+// shipped, and runs the real trampoline (this binary as /opt/carlos/carlos,
+// dispatched by TestMain) over a tenant that is this binary too.
+//
+// 1. KillMode=mixed restored by drop-in: the race reproduces. Some starts
+// log "not our child", and those stops end Result=signal.
+// 2. The shipped template: every stop ends Result=success with the tenant
+// having seen SIGTERM, including the starts that logged "not our child".
+// 3. A tenant that ignores SIGTERM, TimeoutStopSec=3 by drop-in: the stop
+// SIGKILLs it within the bound and leaves no process behind.
+//
+// It needs a fresh runner (no /opt/carlos/carlos, no /etc/carlos, no
+// /data/instances). It removes everything it made. No network.
+func TestRootInstanceStopUnderPrivatePIDs(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
+ write(exe+"/app", bin, 0o755)
+ 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), "KillMode=control-group") {
+ t.Fatal("embedded template is not the PrivatePIDs, control-group template this witness is for")
+ }
+ template := "carlos-stopwit@.service"
+ if out, _ := ctl("show", "-p", "LoadState", "--value", template); out != "not-found" {
+ t.Fatalf("%s already present: %s", template, out)
+ }
+ 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 bool
+ terms int
+ stop time.Duration
+ }
+ cycle := func() outcome {
+ t.Helper()
+ for _, f := range []string{"up", "terms"} {
+ _ = 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()
+ t.Fatalf("unit %s before the tenant was up: %s", s, log)
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("tenant never came up")
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ began := time.Now()
+ 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")
+ }
+ // 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)
+ }
+ if p, err := os.ReadFile("/sys/fs/cgroup/" + strings.TrimPrefix(must("show", "-p", "ControlGroup", "--value", unit), "/") + "/cgroup.procs"); err == nil && strings.TrimSpace(string(p)) != "" {
+ t.Fatalf("processes left after stop: %s", p)
+ }
+ return o
+ }
+
+ const n = 40
+
+ // 1. The old KillMode: the race reproduces here.
+ launch("drain")
+ dropIn("50-mixed.conf", "KillMode=mixed")
+ var mixedAlien, mixedSignal int
+ for i := 0; i < n; i++ {
+ o := cycle()
+ if o.alien {
+ mixedAlien++
+ }
+ if o.result == "signal" {
+ mixedSignal++
+ if !o.alien {
+ t.Errorf("mixed cycle %d: Result=signal without a \"not our child\" line: %+v", i, o)
+ }
+ }
+ }
+ undrop("50-mixed.conf")
+ t.Logf("verdict: mixed: %d/%d alien, %d/%d Result=signal", mixedAlien, n, mixedSignal, n)
+ if mixedSignal == 0 {
+ t.Fatalf("the race did not reproduce under KillMode=mixed in %d cycles (%d alien): the witness cannot tell the fix apart", n, mixedAlien)
+ }
+
+ // 2. The shipped template.
+ var fixedAlien, maxTerms int
+ for i := 0; i < n; i++ {
+ o := cycle()
+ if o.alien {
+ fixedAlien++
+ }
+ if o.terms > maxTerms {
+ maxTerms = o.terms
+ }
+ if o.result != "success" || o.terms == 0 {
+ t.Errorf("control-group cycle %d: %+v", i, o)
+ }
+ }
+ t.Logf("verdict: control-group: %d/%d alien, all Result=success unless an error above; most SIGTERMs one tenant saw: %d", fixedAlien, n, maxTerms)
+ if fixedAlien == 0 {
+ t.Fatalf("no start was alien in %d control-group cycles: the fix was not exercised against the race", n)
+ }
+
+ // 3. A tenant that ignores SIGTERM is still killed within the bound.
+ launch("ignore")
+ dropIn("50-short.conf", "TimeoutStopSec=3")
+ o := cycle()
+ undrop("50-short.conf")
+ t.Logf("verdict: ignore-SIGTERM stop: %+v", o)
+ if o.terms == 0 || o.stop < 3*time.Second || o.stop > 10*time.Second || o.result != "timeout" {
+ t.Errorf("ignore-SIGTERM stop not bounded as designed: %+v", o)
+ }
+ if s := must("show", "-p", "ActiveState", "--value", unit); s != "inactive" && s != "failed" {
+ t.Errorf("unit %s after the bounded stop", s)
+ }
+}
diff --git a/internal/host/plan14_generation_registry_root_linux_test.go b/internal/host/plan14_generation_registry_root_linux_test.go
index 20de50ce6..ff1282dca 100644
--- a/internal/host/plan14_generation_registry_root_linux_test.go
+++ b/internal/host/plan14_generation_registry_root_linux_test.go
@@ -79,6 +79,9 @@ func TestMain(m *testing.M) {
case "plan14-tenant":
plan14InstalledTenant()
return
+ case instanceStopTenantArg:
+ instanceStopTenant()
+ return
}
}
if len(os.Args) > 1 && os.Args[1] == registryChildCommand {