| 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) |
| + } |
| +} |