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