host: root witness for the update from a box without sandbox dirs
Replace the unrun TestRootSandboxUpdateDirectories with TestRootSandboxUpdateFromOldBox: units rendered from the embedded control, runsc and edge units start with both directories absent (old shape fails 226), the first pass creates them root:root 0700/0755, one refresh makes oci-rootfs writable to control, /stop over a never-started gVisor sibling logs no Refusing, and an edge-shaped stop through control takes < 10 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 file changed,
+483
−56
internal/host/runsc_update_dirs_rootrunner_linux_test.go+483 −56
diff --git a/internal/host/runsc_update_dirs_rootrunner_linux_test.go b/internal/host/runsc_update_dirs_rootrunner_linux_test.go| index 68fe21394..e280f2cdf 100644 |
| --- a/internal/host/runsc_update_dirs_rootrunner_linux_test.go |
| +++ b/internal/host/runsc_update_dirs_rootrunner_linux_test.go |
| @@ -3,104 +3,531 @@ |
| package host |
| import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| "errors" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| "os" |
| "os/exec" |
| + "os/signal" |
| "path/filepath" |
| "strings" |
| + "syscall" |
| "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| ) |
| -func TestRootSandboxUpdateDirectories(t *testing.T) { |
| - if os.Geteuid() != 0 { |
| - t.Fatal("requires root") |
| +// Payloads of the update witness, dispatched on argv[1] before any test runs. |
| +const ( |
| + udwControlArg = "udw-control" |
| + udwEdgeArg = "udw-edge" |
| + udwRunscArg = "udw-runsc" |
| + |
| + udwBinDir = "/opt/carlos-udw" |
| + udwBin = udwBinDir + "/udw.test" |
| + udwSock = "/run/carlos-control/udw.sock" |
| + udwReady = "/run/carlos/udw-edge.ready" |
| + udwRootfs = "/var/lib/carlos/oci-rootfs" |
| + udwRuntime = "/opt/carlos/runsc" |
| +) |
| + |
| +func init() { |
| + if len(os.Args) < 2 { |
| + return |
| } |
| - for _, path := range []string{"/opt/carlos", "/var/lib/carlos/oci-rootfs", "/etc/carlos/host.env"} { |
| - if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| - t.Fatalf("requires absent %s: %v", path, err) |
| - } |
| + switch { |
| + case os.Args[1] == udwControlArg && len(os.Args) == 3: |
| + os.Exit(udwControl(os.Args[2])) |
| + case os.Args[1] == udwEdgeArg && len(os.Args) == 5: |
| + os.Exit(udwEdge(os.Args[2], os.Args[3], os.Args[4])) |
| + case os.Args[1] == udwRunscArg && len(os.Args) == 2: |
| + os.Exit(udwRunsc()) |
| } |
| - scratch := "/root/.cache/gvisor-demos/updatedirs" |
| - if err := os.MkdirAll(scratch, 0700); err != nil { |
| - t.Fatal(err) |
| +} |
| + |
| +// udwControl stands in for `carlos instance-control`: the production |
| +// instancectl handler, in systemd mode, on a control socket, plus one probe |
| +// route that asks whether this service's own namespace can write oci-rootfs. |
| +func udwControl(sock string) int { |
| + _ = os.Remove(sock) |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "udw-control:", err) |
| + return 75 |
| } |
| - t.Setenv("TMPDIR", scratch) |
| - t.Run("missing", TestRunscEnsureMissingDirectory) |
| - if err := os.Mkdir("/opt/carlos", 0755); err != nil { |
| - t.Fatal(err) |
| + s := &instancectl.Server{ |
| + Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + }, |
| + CgroupRoot: "/sys/fs/cgroup", |
| + DropInDir: "/run/systemd/system", |
| + SandboxEffective: execsandbox.EffectiveSystemd, |
| + Logf: log.Printf, |
| } |
| - t.Cleanup(func() { |
| - if err := os.RemoveAll("/opt/carlos"); err != nil { |
| - t.Error(err) |
| + mux := http.NewServeMux() |
| + mux.Handle("/", s.Handler()) |
| + mux.HandleFunc("/udw-write", func(w http.ResponseWriter, _ *http.Request) { |
| + p := filepath.Join(udwRootfs, "udw-write") |
| + err := os.WriteFile(p, nil, 0o600) |
| + if err == nil { |
| + err = os.Remove(p) |
| + } |
| + if err != nil { |
| + http.Error(w, err.Error(), http.StatusConflict) |
| + return |
| } |
| + w.WriteHeader(http.StatusNoContent) |
| }) |
| - binary, err := os.Executable() |
| + srv := &http.Server{Handler: mux} |
| + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM) |
| + defer cancel() |
| + go func() { <-ctx.Done(); srv.Close() }() |
| + if err := srv.Serve(ln); !errors.Is(err, http.ErrServerClosed) { |
| + fmt.Fprintln(os.Stderr, "udw-control:", err) |
| + return 75 |
| + } |
| + return 0 |
| +} |
| + |
| +// udwEdge stands in for the agent's shutdown: on SIGTERM it stops one |
| +// instance through the control socket with the client the activator uses, |
| +// then exits 0 only if root answered the stop. |
| +func udwEdge(sock, host, ready string) int { |
| + sigs := make(chan os.Signal, 1) |
| + signal.Notify(sigs, syscall.SIGTERM) |
| + if err := os.WriteFile(ready, []byte("up"), 0o644); err != nil { |
| + fmt.Fprintln(os.Stderr, "udw-edge:", err) |
| + return 75 |
| + } |
| + <-sigs |
| + began := time.Now() |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*instancectl.DeadlineControl) |
| + defer cancel() |
| + err := instancectl.NewClient(sock).Stop(ctx, host, instancectl.RoleRun) |
| + fmt.Printf("udw-edge: stop %s through %s: %v after %s\n", host, sock, err, time.Since(began).Round(time.Millisecond)) |
| if err != nil { |
| - t.Fatal(err) |
| + return 1 |
| } |
| - if err := copyFileDurable(binary, "/opt/carlos/updatedirs.test", 0755); err != nil { |
| + return 0 |
| +} |
| + |
| +// udwRunsc is `carlos system runsc-ensure` with the mode taken from the |
| +// unit's Environment= rather than /etc/carlos/host.env. |
| +func udwRunsc() int { |
| + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + defer cancel() |
| + if err := ensureRunsc(ctx, os.Getenv, nil, runscSystemctl); err != nil { |
| + fmt.Fprintln(os.Stderr, "udw-runsc:", err) |
| + return 1 |
| + } |
| + fmt.Println("udw-runsc: ok") |
| + return 0 |
| +} |
| + |
| +// udwUnit renders an embedded unit the way the box installs it |
| +// (claimUnitContent, empty settings) with its ExecStart= swapped for a |
| +// payload and its ordering/dependency lines on other carlos units removed. |
| +// Every namespace and hardening directive stays. drop lists further |
| +// prefixes to remove; extra lines go into [Service]. |
| +func udwUnit(t *testing.T, embedded, execStart string, drop []string, extra ...string) string { |
| + t.Helper() |
| + raw, err := unitsFS.ReadFile("units/" + embedded) |
| + if err != nil { |
| t.Fatal(err) |
| } |
| - wrapper := "#!/bin/sh\nexec /opt/carlos/updatedirs.test -test.run=^TestRootSandboxUpdateRunscPayload$ -test.v\n" |
| - if err := os.WriteFile("/opt/carlos/carlos", []byte(wrapper), 0755); err != nil { |
| + strip := append([]string{"Requires=", "Wants=", "After=", "Before=", "BindsTo=", "ExecStart=", "ExecReload=", "WantedBy="}, drop...) |
| + var lines []string |
| + for _, line := range strings.Split(string(claimUnitContent(embedded, raw, claimUnitSettings{})), "\n") { |
| + skip := false |
| + for _, p := range strip { |
| + if strings.HasPrefix(line, p) { |
| + skip = true |
| + } |
| + } |
| + if skip { |
| + continue |
| + } |
| + lines = append(lines, line) |
| + if strings.TrimSpace(line) == "[Service]" { |
| + lines = append(lines, "ExecStart="+execStart) |
| + lines = append(lines, extra...) |
| + } |
| + } |
| + return strings.Join(lines, "\n") |
| +} |
| + |
| +// TestRootSandboxUpdateFromOldBox is the v0.34.33 -> new update on real |
| +// systemd as root. A fresh runner has neither /var/lib/carlos nor |
| +// /opt/carlos, the state the old updater left on sophie and demo box-1. |
| +// |
| +// (a) control- and runsc-shaped units rendered from the embedded units |
| +// start without 226/NAMESPACE while both directories are absent; the old |
| +// runsc shape (hard ReadWritePaths=) fails 226 beside them; runsc-ensure in |
| +// gVisor mode refuses with EXEC-SANDBOX-RUNSC. (b) the adopt pass |
| +// (ensureSystemUnits on /etc, systemctl seams faked so nothing is armed) |
| +// creates both directories root:root 0700/0755 although it ends early; the |
| +// running control cannot write oci-rootfs until refreshControlSandboxRootfs |
| +// restarts it once, and a second refresh does nothing. (c) a production |
| +// /stop over a never-started gVisor sibling, with the shipped commandless |
| +// gVisor template installed, logs no "Refusing"; a direct show of the same |
| +// name afterwards does (positive control). (d) an edge-shaped unit whose |
| +// SIGTERM stops an instance through the healthy control stops in < 10 s. |
| +func TestRootSandboxUpdateFromOldBox(t *testing.T) { |
| + if os.Geteuid() != 0 { |
| + t.Fatal("requires the throwaway root runner") |
| + } |
| + 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 nonce [5]byte |
| + if _, err := rand.Read(nonce[:]); err != nil { |
| t.Fatal(err) |
| } |
| - names := []string{claimControlUnit, "carlos-runsc.service", instanceControlSocket, "data-instances.mount", "run-carlos-instances.mount", "run-carlos-logs.mount"} |
| - var installed []string |
| - t.Cleanup(func() { |
| - out, err := exec.Command("systemctl", "stop", "carlos-runsc.service").CombinedOutput() |
| + host := "udw-" + hex.EncodeToString(nonce[:]) + ".example" |
| + native, sibling := instancectl.UnitName(instancectl.RoleRun, host), instancectl.GVisorUnitName(host) |
| + if !strings.Contains(sibling, `\x2d`) { |
| + t.Fatalf("sibling name is not escaped: %s", sibling) |
| + } |
| + const ( |
| + control = "carlos-udw-control.service" |
| + runsc = "carlos-udw-runsc.service" |
| + runscGVisor = "carlos-udw-runsc-gvisor.service" |
| + runscOld = "carlos-udw-runsc-old.service" |
| + edge = "carlos-udw-edge.service" |
| + template = instancectl.UnitPrefixGVisor + ".service" |
| + ) |
| + units := []string{control, runsc, runscGVisor, runscOld, edge, native, template} |
| + for _, path := range []string{"/var/lib/carlos", "/opt/carlos", udwBinDir, "/run/carlos-control", "/run/carlos", "/data", "/etc/carlos/host.env", "/etc/carlos/group.json"} { |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("this witness runs only on a fresh runner: %s: %v", path, err) |
| + } |
| + } |
| + for _, name := range units { |
| + for _, dir := range []string{"/etc/systemd/system", "/run/systemd/system", "/usr/lib/systemd/system", "/lib/systemd/system"} { |
| + if _, err := os.Lstat(filepath.Join(dir, name)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("preexisting unit %s/%s: %v", dir, name, err) |
| + } |
| + } |
| + } |
| + |
| + 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.Errorf("stop: %v: %s", err, out) |
| + t.Fatalf("systemctl %s: %v: %s", strings.Join(args, " "), err, out) |
| + } |
| + return out |
| + } |
| + show := func(unit, props string) map[string]string { |
| + t.Helper() |
| + m := map[string]string{} |
| + for _, line := range strings.Split(must("show", "-p", props, unit), "\n") { |
| + if k, v, ok := strings.Cut(line, "="); ok { |
| + m[k] = v |
| + } |
| + } |
| + t.Logf("%s: %v", unit, m) |
| + return m |
| + } |
| + var installed, made []string |
| + t.Cleanup(func() { |
| + for _, unit := range []string{edge, native, control, runsc, runscGVisor, runscOld} { |
| + _, _ = ctl("stop", unit) |
| } |
| for _, path := range installed { |
| if err := os.Remove(path); err != nil { |
| - t.Error(err) |
| + t.Errorf("cleanup %s: %v", path, err) |
| } |
| } |
| - out, err = exec.Command("systemctl", "daemon-reload").CombinedOutput() |
| - if err != nil { |
| - t.Errorf("reload: %v: %s", err, out) |
| - } |
| - }) |
| - for _, name := range names { |
| - for _, dir := range []string{"/etc/systemd/system", "/run/systemd/system", "/usr/lib/systemd/system"} { |
| - if _, err := os.Lstat(filepath.Join(dir, name)); !errors.Is(err, os.ErrNotExist) { |
| - t.Fatalf("preexisting unit %s: %v", name, err) |
| + _, _ = ctl("daemon-reload") |
| + _, _ = ctl("reset-failed") |
| + _, _ = ctl("stop", instancectl.SliceName(host)) |
| + for i := len(made) - 1; i >= 0; i-- { |
| + if err := os.RemoveAll(made[i]); err != nil { |
| + t.Errorf("cleanup %s: %v", made[i], err) |
| } |
| } |
| - raw, err := unitsFS.ReadFile("units/" + name) |
| - if err != nil { |
| + }) |
| + // Created before anything can make them, so cleanup removes them whole. |
| + made = append(made, "/var/lib/carlos", "/opt/carlos") |
| + for _, dir := range []struct { |
| + path string |
| + mode os.FileMode |
| + }{{udwBinDir, 0o755}, {"/run/carlos-control", 0o700}, {"/run/carlos", 0o755}, {"/data", 0o755}} { |
| + if err := os.Mkdir(dir.path, dir.mode); err != nil { |
| t.Fatal(err) |
| } |
| + made = append(made, dir.path) |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := copyFileDurable(self, udwBin, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + install := func(name, body string) { |
| + t.Helper() |
| path := filepath.Join("/run/systemd/system", name) |
| - if err := os.WriteFile(path, raw, 0644); err != nil { |
| + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { |
| t.Fatal(err) |
| } |
| installed = append(installed, path) |
| + t.Logf("installed %s:\n%s", path, body) |
| + } |
| + controlBody := udwUnit(t, claimControlUnit, udwBin+" "+udwControlArg+" "+udwSock, []string{"MemoryMax="}) |
| + runscBody := udwUnit(t, "carlos-runsc.service", udwBin+" "+udwRunscArg, nil) |
| + for body, want := range map[string]string{controlBody: "ReadWritePaths=-" + udwRootfs + "\n", runscBody: "ReadWritePaths=-" + udwRuntime + "\n"} { |
| + if !strings.Contains(body, want) || !strings.Contains(body, "ProtectSystem=strict\n") { |
| + t.Fatalf("rendered unit lost %q or ProtectSystem=strict:\n%s", want, body) |
| + } |
| + } |
| + install(control, controlBody) |
| + install(runsc, runscBody) |
| + install(runscGVisor, udwUnit(t, "carlos-runsc.service", udwBin+" "+udwRunscArg, nil, "Environment=CARLOS_EXEC_SANDBOX=gvisor")) |
| + install(runscOld, strings.Replace(runscBody, "ReadWritePaths=-"+udwRuntime, "ReadWritePaths="+udwRuntime, 1)) |
| + // The edge runs as root here: no carlos user on the runner, and root's |
| + // socket is 0700 under /run/carlos-control. Every other directive stays. |
| + install(edge, udwUnit(t, "carlos-edge.service", udwBin+" "+udwEdgeArg+" "+udwSock+" "+host+" "+udwReady, []string{"User=", "Group=", "AmbientCapabilities=", "CapabilityBoundingSet="})) |
| + must("daemon-reload") |
| + |
| + absent := func(when string) { |
| + t.Helper() |
| + for _, path := range []string{udwRootfs, udwRuntime} { |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("%s: %s exists: %v", when, path, err) |
| + } |
| + } |
| + } |
| + controlClient := &http.Client{Transport: &http.Transport{DisableKeepAlives: true, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "unix", udwSock) |
| + }}, Timeout: 5 * time.Second} |
| + probeWrite := func() (int, string) { |
| + resp, err := controlClient.Post("http://control/udw-write", "", nil) |
| + if err != nil { |
| + return 0, err.Error() |
| + } |
| + defer resp.Body.Close() |
| + b, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, strings.TrimSpace(string(b)) |
| + } |
| + waitControl := func() { |
| + t.Helper() |
| + deadline := time.Now().Add(15 * time.Second) |
| + for { |
| + if code, _ := probeWrite(); code != 0 { |
| + return |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("control socket never answered: %v", show(control, "ActiveState,SubState,Result,ExecMainStatus,NRestarts")) |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + } |
| + |
| + // (a) The update's restart, with both directories absent. |
| + absent("before the units start") |
| + if _, err := ctl("start", runscOld); err == nil { |
| + t.Fatal("the old runsc shape started with its directory absent") |
| + } |
| + if m := show(runscOld, "Result,ExecMainStatus"); m["ExecMainStatus"] != "226" { |
| + t.Fatalf("old runsc shape: want 226/NAMESPACE as on sophie, got %v", m) |
| + } |
| + must("start", runsc) |
| + if m := show(runsc, "Result,ExecMainStatus"); m["Result"] != "success" || m["ExecMainStatus"] != "0" { |
| + t.Fatalf("runsc unit (systemd mode) with %s absent: %v", udwRuntime, m) |
| + } |
| + if _, err := ctl("start", runscGVisor); err == nil { |
| + t.Fatal("gVisor runsc-ensure accepted an absent runtime directory") |
| + } |
| + if m := show(runscGVisor, "Result,ExecMainStatus"); m["ExecMainStatus"] == "226" || m["ExecMainStatus"] == "0" { |
| + t.Fatalf("gVisor runsc-ensure: want its own refusal, not namespace failure: %v", m) |
| } |
| - for _, args := range [][]string{{"systemd-analyze", "verify", "/run/systemd/system/" + claimControlUnit, "/run/systemd/system/carlos-runsc.service"}, {"systemctl", "daemon-reload"}, {"systemctl", "start", "carlos-runsc.service"}} { |
| - out, err := exec.Command(args[0], args[1:]...).CombinedOutput() |
| - t.Logf("%s: %s", strings.Join(args, " "), out) |
| + var journal string |
| + for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { |
| + out, _ := exec.Command("journalctl", "--no-pager", "-o", "cat", "-u", runscGVisor).CombinedOutput() |
| + if journal = string(out); strings.Contains(journal, execsandbox.ErrRunsc.Error()) { |
| + break |
| + } |
| + } |
| + if !strings.Contains(journal, execsandbox.ErrRunsc.Error()) || !strings.Contains(journal, udwRuntime) { |
| + t.Fatalf("gVisor refusal does not name EXEC-SANDBOX-RUNSC and %s:\n%s", udwRuntime, journal) |
| + } |
| + t.Logf("gVisor runsc-ensure refusal:\n%s", journal) |
| + must("start", control) |
| + waitControl() |
| + if m := show(control, "ActiveState,Result,ExecMainStatus,NRestarts"); m["ActiveState"] != "active" || m["NRestarts"] != "0" || m["ExecMainStatus"] == "226" { |
| + t.Fatalf("control unit with %s absent: %v", udwRootfs, m) |
| + } |
| + absent("after the units started") |
| + t.Log("(a) PASS: control and runsc units start with both directories absent; old shape fails 226") |
| + |
| + // (b) The first adopt pass of the new build. systemctl answers nothing, |
| + // one of the early returns, so the pass arms and installs nothing. |
| + lockPath := filepath.Join(systemRootDir("/opt/carlos"), systemLockFile) |
| + ensureSystemUnits("/etc", lockPath, func(args ...string) (string, error) { |
| + t.Errorf("first pass ran systemctl %v", args) |
| + return "", errors.New("witness: no systemctl") |
| + }, func(args ...string) (string, error) { |
| + return "", errors.New("witness: systemctl silent") |
| + }, t.Logf) |
| + for path, mode := range map[string]os.FileMode{udwRootfs: 0o700, udwRuntime: 0o755, "/var/lib/carlos": 0o700} { |
| + st, err := os.Lstat(path) |
| if err != nil { |
| t.Fatal(err) |
| } |
| + sys := st.Sys().(*syscall.Stat_t) |
| + if !st.IsDir() || st.Mode().Perm() != mode || sys.Uid != 0 || sys.Gid != 0 { |
| + t.Fatalf("%s: mode %v uid %d gid %d, want root:root %04o", path, st.Mode(), sys.Uid, sys.Gid, mode) |
| + } |
| + t.Logf("%s root:root %04o", path, st.Mode().Perm()) |
| } |
| - out, err := exec.Command("systemctl", "show", "carlos-runsc.service", "-p", "Result", "-p", "ExecMainStatus").CombinedOutput() |
| - if err != nil || !strings.Contains(string(out), "Result=success") || !strings.Contains(string(out), "ExecMainStatus=0") { |
| - t.Fatalf("runsc unit: %v: %s", err, out) |
| + code, body := probeWrite() |
| + if code != http.StatusConflict || !strings.Contains(body, "read-only file system") { |
| + t.Fatalf("control started before %s existed should see it read-only: %d %s", udwRootfs, code, body) |
| } |
| - t.Log(string(out)) |
| - for _, path := range []string{"/opt/carlos/runsc", "/var/lib/carlos/oci-rootfs"} { |
| - if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| - t.Fatalf("systemd mode created %s: %v", path, err) |
| + t.Logf("control before refresh: %d %s", code, body) |
| + mainPID := func() string { return show(control, "MainPID")["MainPID"] } |
| + before := mainPID() |
| + var calls []string |
| + mapped := func(args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + if strings.Join(args, " ") != "try-restart "+claimControlUnit { |
| + return "", fmt.Errorf("witness: unexpected systemctl %v", args) |
| } |
| + return ctl("try-restart", control) |
| } |
| - t.Run("adopt", TestSandboxUpdateAdoptCreatesDirectories) |
| -} |
| + probe := func(args ...string) (string, error) { |
| + if strings.Join(args, " ") != "show -p MainPID --value "+claimControlUnit { |
| + return "", fmt.Errorf("witness: unexpected probe %v", args) |
| + } |
| + return ctl("show", "-p", "MainPID", "--value", control) |
| + } |
| + gvisorEnv := &systemApplier{sandboxEnvironment: func() (func(string) string, error) { |
| + return func(k string) string { |
| + if k == "CARLOS_EXEC_SANDBOX" { |
| + return "gvisor" |
| + } |
| + return "" |
| + }, nil |
| + }} |
| + refreshControlSandboxRootfs("/etc", gvisorEnv, mapped, probe, t.Logf) |
| + if strings.Join(calls, "|") != "try-restart "+claimControlUnit { |
| + t.Fatalf("refresh calls %q, want one try-restart", calls) |
| + } |
| + waitControl() |
| + after := mainPID() |
| + if after == before || after == "0" { |
| + t.Fatalf("control was not restarted: MainPID %s -> %s", before, after) |
| + } |
| + if code, body := probeWrite(); code != http.StatusNoContent { |
| + t.Fatalf("restarted control still cannot write %s: %d %s", udwRootfs, code, body) |
| + } |
| + calls = nil |
| + refreshControlSandboxRootfs("/etc", gvisorEnv, mapped, probe, t.Logf) |
| + if len(calls) != 0 || mainPID() != after { |
| + t.Fatalf("a second refresh restarted a control that has the path: %q", calls) |
| + } |
| + t.Log("(b) PASS: first pass creates root:root 0700/0755; one refresh makes oci-rootfs writable; no restart loop") |
| + |
| + // (c) A production /stop over a never-started gVisor sibling. |
| + tb, err := unitsFS.ReadFile("units/" + template) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + install(template, string(tb)) |
| + must("daemon-reload") |
| + cursor := func() string { |
| + t.Helper() |
| + out, err := exec.Command("journalctl", "-n", "1", "--show-cursor", "--no-pager", "-o", "cat").CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("journal cursor: %v %s", err, out) |
| + } |
| + _, c, ok := strings.Cut(string(out), "-- cursor: ") |
| + if !ok { |
| + t.Fatalf("no cursor: %s", out) |
| + } |
| + return strings.TrimSpace(c) |
| + } |
| + since := func(c string) string { |
| + out, _ := exec.Command("journalctl", "--after-cursor="+c, "--no-pager", "-o", "short-precise").CombinedOutput() |
| + return string(out) |
| + } |
| + refusing := func(log string) bool { |
| + for _, line := range strings.Split(log, "\n") { |
| + if strings.Contains(line, "Refusing") && strings.Contains(line, sibling) { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + c1 := cursor() |
| + s := &instancectl.Server{Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + }, CgroupRoot: "/sys/fs/cgroup", DropInDir: "/run/systemd/system", SandboxEffective: execsandbox.EffectiveGVisor} |
| + w := httptest.NewRecorder() |
| + s.Handler().ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/stop?host="+host+"&role=run", nil)) |
| + if w.Code != http.StatusNoContent { |
| + t.Fatalf("/stop: %d %s", w.Code, w.Body) |
| + } |
| + time.Sleep(2 * time.Second) |
| + if log := since(c1); refusing(log) { |
| + t.Fatalf("/stop named the never-started gVisor sibling:\n%s", log) |
| + } |
| + _, _ = ctl("show", "-p", "LoadState", sibling) |
| + var positive string |
| + for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) { |
| + if positive = since(c1); refusing(positive) { |
| + break |
| + } |
| + } |
| + if !refusing(positive) { |
| + t.Fatalf("positive control: a direct show of %s logged no Refusing, so the negative proves nothing:\n%s", sibling, positive) |
| + } |
| + t.Logf("positive control journal:\n%s", positive) |
| + t.Log("(c) PASS: /stop over a never-started gVisor sibling logs no Refusing; a direct show does") |
| -func TestRootSandboxUpdateRunscPayload(t *testing.T) { |
| - if _, err := os.Lstat("/opt/carlos/runsc"); !errors.Is(err, os.ErrNotExist) { |
| - t.Fatalf("runtime directory present: %v", err) |
| + // (d) The edge's shutdown stops an instance through the healthy control. |
| + install(native, fmt.Sprintf("[Unit]\nDescription=update witness instance\n[Service]\nType=exec\nExecStart=/bin/sleep infinity\nSlice=%s\nKillMode=control-group\nTimeoutStopSec=3s\n", instancectl.SliceName(host))) |
| + must("daemon-reload") |
| + must("start", native) |
| + must("start", edge) |
| + for deadline := time.Now().Add(15 * time.Second); ; time.Sleep(100 * time.Millisecond) { |
| + if _, err := os.Stat(udwReady); err == nil { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("edge payload never ready: %v", show(edge, "ActiveState,Result,ExecMainStatus")) |
| + } |
| + } |
| + began := time.Now() |
| + must("stop", edge) |
| + took := time.Since(began) |
| + out, _ := exec.Command("journalctl", "--no-pager", "-o", "cat", "-u", edge).CombinedOutput() |
| + t.Logf("edge stop took %s; journal:\n%s", took.Round(time.Millisecond), out) |
| + if m := show(edge, "Result,ExecMainStatus"); m["Result"] != "success" || m["ExecMainStatus"] != "0" { |
| + t.Fatalf("edge payload's stop through control failed: %v", m) |
| + } |
| + if m := show(native, "ActiveState,MainPID"); m["ActiveState"] != "inactive" || m["MainPID"] != "0" { |
| + t.Fatalf("instance not stopped through control: %v", m) |
| + } |
| + if took >= 10*time.Second { |
| + t.Fatalf("edge-shaped stop took %s, want < 10s", took) |
| } |
| - RunSystemRunscEnsure(nil) |
| + t.Logf("(d) PASS: edge-shaped stop through the healthy control took %s", took.Round(time.Millisecond)) |
| } |