carlos / platform Public

host: create sandbox dirs on every first pass; refresh control

The adopt pass created /var/lib/carlos/oci-rootfs and /opt/carlos/runsc
only after the apply lock, the host.env gate and the systemctl probe, so
a pass meeting the old update's apply (a stage request during its soak)
skipped them. Create them first on non-group boxes; group members still
wait for their maintenance permit.

instance-control started before oci-rootfs existed has the optional
ReadWritePaths= entry skipped, so the directory is read-only inside its
namespace. In gVisor mode, when the path is not in the service's mount
table, try-restart it once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 62f6118648b9b8d0ee14a68af261c6dc3dabf2e9 parent 56f7d87
3 files changed, +238 −3
  • internal/host/execsandboxfloor.go +53 −0
  • internal/host/runsc_update_dirs_linux_test.go +166 −0
  • internal/host/systemunits.go +19 −3
diff --git a/internal/host/execsandboxfloor.go b/internal/host/execsandboxfloor.go
index 6a41b1ef1..04d83f1cd 100644
--- a/internal/host/execsandboxfloor.go
+++ b/internal/host/execsandboxfloor.go
@@ -9,6 +9,7 @@ import (
"log"
"os"
"path/filepath"
+ "strings"
"github.com/carlosframework/platform/internal/execsandbox"
)
@@ -131,6 +132,58 @@ func ensureSandboxDirectories(root, optDir string) error {
return bootstrapMakeDir(filepath.Join(optDir, "runsc"), 0755)
}
+// controlMountinfo reads a process's mount table; a seam for tests.
+var controlMountinfo = func(pid string) ([]byte, error) {
+ return os.ReadFile(filepath.Join("/proc", pid, "mountinfo"))
+}
+
+// refreshControlSandboxRootfs restarts instance-control once when it runs
+// gVisor but started before oci-rootfs existed. Its unit names that
+// directory as an optional ReadWritePaths= (an update from v0.34.33 starts
+// it before anything has created it), and systemd skips a missing optional
+// path when it builds the service's namespace. Created later, the
+// directory shows through ProtectSystem=strict read-only, so every gVisor
+// start would fail writing its rootfs until the next restart. A path
+// systemd made writable is a mount point in the service's mount table, so
+// its absence there is the fact this reads; one try-restart (a stopped
+// service stays stopped) rebuilds the namespace. systemd mode never writes
+// the directory and is left alone, as is anything this cannot read.
+func refreshControlSandboxRootfs(etcDir string, a *systemApplier, systemctl, probe func(args ...string) (string, error), logf func(string, ...any)) {
+ read := a.sandboxEnvironment
+ if read == nil {
+ read = func() (func(string) string, error) {
+ return sandboxHostEnvironmentAt(filepath.Join(etcDir, "carlos", "host.env"))
+ }
+ }
+ getenv, err := read()
+ if err != nil {
+ return
+ }
+ if _, effective, err := execsandbox.ResolveFromEnv(getenv); err != nil || effective != execsandbox.EffectiveGVisor {
+ return
+ }
+ out, _ := probe("show", "-p", "MainPID", "--value", claimControlUnit)
+ pid := strings.TrimSpace(out)
+ if pid == "" || pid == "0" || strings.Trim(pid, "0123456789") != "" {
+ return
+ }
+ rootfs := filepath.Join(filepath.Dir(etcDir), "var/lib/carlos/oci-rootfs")
+ raw, err := controlMountinfo(pid)
+ if err != nil {
+ logf("adopt: %s mount table: %v", claimControlUnit, err)
+ return
+ }
+ for _, line := range strings.Split(string(raw), "\n") {
+ if f := strings.Fields(line); len(f) > 4 && f[4] == rootfs {
+ return
+ }
+ }
+ logf("adopt: %s started before %s existed; restarting it so gVisor can write there", claimControlUnit, rootfs)
+ if _, err := systemctl("try-restart", claimControlUnit); err != nil {
+ logf("adopt: systemctl try-restart %s: %v", claimControlUnit, err)
+ }
+}
+
// Called by instance-control as root: the agent cannot read root's 0600 host.env.
func sandboxEnvironmentProblem(read func() (func(string) string, error)) error {
getenv, err := read()
diff --git a/internal/host/runsc_update_dirs_linux_test.go b/internal/host/runsc_update_dirs_linux_test.go
index 6f51f156e..5d89597b9 100644
--- a/internal/host/runsc_update_dirs_linux_test.go
+++ b/internal/host/runsc_update_dirs_linux_test.go
@@ -141,3 +141,169 @@ func TestRunscEnsureMissingDirectory(t *testing.T) {
}
}
}
+
+// oldSandboxBox lays out a box a v0.34.33 updater left behind: every unit
+// installed, host.env as given, and neither live sandbox directory.
+func oldSandboxBox(t *testing.T, hostEnv string) (etc, opt string, dirs map[string]os.FileMode) {
+ t.Helper()
+ root := t.TempDir()
+ etc, opt = filepath.Join(root, "etc"), filepath.Join(root, "opt/carlos")
+ unitDir := filepath.Join(etc, "systemd/system")
+ for _, dir := range []string{unitDir, filepath.Join(etc, "carlos")} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(etc, "carlos/host.env"), []byte(hostEnv), 0600); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range systemUnitFiles {
+ raw, err := unitsFS.ReadFile("units/" + name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(unitDir, name), raw, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ dirs = map[string]os.FileMode{filepath.Join(root, "var/lib/carlos/oci-rootfs"): 0700, filepath.Join(opt, "runsc"): 0755}
+ for path := range dirs {
+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("not an old box: %s: %v", path, err)
+ }
+ }
+ return etc, opt, dirs
+}
+
+func armedUnitsProbe(args ...string) (string, error) {
+ if len(args) > 1 && args[1] == dbReadSocketUnit {
+ if args[0] == "is-active" {
+ return "inactive", systemctlExit(3)
+ }
+ return "disabled", systemctlExit(1)
+ }
+ switch args[0] {
+ case "is-active":
+ return "active", nil
+ case "is-enabled":
+ return "enabled", nil
+ }
+ return "", nil
+}
+
+// The first pass of the new build creates both directories even when it
+// ends early: the old update's apply still holds the lock (a stage request
+// during its soak), host.env cannot be parsed, or systemctl says nothing.
+func TestSandboxUpdateDirectoriesBeforeEveryEarlyReturn(t *testing.T) {
+ for _, tc := range []struct {
+ name, hostEnv string
+ locked bool
+ probe func(...string) (string, error)
+ }{
+ {name: "apply holds the lock", hostEnv: "CARLOS_EXEC_SANDBOX=systemd\n", locked: true, probe: armedUnitsProbe},
+ {name: "demo host.env unparseable", hostEnv: "CARLOS_DEMO_BOX=1\nCARLOS_DEMO_ACCOUNT=\"open\n", probe: armedUnitsProbe},
+ {name: "systemctl silent", hostEnv: "", probe: func(...string) (string, error) { return "", errors.New("no systemctl") }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ etc, opt, dirs := oldSandboxBox(t, tc.hostEnv)
+ lockPath := filepath.Join(systemRootDir(opt), systemLockFile)
+ if tc.locked {
+ if err := os.MkdirAll(filepath.Dir(lockPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ held, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer held.Close()
+ if err := flockExclusiveNonblock(held); err != nil {
+ t.Fatal(err)
+ }
+ }
+ call := func(args ...string) (string, error) {
+ t.Errorf("early-return pass ran systemctl %v", args)
+ return "", nil
+ }
+ ensureSystemUnits(etc, lockPath, call, tc.probe, t.Logf)
+ for path, mode := range dirs {
+ st, err := os.Lstat(path)
+ if err != nil || !st.IsDir() || st.Mode().Perm() != mode {
+ t.Fatalf("%s not created %04o: %v %v", path, mode, st, err)
+ }
+ }
+ })
+ }
+}
+
+// A group member's directories still wait for its maintenance permit.
+func TestSandboxUpdateDirectoriesGroupWaitsForPermit(t *testing.T) {
+ etc, opt, dirs := oldSandboxBox(t, "")
+ if err := os.WriteFile(filepath.Join(etc, "carlos/group.json"), []byte("{}"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ call := func(args ...string) (string, error) {
+ t.Errorf("unpermitted group pass ran systemctl %v", args)
+ return "", nil
+ }
+ ensureSystemUnits(etc, filepath.Join(systemRootDir(opt), systemLockFile), call, armedUnitsProbe, t.Logf)
+ for path := range dirs {
+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("group member without a permit created %s: %v", path, err)
+ }
+ }
+}
+
+// instance-control started before oci-rootfs existed sees it read-only:
+// systemd skipped the optional ReadWritePaths= entry. In gVisor mode the
+// first pass restarts it once; with the path mounted, in systemd mode, or
+// with no running service it does nothing.
+func TestSandboxUpdateControlRestartForNewRootfs(t *testing.T) {
+ for _, tc := range []struct {
+ name, mode, pid string
+ mounted, want bool
+ }{
+ {name: "gvisor, started before the directory", mode: "gvisor", pid: "4242", want: true},
+ {name: "gvisor, path mounted", mode: "gvisor", pid: "4242", mounted: true},
+ {name: "gvisor, not running", mode: "gvisor", pid: "0"},
+ {name: "systemd", mode: "systemd", pid: "4242"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ etc, opt, _ := oldSandboxBox(t, "CARLOS_EXEC_SANDBOX="+tc.mode+"\n")
+ rootfs := filepath.Join(filepath.Dir(etc), "var/lib/carlos/oci-rootfs")
+ old := controlMountinfo
+ t.Cleanup(func() { controlMountinfo = old })
+ controlMountinfo = func(pid string) ([]byte, error) {
+ if pid != tc.pid {
+ t.Errorf("mount table of %q, want %q", pid, tc.pid)
+ }
+ table := "22 1 259:1 / / ro,relatime shared:1 - ext4 /dev/root rw\n31 22 259:1 /run/carlos-control /run/carlos-control rw,relatime shared:9 - tmpfs tmpfs rw\n"
+ if tc.mounted {
+ table += "40 22 259:1 " + rootfs + " " + rootfs + " rw,relatime shared:1 - ext4 /dev/root rw\n"
+ }
+ return []byte(table), nil
+ }
+ probe := func(args ...string) (string, error) {
+ if args[0] == "show" {
+ if strings.Join(args, " ") != "show -p MainPID --value "+claimControlUnit {
+ t.Errorf("probe %v", args)
+ }
+ return tc.pid + "\n", nil
+ }
+ return armedUnitsProbe(args...)
+ }
+ var calls []string
+ call := func(args ...string) (string, error) {
+ calls = append(calls, strings.Join(args, " "))
+ return "", nil
+ }
+ ensureSystemUnits(etc, filepath.Join(systemRootDir(opt), systemLockFile), call, probe, t.Logf)
+ want := []string(nil)
+ if tc.want {
+ want = []string{"try-restart " + claimControlUnit}
+ }
+ if strings.Join(calls, "|") != strings.Join(want, "|") {
+ t.Fatalf("systemctl calls %q, want %q", calls, want)
+ }
+ })
+ }
+}
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go
index 6f66f584e..1c5ba3d06 100644
--- a/internal/host/systemunits.go
+++ b/internal/host/systemunits.go
@@ -59,7 +59,19 @@ func ensureSystemUnits(etcDir, lockPath string, systemctl, probe func(args ...st
ensureSystemUnitsWithGuard(etcDir, lockPath, systemctl, probe, logf, a)
}
func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(args ...string) (string, error), logf func(string, ...any), a *systemApplier) {
-
+ // The live sandbox directories come first, before the apply lock and
+ // every early return below. The first update from a build without them
+ // (v0.34.33) leaves both absent: its updater installs and restarts the
+ // units but cannot create what it does not know. Any pass of this
+ // build, including one that meets that update's apply still holding the
+ // lock (a stage request during its soak), creates them. They touch no
+ // unit file, so the lock has nothing to protect here. A group member
+ // still waits for its maintenance permit below.
+ var dirsErr error
+ early := !groupMarkerPresent(etcDir)
+ if early {
+ dirsErr = ensureSandboxDirectories(filepath.Dir(etcDir), a.optDir)
+ }
if err := os.MkdirAll(filepath.Dir(lockPath), 0o755); err != nil {
logf("adopt: system units: %v", err)
return
@@ -99,6 +111,9 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
return
}
}
+ if !early {
+ dirsErr = ensureSandboxDirectories(filepath.Dir(etcDir), a.optDir)
+ }
claimSettings, settingsErr := readClaimUnitSettings(filepath.Join(etcDir, "carlos", "host.env"))
if settingsErr != nil {
@@ -160,10 +175,11 @@ func ensureSystemUnitsWithGuard(etcDir, lockPath string, systemctl, probe func(a
logf("adopt: retired units this build no longer ships: %s", strings.Join(retiredUnits, ", "))
}
isEnabled := parseIsEnabled(enabled)
- if err := ensureSandboxDirectories(filepath.Dir(etcDir), a.optDir); err != nil {
- logf("adopt: sandbox directories: %v", err)
+ if dirsErr != nil {
+ logf("adopt: sandbox directories: %v", dirsErr)
return
}
+ refreshControlSandboxRootfs(etcDir, a, systemctl, probe, logf)
missing := false
for _, u := range systemUnitFiles {
if group && groupAutomaticUnit(u) {