Merge origin/main into region-ha-held-build
main 4dfb36d5 (gVisor update keeps instance control running). Census: main's gvisor-update-dirs overlay chains before this branch's, which is re-proposed last; no unit of this branch changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
26 files changed,
+1,810
−17
docs/superpowers/notes/census-proposal-gvisor-update-dirs.md+37 −0docs/superpowers/notes/census-proposal-region-ha-held-build.md+1 −1internal/activator/backend_exec.go+50 −2internal/activator/backend_legacy_test.go+73 −0internal/activator/control.go+12 −0internal/activator/sandbox_spawn_guard_test.go+2 −1internal/demobuild/gvisor_cleanup_test.go+4 −0internal/demobuild/gvisor_never_loaded_test.go+138 −0internal/demobuild/gvisor_test.go+12 −0internal/demobuild/unit.go+39 −1internal/host/claimunit_test.go+1 −1internal/host/execsandboxfloor.go+193 −0internal/host/runsc_update_dirs_linux_test.go+451 −0internal/host/runsc_update_dirs_rootrunner_linux_test.go+557 −0internal/host/runscensure.go+1 −1internal/host/runscensure_test.go+2 −2internal/host/systemapply.go+19 −0internal/host/systemunits.go+19 −3internal/host/units/carlos-instance-control.service+1 −1internal/host/units/carlos-runsc.service+1 −1internal/instancectl/demo_cleanup.go+3 −0internal/instancectl/gvisor_never_loaded_test.go+111 −0internal/instancectl/sandboxstop.go+50 −0internal/provision/testdata/plan14-root-reads-chain.tsv+2 −1internal/provision/testdata/plan14-root-reads-gvisor-update-dirs.tsv+29 −0internal/provision/testdata/plan14-root-reads-region-ha-held-build.tsv+2 −2
CI passed — run details
Intent
Attributed to this commit: 74.0 g CO₂e (9,391,419 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-held-build, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/superpowers/notes/census-proposal-gvisor-update-dirs.md b/docs/superpowers/notes/census-proposal-gvisor-update-dirs.md| new file mode 100644 |
| index 000000000..01ca5dd32 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-gvisor-update-dirs.md |
| @@ -0,0 +1,37 @@ |
| +# Census approval: gvisor-update-dirs |
| + |
| +Ruling `census-ruling-gvisor-update-dirs`. The independent reviewer approves or rejects every change below, 5 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/host/systemunits.go` `ensureSystemUnitsWithGuard` | body | unchanged (5) | Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below. | |
| +| `internal/host/units/carlos-instance-control.service` `external` | body | unchanged (1) | Make the existing /var/lib/carlos/oci-rootfs writable-path entry optional when absent so old updaters can start the new control unit; retain ProtectSystem=strict and the same path and environment. No new root read. | |
| +| `internal/host/units/carlos-runsc.service` `external` | body | unchanged (1) | Make the existing /opt/carlos/runsc writable-path entry optional when absent so systemd-mode installation exits successfully on old boxes; gvisor still refuses absent runtime directories with EXEC-SANDBOX-RUNSC. No new path or root read. | |
| +| `internal/instancectl/demo_cleanup.go` `Server.stopDemoUnits` | body | unchanged (1) | Skip the post-stop ActiveState show for the host's gVisor sibling only when gvisorUnitNeverLoaded proves it never loaded; the slice-level cgroup-empty wait still runs. No new read. | |
| +| `internal/instancectl/sandboxstop.go` `Server.proveRunGone` | body | unchanged (1) | For a carlos-instance-gvisor@ unit only, return proven-gone without naming it to systemctl when gvisorUnitNeverLoaded holds (no cgroup dir, no drop-in dir, not listed by systemd). Every other unit, and any doubt or error, keeps the existing show/cgroup proof unchanged. | |
| +| `internal/activator/backend_exec.go` `ExecBackend.LegacyRunGone` | sites | +whole:Route | Agent side (carlos user): skip the gVisor sibling's show-based proof only when gvisorSiblingNeverLoaded holds; the native unit's proof is unchanged and any doubt keeps the lease as before. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/demobuild`, `internal/host`, `internal/host/units`, `internal/instancectl`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/host/systemunits.go` `ensureSystemUnitsWithGuard`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged. |
| +- `internal/host/units/carlos-instance-control.service` `external`: authority, task B3,C,D,E1,J4. Basis: root-input;kept=B3,C,D,E1;scope=protected-decision-only;rev3=census-ruling-agent-start-demo-3;basis=Correct the runtime-write comment to include escaped demo snapshot .mount units alongside per-generation drop-ins; service directives are unchanged.;rev3=census-ruling-region-ha-graceful-terminate-t1;basis=Region HA T1/DR-4 final fix: retain After=nftables.service without Wants or Requires; add Restart=on-failure and RestartSec=1 so a crashed control restarts before a later edge stop can block socket activation and shutdown proofs; rewrap the header and explain this ordering. Same ExecStart and protections; no new root read, input, path, command or capability.;rev3=census-ruling-gvisor-demos;basis=Add Wants/After installer and narrowly writable rootfs parent. Keep one host.env EnvironmentFile and other hardening. |
| +- `internal/host/units/carlos-runsc.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Root oneshot reads fixed root-owned host.env through its applet and installs compiled runtime set only under /opt/carlos/runsc; no RemainAfterExit. |
| +- `internal/instancectl/demo_cleanup.go` `Server.stopDemoUnits`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Enumerate derived instance units, stop them and prove unit/cgroup emptiness before freeze or purge proceeds. Census read-site delta: +file:ReadDir.;rev3=census-ruling-gvisor-demos;basis=Acquire the existing original-run fence, stop/prove both original families, finish the retained runsc delete hook and remove the gVisor bundle/skeleton/drop-in before freeze or purge may stream data. Discover queued generation jobs as well as loaded units and retained generation files. Existing ReadDir inputs remain derived controller roots. |
| +- `internal/instancectl/sandboxstop.go` `Server.proveRunGone`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Task 5: read only the validated host-derived systemd cgroup.events path under the configured root. Require complete inactive/dead state, zero jobs/MainPID/ControlPID, expected ControlGroup and exact populated 0 or absent cgroup; unreadable or malformed proof refuses cleanup. Fix round 1 C1/I1: accept the captured systemd 257 empty Job field as no queued job, also zero. Do not infer running state from LoadState; keep required-property presence, inactive/failed plus dead/failed, zero MainPID/ControlPID, expected ControlGroup and empty/absent cgroup proof. Native cleanup runs before sibling ID derivation. No new read path. Task 9: Treat omitted empty Job, InvocationID and ControlGroup as their captured systemd 257 unset defaults. Require explicit LoadState, ActiveState, SubState, MainPID and ControlPID; retain no-job, zero-PID, terminal-state, expected-group and empty/absent-cgroup checks. Same fixed derived path and read. |
| +- `internal/activator/backend_exec.go` `ExecBackend.LegacyRunGone`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-292;basis=Census ruling 292: new unit; stops the host's original run unit through instance-control's existing /stop and proves it gone from systemctl show state and cgroup.events, as the exit observer reads. The termination proof only decides release-or-keep, and never starts, wakes or admits anything; unknown or error means keep. Boundary: agent-side shutdown gates running as carlos; they refuse or stop new work once shutdown begins, and a cancelled wake releases its lease; no new read and no root decision; plus the legacy run unit's termination proof (systemctl show state and cgroup.events, as the exit observer reads), and a retried conditional lease delete of the same record.;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=a rootfs row's original run unit is the rootfs template's: it is named by unitNameFor and stopped through stopRole (the rootfs verb), and its cgroup proven by unitEvents, which for a rootfs row also reads the control group systemd reports; the Host sites became Route sites (the route passed to those three); the proof's rule is unchanged: unknown or error keeps the lease; no root decision;rev3=census-ruling-gvisor-demos;basis=Task 5: after root fenced Stop succeeds, check both native and gVisor original siblings using the existing systemd/cgroup readers; rootfs retains its existing path. A failed root proof returns immediately and keeps the lease. No mode-dependent cleanup. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/activator/backend_exec.go:ExecBackend.gvisorSiblingNeverLoaded`: reads +file:Lstat, +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/activator/control.go:systemctlUnitsListed`: reads +file:CommandContext; written legacy, accepted-legacy, frozen |
| +- new `internal/demobuild/unit.go:gvisorBuildNeverLoaded`: reads +file:Lstat; written legacy, accepted-legacy, frozen |
| +- new `internal/host/execsandboxfloor.go:var controlProcess`: reads +file:OpenRoot, +file:ReadFile ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/instancectl/sandboxstop.go:Server.gvisorUnitNeverLoaded`: reads +file:Lstat; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `7ac2bde8301c37c7546e9aa19d375f1468fc8061876a618fa8f93dd4543c5652` → `1f1b2fdb569b7be42e75e10d1943d7e512708299364f912c2f72dccf1bd5b678`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-gvisor-update-dirs.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/census-proposal-region-ha-held-build.md b/docs/superpowers/notes/census-proposal-region-ha-held-build.md| index 162a56123..1b3959f97 100644 |
| --- a/docs/superpowers/notes/census-proposal-region-ha-held-build.md |
| +++ b/docs/superpowers/notes/census-proposal-region-ha-held-build.md |
| @@ -96,6 +96,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - reads `internal/edge/edge.go:Edge.ServeHTTP`: +registry:HA ×2, +registry:Host, +whole:Route ×4; keeps legacy, task accepted-legacy |
| - reads `internal/edge/forwardha.go:Edge.forwardHAAndNote`: -registry:Host ×3, +whole:Route; keeps legacy, task accepted-legacy |
| -Seal: `7ac2bde8301c37c7546e9aa19d375f1468fc8061876a618fa8f93dd4543c5652` → `318d254cf1f1bd33b50bed810332a2d95e89c43b558c5d305d3e64e3d8d9ff9e`. |
| +Seal: `1f1b2fdb569b7be42e75e10d1943d7e512708299364f912c2f72dccf1bd5b678` → `beb085e4c6cdb3d430d12a8dc3c93f25cc3faf1aa7d62be37698ff9c9c82ecce`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-held-build.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 707548179..f6de02f2f 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -239,6 +239,14 @@ type ExecBackend struct { |
| // processes are in the group systemd reports, not under the host |
| // slice. Nil: systemctlControlGroup. |
| ControlGroup ControlGroupOf |
| + // UnitsListed answers `systemctl list-units --all ... <glob>` for the |
| + // legacy proof's gVisor sibling (gvisorSiblingNeverLoaded). Nil: |
| + // systemctlUnitsListed, unless UnitState is a fake, in which case no |
| + // listing is asked and the full proof runs. |
| + UnitsListed UnitsListed |
| + // GVisorDropInDir is where root writes gVisor drop-ins. Empty: |
| + // /run/systemd/system. |
| + GVisorDropInDir string |
| // NestedOK gates a nested wake on the box facts a unit test can't see: |
| // the isolation mounts, the control service's own /ready. Nil: no |
| // gate (every unit test and any box that predates the check). Wired in |
| @@ -3036,8 +3044,8 @@ func (b *ExecBackend) LegacyRunGone(ctx context.Context, rt registry.Route) erro |
| return fmt.Errorf("stop %s: %w", unit, err) |
| } |
| units := []string{unit} |
| - if !rt.Rootfs() { |
| - units = append(units, instancectl.GVisorUnitName(rt.Host)) |
| + if sibling := instancectl.GVisorUnitName(rt.Host); !rt.Rootfs() && !b.gvisorSiblingNeverLoaded(ctx, rt, sibling) { |
| + units = append(units, sibling) |
| } |
| for _, unit := range units { |
| if err := b.waitLegacyRunGone(ctx, rt, unit); err != nil { |
| @@ -3046,6 +3054,46 @@ func (b *ExecBackend) LegacyRunGone(ctx context.Context, rt registry.Route) erro |
| } |
| return nil |
| } |
| + |
| +// gvisorSiblingNeverLoaded proves the gVisor sibling gone without naming it |
| +// to systemd: its template's empty ExecStart= is filled only by a per-start |
| +// drop-in, so a `systemctl show` of a name never started makes systemd load |
| +// it and log "Service has no ExecStart=... Refusing" on every proof of a |
| +// systemd-mode box. Proof: no cgroup, no drop-in directory, and systemd does |
| +// not list the name among the units it holds (asked by family glob, never |
| +// by the escaped name). Any doubt or error is false: the full proof runs. |
| +func (b *ExecBackend) gvisorSiblingNeverLoaded(ctx context.Context, rt registry.Route, unit string) bool { |
| + listed := b.UnitsListed |
| + if listed == nil { |
| + if b.UnitState != nil { |
| + return false |
| + } |
| + listed = systemctlUnitsListed |
| + } |
| + dir := b.GVisorDropInDir |
| + if dir == "" { |
| + dir = "/run/systemd/system" |
| + } |
| + if _, err := os.Lstat(filepath.Join(dir, unit+".d")); !errors.Is(err, os.ErrNotExist) { |
| + return false |
| + } |
| + if exists, _, err := b.unitEvents(ctx, rt, unit); err != nil || exists { |
| + return false |
| + } |
| + out, err := listed(ctx, instancectl.UnitPrefixGVisor+"*.service") |
| + if err != nil { |
| + return false |
| + } |
| + for _, line := range strings.Split(out, "\n") { |
| + for _, f := range strings.Fields(line) { |
| + if f == unit { |
| + return false |
| + } |
| + } |
| + } |
| + return true |
| +} |
| + |
| func (b *ExecBackend) waitLegacyRunGone(ctx context.Context, rt registry.Route, unit string) error { |
| state := b.UnitState |
| if state == nil { |
diff --git a/internal/activator/backend_legacy_test.go b/internal/activator/backend_legacy_test.go| index 24ea99926..3072efa1d 100644 |
| --- a/internal/activator/backend_legacy_test.go |
| +++ b/internal/activator/backend_legacy_test.go |
| @@ -2,6 +2,10 @@ package activator |
| import ( |
| "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| "strings" |
| "sync" |
| "testing" |
| @@ -107,3 +111,72 @@ func TestLegacyRunGoneRefusesWhileTheUnitRuns(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// The legacy proof's gVisor sibling is never named to systemctl on a box |
| +// where systemd does not hold it and it has no cgroup or drop-in: a |
| +// `systemctl show` would load its commandless template and log "Refusing". |
| +// Listed, or with a drop-in, it keeps the full proof. |
| +func TestLegacyRunGoneSkipsAnUnloadedGVisorSibling(t *testing.T) { |
| + t.Parallel() |
| + for _, tc := range []struct { |
| + name string |
| + listed bool |
| + dropIn bool |
| + listErr bool |
| + wantNamed bool |
| + }{ |
| + {name: "unlisted"}, |
| + {name: "listed", listed: true, wantNamed: true}, |
| + {name: "drop-in", dropIn: true, wantNamed: true}, |
| + {name: "listing error", listErr: true, wantNamed: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + unit := &fakeUnit{} |
| + unit.set("inactive", "", false, false) |
| + b, rt := nestedBackend(t, &fakeControl{}, unit) |
| + sibling := instancectl.GVisorUnitName(rt.Host) |
| + b.GVisorDropInDir = t.TempDir() |
| + if tc.dropIn { |
| + if err := os.Mkdir(filepath.Join(b.GVisorDropInDir, sibling+".d"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var globs []string |
| + b.UnitsListed = func(_ context.Context, glob string) (string, error) { |
| + globs = append(globs, glob) |
| + if tc.listErr { |
| + return "", errors.New("bus") |
| + } |
| + if tc.listed { |
| + return sibling + " loaded inactive dead x\n", nil |
| + } |
| + return "", nil |
| + } |
| + var mu sync.Mutex |
| + var asked []string |
| + b.UnitState = func(ctx context.Context, u string) (string, string, error) { |
| + mu.Lock() |
| + asked = append(asked, u) |
| + mu.Unlock() |
| + return unit.state(ctx, u) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| + defer cancel() |
| + if err := b.LegacyRunGone(ctx, rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + named := slices.Contains(asked, sibling) |
| + if named != tc.wantNamed { |
| + t.Fatalf("gVisor sibling asked = %v, want %v (asked %v)", named, tc.wantNamed, asked) |
| + } |
| + if !slices.Contains(asked, instancectl.UnitName(instancectl.RoleRun, rt.Host)) { |
| + t.Fatalf("native run not proven: %v", asked) |
| + } |
| + for _, g := range globs { |
| + if g != instancectl.UnitPrefixGVisor+"*.service" { |
| + t.Fatalf("listing asked %q, not the family glob", g) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/activator/control.go b/internal/activator/control.go| index 1b942185f..a4dc01826 100644 |
| --- a/internal/activator/control.go |
| +++ b/internal/activator/control.go |
| @@ -136,6 +136,18 @@ func systemctlUnitState(ctx context.Context, unit string) (string, string, error |
| return active, inv, nil |
| } |
| +// UnitsListed answers `systemctl list-units --all --plain --no-legend |
| +// --no-pager <glob>`: the units systemd holds in memory, read-only. |
| +type UnitsListed func(ctx context.Context, glob string) (string, error) |
| + |
| +func systemctlUnitsListed(ctx context.Context, glob string) (string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", "list-units", "--all", "--plain", "--no-legend", "--no-pager", glob).Output() |
| + if err != nil { |
| + return "", unitStateError(err) |
| + } |
| + return string(out), nil |
| +} |
| + |
| // UnitMainExit answers `systemctl show -p |
| // InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus <unit>`, which |
| // needs no privilege: how systemd recorded the end of the unit's main |
diff --git a/internal/activator/sandbox_spawn_guard_test.go b/internal/activator/sandbox_spawn_guard_test.go| index 90d2aaae2..9ef33fbba 100644 |
| --- a/internal/activator/sandbox_spawn_guard_test.go |
| +++ b/internal/activator/sandbox_spawn_guard_test.go |
| @@ -96,7 +96,7 @@ func sandboxSystemctlViolations(file *ast.File) []string { |
| verb, constant := call.Args[arg+1].(*ast.BasicLit) |
| if constant { |
| switch verb.Value { |
| - case `"show"`, `"stop"`, `"reset-failed"`, `"daemon-reload"`: |
| + case `"show"`, `"stop"`, `"reset-failed"`, `"daemon-reload"`, `"list-units"`: |
| return true |
| } |
| } |
| @@ -131,6 +131,7 @@ var sandboxSpawnInventory = map[string]int{ |
| "control.go:systemctlControlGroup:Output": 1, |
| "control.go:systemctlUnitMainExit:Output": 1, |
| "control.go:systemctlUnitState:Output": 1, |
| + "control.go:systemctlUnitsListed:Output": 1, |
| "genbackend.go:StartStaged:spawnChildFrom": 2, |
| "genbackend.go:StartStaged:spawnUnitFrom": 1, |
| "genservice.go:startGen:Start": 1, |
diff --git a/internal/demobuild/gvisor_cleanup_test.go b/internal/demobuild/gvisor_cleanup_test.go| index 6e28f1d30..ba8d12fa6 100644 |
| --- a/internal/demobuild/gvisor_cleanup_test.go |
| +++ b/internal/demobuild/gvisor_cleanup_test.go |
| @@ -67,6 +67,10 @@ func TestGVisorBuildExitDiagnosticsOnly(t *testing.T) { |
| } |
| ctl := systemctl |
| systemctl = func(ctx context.Context, args ...string) (string, error) { |
| + if args[0] == "list-units" && fault == "termination" { |
| + // A unit with a main process is loaded. |
| + return "carlos-demo-build-gvisor@test.service loaded active running x\n", nil |
| + } |
| out, err := ctl(ctx, args...) |
| if fault == "termination" { |
| out = strings.ReplaceAll(out, "MainPID=0", "MainPID=12") |
diff --git a/internal/demobuild/gvisor_never_loaded_test.go b/internal/demobuild/gvisor_never_loaded_test.go| new file mode 100644 |
| index 000000000..018b2bc01 |
| --- /dev/null |
| +++ b/internal/demobuild/gvisor_never_loaded_test.go |
| @@ -0,0 +1,138 @@ |
| +package demobuild |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| +) |
| + |
| +// cleanUnit stops both build families. On a systemd-mode box the gVisor |
| +// build unit was never started, and naming it to systemctl makes systemd |
| +// load its commandless template and log "Refusing". Unlisted, with no |
| +// cgroup and no job drop-in, it is proven gone without its name. |
| +func TestGVisorBuildNeverLoadedIsNotNamed(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + listing string |
| + listErr error |
| + cgroup bool |
| + dropIn bool |
| + wantNamed bool |
| + }{ |
| + {name: "unlisted", listing: "carlos-demo-build-gvisor@ff_1.service loaded inactive dead x\n"}, |
| + {name: "listed", listing: "LISTED loaded active running x\n", wantNamed: true}, |
| + {name: "cgroup present", cgroup: true, wantNamed: true}, |
| + {name: "drop-in present", dropIn: true, wantNamed: true}, |
| + {name: "listing error", listErr: errors.New("bus"), wantNamed: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fakeUnitController(t) |
| + w, j, _, _ := workerFixture(t) |
| + dir := filepath.Join(w.root, j.ID, "1") |
| + if err := os.MkdirAll(dir+"/work", 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + native, err := layoutFor(w.root, dir, execsandbox.FamilySystemd) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + gvisor, err := layoutFor(w.root, dir, execsandbox.FamilyGVisor) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if tc.cgroup { |
| + if err := os.Mkdir(filepath.Join(buildCgroupRoot, gvisor.unit), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(buildCgroupRoot, gvisor.unit, "cgroup.events"), []byte("populated 0\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if tc.dropIn { |
| + if err := os.Mkdir(filepath.Join(unitRoot, gvisor.unit+".d"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var calls []string |
| + w.removeSandbox = func(string) error { return nil } |
| + systemctl = func(_ context.Context, args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + switch args[0] { |
| + case "list-units": |
| + return strings.ReplaceAll(tc.listing, "LISTED", gvisor.unit), tc.listErr |
| + case "show": |
| + return "LoadState=not-found\nActiveState=inactive\nMainPID=0\nControlPID=0\nSubState=dead\nJob=\n", nil |
| + } |
| + return "", nil |
| + } |
| + if err := w.cleanUnit(context.Background(), native); err != nil { |
| + t.Fatal(err) |
| + } |
| + named := false |
| + for _, c := range calls { |
| + if strings.HasPrefix(c, "list-units") { |
| + if !strings.HasSuffix(c, " carlos-demo-build-gvisor@*.service") { |
| + t.Fatalf("listing must ask the family glob: %q", c) |
| + } |
| + continue |
| + } |
| + if strings.Contains(c, gvisor.unit) { |
| + named = true |
| + } |
| + } |
| + if named != tc.wantNamed { |
| + t.Fatalf("gVisor build name passed to systemctl = %v, want %v\n%s", named, tc.wantNamed, strings.Join(calls, "\n")) |
| + } |
| + if !strings.Contains(strings.Join(calls, "\n"), "show "+native.unit) { |
| + t.Fatalf("native build not proven:\n%s", strings.Join(calls, "\n")) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// R1 P2-3: the wrapper keeps only systemctlCaptureLimit bytes of output and |
| +// reports success. A listing cut there is not an inventory: the target may |
| +// sit past the cut, so the full proof runs. |
| +func TestGVisorBuildTruncatedListingKeepsTheProof(t *testing.T) { |
| + fakeUnitController(t) |
| + w, j, _, _ := workerFixture(t) |
| + dir := filepath.Join(w.root, j.ID, "1") |
| + if err := os.MkdirAll(dir+"/work", 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + gvisor, err := layoutFor(w.root, dir, execsandbox.FamilyGVisor) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var full strings.Builder |
| + for i := 0; full.Len() <= systemctlCaptureLimit; i++ { |
| + fmt.Fprintf(&full, "carlos-demo-build-gvisor@%064x_%d.service loaded inactive dead carlos gVisor offline demo build\n", i, i) |
| + } |
| + full.WriteString(gvisor.unit + " loaded active running carlos gVisor offline demo build\n") |
| + var calls []string |
| + systemctl = func(_ context.Context, args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + if args[0] == "list-units" { |
| + var captured limitedLog // what the production wrapper keeps |
| + captured.Write([]byte(full.String())) |
| + if strings.Contains(string(captured.b), gvisor.unit) { |
| + t.Fatal("fixture: target inside the captured part") |
| + } |
| + return string(captured.b), nil |
| + } |
| + return "LoadState=not-found\nActiveState=inactive\nMainPID=0\nControlPID=0\nSubState=dead\nJob=\n", nil |
| + } |
| + if err := stopBuildContext(context.Background(), gvisor); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.ContainsFunc(calls, func(c string) bool { return strings.HasPrefix(c, "show "+gvisor.unit) }) { |
| + t.Fatalf("truncated listing taken as absence:\n%s", strings.Join(calls, "\n")) |
| + } |
| +} |
diff --git a/internal/demobuild/gvisor_test.go b/internal/demobuild/gvisor_test.go| index 5cabec1a3..1376e99bc 100644 |
| --- a/internal/demobuild/gvisor_test.go |
| +++ b/internal/demobuild/gvisor_test.go |
| @@ -159,7 +159,15 @@ func TestGVisorBuildRecoveryBothFamilies(t *testing.T) { |
| removed = true |
| return nil |
| } |
| + gvisor, lerr := layoutFor(w.root, dir, execsandbox.FamilyGVisor) |
| + if lerr != nil { |
| + t.Fatal(lerr) |
| + } |
| systemctl = func(_ context.Context, args ...string) (string, error) { |
| + if args[0] == "list-units" { |
| + // Running, or holding a queued stop job: loaded either way. |
| + return gvisor.unit + " loaded active running x\n", nil |
| + } |
| if args[0] == "stop" && strings.HasSuffix(args[len(args)-1], ".service") { |
| stops[args[len(args)-1]] = true |
| } |
| @@ -349,6 +357,10 @@ func TestGVisorBuildStopProof(t *testing.T) { |
| if args[0] == "kill" { |
| t.Fatal("extra kill could terminate runtime deletion") |
| } |
| + if args[0] == "list-units" { |
| + // A unit with a job or a process is loaded. |
| + return l.unit + " loaded active running x\n", nil |
| + } |
| out, err := ctl(ctx, args...) |
| if fault == "missing-job" { |
| out = strings.ReplaceAll(out, "Job=\n", "") |
diff --git a/internal/demobuild/unit.go b/internal/demobuild/unit.go| index 250c34dab..55705913a 100644 |
| --- a/internal/demobuild/unit.go |
| +++ b/internal/demobuild/unit.go |
| @@ -88,11 +88,15 @@ var systemctl = func(ctx context.Context, args ...string) (string, error) { |
| return string(b.b), err |
| } |
| +// systemctlCaptureLimit caps what the systemctl wrapper keeps of its |
| +// output. Output of exactly this length may have been cut short. |
| +const systemctlCaptureLimit = 128 * 1024 |
| + |
| type limitedLog struct{ b []byte } |
| func (b *limitedLog) Write(p []byte) (int, error) { |
| n := len(p) |
| - if room := 128*1024 - len(b.b); room > 0 { |
| + if room := systemctlCaptureLimit - len(b.b); room > 0 { |
| b.b = append(b.b, p[:min(room, len(p))]...) |
| } |
| return n, nil |
| @@ -343,6 +347,9 @@ func stopBuild(l buildLayout) error { |
| } |
| func stopBuildContext(ctx context.Context, l buildLayout) error { |
| + if l.family == execsandbox.FamilyGVisor && gvisorBuildNeverLoaded(ctx, l.unit) { |
| + return nil |
| + } |
| out, err := systemctl(ctx, "show", l.unit, "-p", "ActiveState,SubState,MainPID,ControlPID,LoadState,Job") |
| if err != nil { |
| return fmt.Errorf("show %s: %w: %s", l.unit, err, out) |
| @@ -381,6 +388,37 @@ func stopBuildContext(ctx context.Context, l buildLayout) error { |
| } |
| } |
| +// gvisorBuildNeverLoaded proves a carlos-demo-build-gvisor@ unit gone without |
| +// naming it to systemd: its template's empty ExecStart= is filled only by the |
| +// job drop-in, so a show or stop of a name never started makes systemd load |
| +// it and log "Service has no ExecStart=... Refusing" (cleanUnit stops both |
| +// families, so every build on a systemd-mode box did). The proof: no cgroup |
| +// directory (the path emptyBuildCgroup reads), no job drop-in directory, and |
| +// no listing among the units systemd holds, asked by family glob rather than |
| +// by name. Any error, or a listing that may be truncated, is false and the |
| +// full proof runs. |
| +func gvisorBuildNeverLoaded(ctx context.Context, unit string) bool { |
| + for _, path := range []string{filepath.Join(buildCgroupRoot, unit), filepath.Join(unitRoot, unit+".d")} { |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + return false |
| + } |
| + } |
| + out, err := systemctl(ctx, "list-units", "--all", "--plain", "--no-legend", "--no-pager", "carlos-demo-build-gvisor@*.service") |
| + // Absence needs the whole inventory: a listing the capture may have cut |
| + // at its limit keeps the full proof. |
| + if err != nil || len(out) >= systemctlCaptureLimit { |
| + return false |
| + } |
| + for _, line := range strings.Split(out, "\n") { |
| + for _, f := range strings.Fields(line) { |
| + if f == unit { |
| + return false |
| + } |
| + } |
| + } |
| + return true |
| +} |
| + |
| func buildInactive(m map[string]string) bool { |
| job := m["Job"] |
| return (job == "" || job == "0") && (m["ActiveState"] == "inactive" || m["ActiveState"] == "failed") && (m["SubState"] == "dead" || m["SubState"] == "failed") && m["MainPID"] == "0" && m["ControlPID"] == "0" |
diff --git a/internal/host/claimunit_test.go b/internal/host/claimunit_test.go| index 12faff98f..9015c23d4 100644 |
| --- a/internal/host/claimunit_test.go |
| +++ b/internal/host/claimunit_test.go |
| @@ -81,7 +81,7 @@ func TestClaimControlUnitInstallers(t *testing.T) { |
| "EnvironmentFile": {"-/etc/carlos/host.env"}, |
| "StateDirectory": {"carlos-claims"}, |
| "StateDirectoryMode": {"0700"}, |
| - "ReadWritePaths": {"/run/carlos-control /run/carlos /var/lib/carlos-claims /var/lib/carlos-release/private /run/systemd/system /data /opt/carlos /etc/systemd/system /sys/fs/cgroup", "/var/lib/carlos/oci-rootfs"}, |
| + "ReadWritePaths": {"/run/carlos-control /run/carlos /var/lib/carlos-claims /var/lib/carlos-release/private /run/systemd/system /data /opt/carlos /etc/systemd/system /sys/fs/cgroup", "-/var/lib/carlos/oci-rootfs"}, |
| "RestrictAddressFamilies": {"AF_UNIX AF_INET AF_INET6"}, |
| "ProtectSystem": {"strict"}, |
| "ProtectHome": {"yes"}, |
diff --git a/internal/host/execsandboxfloor.go b/internal/host/execsandboxfloor.go| index 6a41b1ef1..f9168e1c2 100644 |
| --- a/internal/host/execsandboxfloor.go |
| +++ b/internal/host/execsandboxfloor.go |
| @@ -9,6 +9,8 @@ import ( |
| "log" |
| "os" |
| "path/filepath" |
| + "slices" |
| + "strings" |
| "github.com/carlosframework/platform/internal/execsandbox" |
| ) |
| @@ -131,6 +133,197 @@ func ensureSandboxDirectories(root, optDir string) error { |
| return bootstrapMakeDir(filepath.Join(optDir, "runsc"), 0755) |
| } |
| +// controlProcess reads one process instance's cgroup and mount table |
| +// through a single /proc/<pid> directory descriptor: both files come from |
| +// the process that descriptor was opened on, and if it has exited the |
| +// reads fail (ESRCH) even when the PID has been reused since. A seam for |
| +// tests. |
| +var controlProcess = func(pid string) (cgroup, mountinfo []byte, err error) { |
| + dir, err := os.OpenRoot(filepath.Join("/proc", pid)) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + defer dir.Close() |
| + if cgroup, err = dir.ReadFile("cgroup"); err != nil { |
| + return nil, nil, err |
| + } |
| + if mountinfo, err = dir.ReadFile("mountinfo"); err != nil { |
| + return nil, nil, err |
| + } |
| + return cgroup, mountinfo, nil |
| +} |
| + |
| +// controlInvocation is what systemd says runs a unit now. |
| +type controlInvocation struct{ pid, invocation, group string } |
| + |
| +// readControlInvocation asks systemd for unit's MainPID, InvocationID and |
| +// ControlGroup. Any error, a stopped service, or a value out of shape is |
| +// not an answer. |
| +func readControlInvocation(probe func(args ...string) (string, error), unit string) (controlInvocation, bool) { |
| + out, err := probe("show", "-p", "MainPID,InvocationID,ControlGroup", unit) |
| + if err != nil { |
| + return controlInvocation{}, false |
| + } |
| + var c controlInvocation |
| + seen := map[string]bool{} |
| + for _, line := range strings.Split(out, "\n") { |
| + k, v, ok := strings.Cut(strings.TrimSpace(line), "=") |
| + if !ok { |
| + continue |
| + } |
| + if seen[k] { |
| + return controlInvocation{}, false |
| + } |
| + seen[k] = true |
| + switch k { |
| + case "MainPID": |
| + c.pid = v |
| + case "InvocationID": |
| + c.invocation = v |
| + case "ControlGroup": |
| + c.group = v |
| + } |
| + } |
| + if c.pid == "" || c.pid == "0" || strings.Trim(c.pid, "0123456789") != "" || c.invocation == "" || |
| + !strings.HasPrefix(c.group, "/") || !strings.HasSuffix(c.group, "/"+unit) { |
| + return controlInvocation{}, false |
| + } |
| + return c, true |
| +} |
| + |
| +// 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. |
| +// |
| +// The mount table read must be the service's own (census R1 P1): a PID |
| +// read from systemd can be reused by any process, an agent child under |
| +// carlos-edge's read-only namespace among them. So the observation is |
| +// bound to one invocation: MainPID, InvocationID and ControlGroup from |
| +// systemd; cgroup and mountinfo through one /proc/<pid> descriptor, the |
| +// cgroup exactly the unit's; then the same three again, unchanged. Any |
| +// error, mismatch or exited process is unknown, and unknown never |
| +// restarts. systemd mode never writes the directory and is left alone. |
| +func refreshControlSandboxRootfs(etcDir string, a *systemApplier, systemctl, probe func(args ...string) (string, error), logf func(string, ...any)) { |
| + refreshControlSandboxRootfsUnit(etcDir, claimControlUnit, a, systemctl, probe, logf) |
| +} |
| + |
| +func refreshControlSandboxRootfsUnit(etcDir, unit 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 |
| + } |
| + before, ok := readControlInvocation(probe, unit) |
| + if !ok { |
| + return |
| + } |
| + cgroup, raw, err := controlProcess(before.pid) |
| + if err != nil { |
| + logf("adopt: %s process %s: %v; leaving it", unit, before.pid, err) |
| + return |
| + } |
| + if strings.TrimSpace(string(cgroup)) != "0::"+before.group { |
| + logf("adopt: process %s is not %s's (cgroup %q); leaving it", before.pid, unit, strings.TrimSpace(string(cgroup))) |
| + return |
| + } |
| + if after, ok := readControlInvocation(probe, unit); !ok || after != before { |
| + logf("adopt: %s changed while its mount table was read; leaving it", unit) |
| + return |
| + } |
| + rootfs := filepath.Join(filepath.Dir(etcDir), "var/lib/carlos/oci-rootfs") |
| + writable, known := mountWritable(raw, rootfs) |
| + if !known { |
| + logf("adopt: %s mount table does not settle whether %s is writable; leaving it", unit, rootfs) |
| + return |
| + } |
| + if writable { |
| + return |
| + } |
| + logf("adopt: %s started before %s existed; restarting it so gVisor can write there", unit, rootfs) |
| + if _, err := systemctl("try-restart", unit); err != nil { |
| + logf("adopt: systemctl try-restart %s: %v", unit, err) |
| + } |
| +} |
| + |
| +// mountWritable judges path from the mount that contains it in a |
| +// /proc/<pid>/mountinfo table: the entry with the longest mount point that |
| +// is path or one of its parents, later entries winning ties (they are |
| +// mounted over earlier ones). Its per-mount options say rw or ro. A |
| +// writable parent with no mount point of the path's own is healthy: |
| +// systemd drops a ReadWritePaths= entry a writable parent already covers. |
| +// Any malformed line, or no containing mount, is unknown. |
| +func mountWritable(table []byte, path string) (writable, known bool) { |
| + best := -1 |
| + for _, line := range strings.Split(string(table), "\n") { |
| + if strings.TrimSpace(line) == "" { |
| + continue |
| + } |
| + f := strings.Fields(line) |
| + sep := slices.Index(f, "-") |
| + if len(f) < 10 || sep < 6 || len(f) < sep+4 { |
| + return false, false |
| + } |
| + point, ok := unescapeMountinfo(f[4]) |
| + if !ok || !strings.HasPrefix(point, "/") { |
| + return false, false |
| + } |
| + if point != "/" && point != path && !strings.HasPrefix(path, point+"/") { |
| + continue |
| + } |
| + if len(point) < best { |
| + continue |
| + } |
| + best = len(point) |
| + writable, known = false, false |
| + for _, opt := range strings.Split(f[5], ",") { |
| + switch opt { |
| + case "rw": |
| + writable, known = true, true |
| + case "ro": |
| + writable, known = false, true |
| + } |
| + } |
| + } |
| + return writable, known |
| +} |
| + |
| +// unescapeMountinfo undoes the kernel's \ooo octal escapes (space, tab, |
| +// newline, backslash) in a mountinfo path field. |
| +func unescapeMountinfo(s string) (string, bool) { |
| + var b strings.Builder |
| + for i := 0; i < len(s); i++ { |
| + if s[i] != '\\' { |
| + b.WriteByte(s[i]) |
| + continue |
| + } |
| + if i+4 > len(s) { |
| + return "", false |
| + } |
| + v := 0 |
| + for _, c := range s[i+1 : i+4] { |
| + if c < '0' || c > '7' { |
| + return "", false |
| + } |
| + v = v*8 + int(c-'0') |
| + } |
| + b.WriteByte(byte(v)) |
| + i += 3 |
| + } |
| + return b.String(), true |
| +} |
| + |
| // 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| new file mode 100644 |
| index 000000000..1184569e3 |
| --- /dev/null |
| +++ b/internal/host/runsc_update_dirs_linux_test.go |
| @@ -0,0 +1,451 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| +) |
| + |
| +func TestSandboxUpdateUnitsWithMissingDirectories(t *testing.T) { |
| + root := t.TempDir() |
| + for _, cfg := range []claimUnitSettings{{}, {enabled: true, data: "/data", opt: "/opt/carlos"}, {demo: demo.Config{Account: "demo", Fleet: "dev", Domain: "demo.example"}}, {demo: demo.Config{Account: "demo", Fleet: "dev", Domain: "demo.example", BuildWorker: true}}} { |
| + for name, path := range map[string]string{claimControlUnit: "/var/lib/carlos/oci-rootfs", "carlos-runsc.service": "/opt/carlos/runsc"} { |
| + raw, err := unitsFS.ReadFile("units/" + name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + installed := claimUnitContent(name, raw, cfg) |
| + target := filepath.Join(root, "etc/systemd/system", name) |
| + if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := writeFileDurable(target, installed, 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := os.ReadFile(target) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.Contains(string(got), "ReadWritePaths=-"+path+"\n") || strings.Contains(string(got), "ReadWritePaths="+path+"\n") { |
| + t.Errorf("%s requires missing directory %s", name, path) |
| + } |
| + if _, err := os.Lstat(filepath.Join(root, path)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("old updater created %s: %v", path, err) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestSandboxUpdateAdoptCreatesDirectories(t *testing.T) { |
| + for _, mode := range []string{"systemd", "gvisor"} { |
| + t.Run(mode, func(t *testing.T) { |
| + 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("CARLOS_EXEC_SANDBOX="+mode+"\n"), 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) |
| + } |
| + } |
| + paths := map[string]os.FileMode{filepath.Join(root, "var/lib/carlos/oci-rootfs"): 0700, filepath.Join(opt, "runsc"): 0755} |
| + for path := range paths { |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("not an old box: %s: %v", path, err) |
| + } |
| + } |
| + probe := func(args ...string) (string, error) { |
| + if args[1] == dbReadSocketUnit { |
| + if args[0] == "is-active" { |
| + return "inactive", systemctlExit(3) |
| + } |
| + return "disabled", systemctlExit(1) |
| + } |
| + if args[0] == "is-active" { |
| + return "active", nil |
| + } |
| + return "enabled", nil |
| + } |
| + call := func(args ...string) (string, error) { |
| + t.Errorf("already armed box changed units: %v", args) |
| + return "", nil |
| + } |
| + ensureSystemUnits(etc, filepath.Join(systemRootDir(opt), systemLockFile), call, probe, t.Logf) |
| + for path, mode := range paths { |
| + st, err := os.Lstat(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + stat := st.Sys().(*syscall.Stat_t) |
| + if !st.IsDir() || st.Mode().Perm() != mode || stat.Uid != uint32(os.Geteuid()) || stat.Gid != uint32(os.Getegid()) { |
| + t.Fatalf("%s: mode=%v uid=%d gid=%d", path, st.Mode(), stat.Uid, stat.Gid) |
| + } |
| + t.Logf("%s mode=%04o uid=%d gid=%d", path, st.Mode().Perm(), stat.Uid, stat.Gid) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRunscEnsureMissingDirectory(t *testing.T) { |
| + const root = "/opt/carlos/runsc" |
| + if _, err := os.Lstat(root); !errors.Is(err, os.ErrNotExist) { |
| + t.Skipf("requires absent %s: %v", root, err) |
| + } |
| + for _, mode := range []string{"systemd", "gvisor"} { |
| + t.Run(mode, func(t *testing.T) { |
| + getenv := func(k string) string { |
| + if k == "CARLOS_EXEC_SANDBOX" { |
| + return mode |
| + } |
| + return "" |
| + } |
| + err := ensureRunsc(context.Background(), getenv, nil, func(context.Context, ...string) (string, error) { |
| + t.Error("missing runtime reached systemctl") |
| + return "", nil |
| + }) |
| + if mode == "systemd" { |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } else if !errors.Is(err, execsandbox.ErrRunsc) || !strings.Contains(err.Error(), root) { |
| + t.Fatalf("want EXEC-SANDBOX-RUNSC with directory, got %v", err) |
| + } |
| + if _, err := os.Lstat(root); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("created runtime directory: %v", err) |
| + } |
| + }) |
| + } |
| + r := &runscReadiness{next: time.Now().Add(time.Hour)} |
| + for range 2 { |
| + if err := r.check(context.Background()); !errors.Is(err, execsandbox.ErrRunsc) { |
| + t.Fatalf("Ready accepted missing runtime: %v", err) |
| + } |
| + } |
| +} |
| + |
| +// 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 |
| + parent, garbled bool |
| + // Census R1 P1: the observation is bound to one control invocation. |
| + exited, wrongCgroup, newInvocation, probeErr bool |
| + }{ |
| + {name: "gvisor, started before the directory", mode: "gvisor", pid: "4242", want: true}, |
| + {name: "gvisor, path mounted", mode: "gvisor", pid: "4242", mounted: true}, |
| + // R1 P2-2: a writable parent covers the path with no mount of its own. |
| + {name: "gvisor, writable parent", mode: "gvisor", pid: "4242", parent: true}, |
| + {name: "gvisor, malformed table", mode: "gvisor", pid: "4242", garbled: true}, |
| + {name: "gvisor, not running", mode: "gvisor", pid: "0"}, |
| + {name: "gvisor, PID gone or replaced before the read", mode: "gvisor", pid: "4242", exited: true}, |
| + {name: "gvisor, PID belongs to another cgroup", mode: "gvisor", pid: "4242", wrongCgroup: true}, |
| + {name: "gvisor, invocation changed during the read", mode: "gvisor", pid: "4242", newInvocation: true}, |
| + {name: "gvisor, show fails", mode: "gvisor", pid: "4242", probeErr: true}, |
| + {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") |
| + group := "/system.slice/" + claimControlUnit |
| + old := controlProcess |
| + t.Cleanup(func() { controlProcess = old }) |
| + controlProcess = func(pid string) ([]byte, []byte, error) { |
| + if pid != tc.pid { |
| + t.Errorf("process %q, want %q", pid, tc.pid) |
| + } |
| + if tc.exited { |
| + // The descriptor's process is gone: what ESRCH looks like. |
| + return nil, nil, syscall.ESRCH |
| + } |
| + cgroup := "0::" + group + "\n" |
| + if tc.wrongCgroup { |
| + // A recycled PID: an agent child in carlos-edge's namespace. |
| + cgroup = "0::/carlos.slice/carlos-edge.service\n" |
| + } |
| + 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" |
| + } |
| + if tc.parent { |
| + parent := filepath.Dir(rootfs) |
| + table += "41 22 259:1 " + parent + " " + parent + " rw,relatime shared:1 - ext4 /dev/root rw\n" |
| + } |
| + if tc.garbled { |
| + table += "42 22 259:1 " + rootfs + "\n" |
| + } |
| + return []byte(cgroup), []byte(table), nil |
| + } |
| + shows := 0 |
| + probe := func(args ...string) (string, error) { |
| + if args[0] == "show" { |
| + if strings.Join(args, " ") != "show -p MainPID,InvocationID,ControlGroup "+claimControlUnit { |
| + t.Errorf("probe %v", args) |
| + } |
| + if tc.probeErr { |
| + return "MainPID=" + tc.pid + "\nInvocationID=aa\nControlGroup=" + group + "\n", errors.New("bus") |
| + } |
| + shows++ |
| + inv := "aa" |
| + if tc.newInvocation && shows%2 == 0 { |
| + inv = "bb" |
| + } |
| + return "MainPID=" + tc.pid + "\nInvocationID=" + inv + "\nControlGroup=" + group + "\n", nil |
| + } |
| + return armedUnitsProbe(args...) |
| + } |
| + var calls []string |
| + call := func(args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + return "", nil |
| + } |
| + // Repeated passes: a healthy namespace is never restarted, and an |
| + // unhealthy one is asked to restart on each pass it stays unhealthy. |
| + ensureSystemUnits(etc, filepath.Join(systemRootDir(opt), systemLockFile), call, probe, t.Logf) |
| + if !tc.want { |
| + 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) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// R1 P2-1: the new build's first pass may be an apply that installs |
| +// nothing (a no-op request, or the build already on disk). It too creates |
| +// both live directories; a group member without a permit does not. |
| +func TestSandboxUpdateApplyWithoutInstallCreatesDirectories(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + noOp bool |
| + group bool |
| + }{ |
| + {name: "same version"}, |
| + {name: "no-op request", noOp: true}, |
| + {name: "group without permit", group: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + f := newApplyFixture(t, "stable", "v2") |
| + f.promote("v2", []byte("#!/bin/sh\necho carlos v2\n"), tc.noOp) |
| + f.answer["version:"+systemBinaryPath(f.a.optDir)] = "carlos v2\n" |
| + if tc.group { |
| + if err := os.MkdirAll(filepath.Join(f.a.etcDir, "carlos"), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(f.a.etcDir, "carlos/group.json"), []byte("{}"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + dirs := map[string]os.FileMode{filepath.Join(filepath.Dir(f.a.etcDir), "var/lib/carlos/oci-rootfs"): 0700, filepath.Join(f.a.optDir, "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) |
| + } |
| + } |
| + err := f.a.Run(context.Background(), false) |
| + t.Logf("run: %v; result %+v", err, f.result()) |
| + if !tc.group { |
| + if r := f.result(); r == nil || r.Outcome != systemOutcomeNoted { |
| + t.Fatalf("result = %+v", r) |
| + } |
| + } |
| + for path, mode := range dirs { |
| + st, err := os.Lstat(path) |
| + if tc.group { |
| + if !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("group member without a permit created %s: %v", path, err) |
| + } |
| + continue |
| + } |
| + if err != nil || !st.IsDir() || st.Mode().Perm() != mode { |
| + t.Fatalf("%s not created %04o: %v %v", path, mode, st, err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestMountWritableJudgesTheContainingMount(t *testing.T) { |
| + const path = "/var/lib/carlos/oci-rootfs" |
| + root := "22 1 259:1 / / ro,relatime shared:1 - ext4 /dev/root rw\n" |
| + for _, tc := range []struct { |
| + name, table string |
| + writable, known bool |
| + }{ |
| + {"read-only root only", root, false, true}, |
| + {"exact rw mount", root + "40 22 259:1 /var/lib/carlos/oci-rootfs /var/lib/carlos/oci-rootfs rw,relatime - ext4 /dev/root rw\n", true, true}, |
| + {"rw parent", root + "41 22 259:1 /var/lib/carlos /var/lib/carlos rw,nosuid - ext4 /dev/root rw\n", true, true}, |
| + {"rw parent, ro child over it", root + "41 22 259:1 /var/lib/carlos /var/lib/carlos rw - ext4 /dev/root rw\n43 41 259:1 /var/lib/carlos/oci-rootfs /var/lib/carlos/oci-rootfs ro - ext4 /dev/root rw\n", false, true}, |
| + {"later mount over the same point wins", root + "40 22 259:1 / /var/lib/carlos/oci-rootfs rw - ext4 /dev/root rw\n44 40 259:1 / /var/lib/carlos/oci-rootfs ro - ext4 /dev/root rw\n", false, true}, |
| + {"sibling prefix is not a parent", root + "45 22 259:1 /var/lib/carlos-app /var/lib/carlos-app rw - ext4 /dev/root rw\n", false, true}, |
| + {"escaped mount point", root + "46 22 259:1 /x /var/lib/carlos\\040x rw - ext4 /dev/root rw\n", false, true}, |
| + {"truncated line", root + "47 22 259:1 /var/lib/carlos\n", false, false}, |
| + {"no separator", "22 1 259:1 / / rw,relatime shared:1 x ext4 /dev/root rw\n", false, false}, |
| + {"bad escape", root + "48 22 259:1 / /var/\\9zz rw - ext4 /dev/root rw\n", false, false}, |
| + {"empty", "", false, false}, |
| + {"no rw or ro option", "22 1 259:1 / / relatime - ext4 /dev/root rw\n", false, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + w, k := mountWritable([]byte(tc.table), path) |
| + if w != tc.writable || k != tc.known { |
| + t.Fatalf("mountWritable = %v, %v; want %v, %v", w, k, tc.writable, tc.known) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The production seam reads both files of one live process, and refuses a |
| +// process that has gone (census R1 P1). |
| +func TestControlProcessReadsOneLiveProcess(t *testing.T) { |
| + cgroup, mountinfo, err := controlProcess(strconv.Itoa(os.Getpid())) |
| + if err != nil || !strings.HasPrefix(string(cgroup), "0::") || !strings.Contains(string(mountinfo), " / ") { |
| + t.Fatalf("own process: %q %q %v", cgroup, mountinfo, err) |
| + } |
| + child := exec.Command("true") |
| + if err := child.Run(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := controlProcess(strconv.Itoa(child.Process.Pid)); err == nil { |
| + t.Skip("the exited child's PID was reused already") |
| + } |
| +} |
diff --git a/internal/host/runsc_update_dirs_rootrunner_linux_test.go b/internal/host/runsc_update_dirs_rootrunner_linux_test.go| new file mode 100644 |
| index 000000000..3a2e44a81 |
| --- /dev/null |
| +++ b/internal/host/runsc_update_dirs_rootrunner_linux_test.go |
| @@ -0,0 +1,557 @@ |
| +//go:build linux && rootrunner |
| + |
| +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" |
| +) |
| + |
| +// 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 |
| + } |
| + 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()) |
| + } |
| +} |
| + |
| +// 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 |
| + } |
| + 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, |
| + } |
| + 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) |
| + }) |
| + 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 { |
| + return 1 |
| + } |
| + 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) |
| + } |
| + 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; a foreign PID in a |
| +// read-only namespace (a recycled PID) never restarts it. (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) |
| + } |
| + 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" |
| + impostor = "carlos-udw-impostor.service" |
| + template = instancectl.UnitPrefixGVisor + ".service" |
| + ) |
| + units := []string{control, runsc, runscGVisor, runscOld, edge, native, template, impostor} |
| + 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.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, impostor} { |
| + _, _ = ctl("stop", unit) |
| + } |
| + for _, path := range installed { |
| + if err := os.Remove(path); err != nil { |
| + t.Errorf("cleanup %s: %v", path, 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) |
| + } |
| + } |
| + }) |
| + // 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, []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="})) |
| + install(impostor, "[Unit]\nDescription=update witness: a foreign process in a strict namespace\n[Service]\nType=exec\nExecStart=/bin/sleep infinity\nProtectSystem=strict\n") |
| + 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) |
| + } |
| + 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()) |
| + } |
| + 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.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 "+control { |
| + return "", fmt.Errorf("witness: unexpected systemctl %v", args) |
| + } |
| + return ctl(args...) |
| + } |
| + probe := func(args ...string) (string, error) { |
| + if strings.Join(args, " ") != "show -p MainPID,InvocationID,ControlGroup "+control { |
| + return "", fmt.Errorf("witness: unexpected probe %v", args) |
| + } |
| + return ctl(args...) |
| + } |
| + gvisorEnv := &systemApplier{sandboxEnvironment: func() (func(string) string, error) { |
| + return func(k string) string { |
| + if k == "CARLOS_EXEC_SANDBOX" { |
| + return "gvisor" |
| + } |
| + return "" |
| + }, nil |
| + }} |
| + // Census R1 P1: a PID that is not control's, here a process in another |
| + // ProtectSystem=strict namespace with oci-rootfs read-only, as an agent |
| + // child holding a recycled PID would be, must not restart control. |
| + must("start", impostor) |
| + impostorPID := show(impostor, "MainPID")["MainPID"] |
| + recycled := func(args ...string) (string, error) { |
| + out, err := probe(args...) |
| + var lines []string |
| + for _, line := range strings.Split(out, "\n") { |
| + if strings.HasPrefix(line, "MainPID=") { |
| + line = "MainPID=" + impostorPID |
| + } |
| + lines = append(lines, line) |
| + } |
| + return strings.Join(lines, "\n"), err |
| + } |
| + refreshControlSandboxRootfsUnit("/etc", control, gvisorEnv, mapped, recycled, t.Logf) |
| + if len(calls) != 0 || mainPID() != before { |
| + t.Fatalf("a foreign PID's read-only namespace restarted control: %q", calls) |
| + } |
| + must("stop", impostor) |
| + refreshControlSandboxRootfsUnit("/etc", control, gvisorEnv, mapped, probe, t.Logf) |
| + if strings.Join(calls, "|") != "try-restart "+control { |
| + 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 |
| + refreshControlSandboxRootfsUnit("/etc", control, 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; a foreign PID restarts nothing; 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") |
| + |
| + // (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) |
| + } |
| + t.Logf("(d) PASS: edge-shaped stop through the healthy control took %s", took.Round(time.Millisecond)) |
| +} |
diff --git a/internal/host/runscensure.go b/internal/host/runscensure.go| index 763301fbb..52a43bf6b 100644 |
| --- a/internal/host/runscensure.go |
| +++ b/internal/host/runscensure.go |
| @@ -58,7 +58,7 @@ func ensureRunsc(ctx context.Context, getenv func(string) string, store release. |
| } |
| root := filepath.Dir(execsandbox.RunscDir(pin)) |
| if err := execsandbox.CheckRootDir(root); err != nil { |
| - return err |
| + return fmt.Errorf("%w: %v", execsandbox.ErrRunsc, err) |
| } |
| // The oneshot and any manual retry share one lock under the only writable root. |
| lock, err := openRunscLock(filepath.Join(root, ".install.lock")) |
diff --git a/internal/host/runscensure_test.go b/internal/host/runscensure_test.go| index 68b97bde6..3dff29352 100644 |
| --- a/internal/host/runscensure_test.go |
| +++ b/internal/host/runscensure_test.go |
| @@ -256,7 +256,7 @@ func TestRunscUnitsAndDirectories(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - want := "[Unit]\nDescription=carlos pinned runsc installation\nBefore=carlos-instance-control.service\n[Service]\nType=oneshot\nUser=root\nGroup=root\nExecStart=/opt/carlos/carlos system runsc-ensure\nEnvironmentFile=-/etc/carlos/host.env\nTimeoutStartSec=120\nProtectSystem=strict\nReadWritePaths=/opt/carlos/runsc\nProtectHome=yes\nPrivateDevices=yes\nNoNewPrivileges=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nUMask=0077\n" |
| + want := "[Unit]\nDescription=carlos pinned runsc installation\nBefore=carlos-instance-control.service\n[Service]\nType=oneshot\nUser=root\nGroup=root\nExecStart=/opt/carlos/carlos system runsc-ensure\nEnvironmentFile=-/etc/carlos/host.env\nTimeoutStartSec=120\nProtectSystem=strict\nReadWritePaths=-/opt/carlos/runsc\nProtectHome=yes\nPrivateDevices=yes\nNoNewPrivileges=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nUMask=0077\n" |
| if string(raw) != want { |
| t.Fatal("installer unit differs from contract") |
| } |
| @@ -266,7 +266,7 @@ func TestRunscUnitsAndDirectories(t *testing.T) { |
| } |
| for _, settings := range []claimUnitSettings{{}, {enabled: true, data: "/data", opt: "/opt/carlos"}} { |
| rendered := string(claimUnitContent(claimControlUnit, control, settings)) |
| - for _, line := range []string{"EnvironmentFile=-/etc/carlos/host.env\n", "Wants=carlos-runsc.service\n", "After=data-instances.mount run-carlos-instances.mount run-carlos-logs.mount carlos-runsc.service\n", "ReadWritePaths=/var/lib/carlos/oci-rootfs\n"} { |
| + for _, line := range []string{"EnvironmentFile=-/etc/carlos/host.env\n", "Wants=carlos-runsc.service\n", "After=data-instances.mount run-carlos-instances.mount run-carlos-logs.mount carlos-runsc.service\n", "ReadWritePaths=-/var/lib/carlos/oci-rootfs\n"} { |
| if strings.Count(rendered, line) != 1 { |
| t.Fatalf("control lacks exactly one %q", line) |
| } |
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go| index 6b34780f8..0d1814c2d 100644 |
| --- a/internal/host/systemapply.go |
| +++ b/internal/host/systemapply.go |
| @@ -483,10 +483,12 @@ func (a *systemApplier) runLocked(ctx context.Context, recover bool, operation f |
| return err |
| } |
| if req.NoOp { |
| + a.migrateSandboxDirectories() |
| return a.writeResult(req, systemOutcomeNoted, "") |
| } |
| installed := a.onDiskBuild(ctx) |
| if p.Current.Version == installed { |
| + a.migrateSandboxDirectories() |
| return a.writeResult(req, systemOutcomeNoted, "") |
| } |
| // The rootfs floor is the console's (console/rootfsfloor.go): it judges |
| @@ -1459,6 +1461,23 @@ func (a *systemApplier) journal(j systemJournal) error { |
| return writeJSONDurable(a.file("journal.json"), j, 0o600) |
| } |
| +// migrateSandboxDirectories gives an apply that installs nothing (a no-op |
| +// request, or the build already on disk) the live sandbox directories |
| +// installUnits would have created: after an update by a build that never |
| +// made them (v0.34.33), the new build's first pass may be exactly such an |
| +// apply. A group member needs its maintenance permit, as installUnits |
| +// does. Failure is logged and leaves the outcome alone; the next adopt |
| +// pass tries again. |
| +func (a *systemApplier) migrateSandboxDirectories() { |
| + if err := a.requireGroupMaintenance("apply", "rollback"); err != nil { |
| + a.ops.logf("system apply: sandbox directories wait for a maintenance permit: %v", err) |
| + return |
| + } |
| + if err := ensureSandboxDirectories(filepath.Dir(a.etcDir), a.optDir); err != nil { |
| + a.ops.logf("system apply: sandbox directories: %v", err) |
| + } |
| +} |
| + |
| // installUnits removes what the target build dropped, copies its units in, |
| // then sysusers BEFORE tmpfiles — tmpfiles silently drops a line whose |
| // group does not resolve, and carlos-edge never starts again after the |
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) { |
diff --git a/internal/host/units/carlos-instance-control.service b/internal/host/units/carlos-instance-control.service| index 4636f281e..dc47099a4 100644 |
| --- a/internal/host/units/carlos-instance-control.service |
| +++ b/internal/host/units/carlos-instance-control.service |
| @@ -45,7 +45,7 @@ ProtectSystem=strict |
| # /run/systemd/system: per-generation runtime drop-ins (zero-downtime |
| # deploys, plan 2 D1) and escaped .mount units for demo snapshot disks. |
| ReadWritePaths=/run/carlos-control /run/systemd/system |
| -ReadWritePaths=/var/lib/carlos/oci-rootfs |
| +ReadWritePaths=-/var/lib/carlos/oci-rootfs |
| ProtectHome=yes |
| PrivateTmp=yes |
| PrivateDevices=yes |
diff --git a/internal/host/units/carlos-runsc.service b/internal/host/units/carlos-runsc.service| index b420839c0..7bf3432c4 100644 |
| --- a/internal/host/units/carlos-runsc.service |
| +++ b/internal/host/units/carlos-runsc.service |
| @@ -9,7 +9,7 @@ ExecStart=/opt/carlos/carlos system runsc-ensure |
| EnvironmentFile=-/etc/carlos/host.env |
| TimeoutStartSec=120 |
| ProtectSystem=strict |
| -ReadWritePaths=/opt/carlos/runsc |
| +ReadWritePaths=-/opt/carlos/runsc |
| ProtectHome=yes |
| PrivateDevices=yes |
| NoNewPrivileges=yes |
diff --git a/internal/instancectl/demo_cleanup.go b/internal/instancectl/demo_cleanup.go| index f55eb83b9..ec5b89d5d 100644 |
| --- a/internal/instancectl/demo_cleanup.go |
| +++ b/internal/instancectl/demo_cleanup.go |
| @@ -246,6 +246,9 @@ func (s *Server) stopDemoUnits(ctx context.Context, host string) (map[string]boo |
| return nil, err |
| } |
| for unit := range units { |
| + if unit == GVisorUnitName(host) && s.gvisorUnitNeverLoaded(ctx, host, unit) { |
| + continue |
| + } |
| out, err = s.Systemctl(ctx, "show", unit, "-p", "ActiveState") |
| if err != nil { |
| return nil, err |
diff --git a/internal/instancectl/gvisor_never_loaded_test.go b/internal/instancectl/gvisor_never_loaded_test.go| new file mode 100644 |
| index 000000000..0296f48ee |
| --- /dev/null |
| +++ b/internal/instancectl/gvisor_never_loaded_test.go |
| @@ -0,0 +1,111 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/execsandbox" |
| +) |
| + |
| +// A systemd-mode box stops the gVisor sibling of every run. Its template's |
| +// empty ExecStart= makes systemd log "Refusing" whenever the name is loaded, |
| +// so a sibling systemd does not hold, with no cgroup and no drop-in, is |
| +// proven gone without its name reaching systemctl. Every other answer keeps |
| +// the show/stop proof. |
| +func TestGVisorSiblingNeverLoadedIsNotNamed(t *testing.T) { |
| + const host = "hs-ie.example" |
| + sibling := GVisorUnitName(host) |
| + if !strings.Contains(sibling, `\x2d`) { |
| + t.Fatalf("fixture must exercise an escaped name: %s", sibling) |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + listing string |
| + listErr error |
| + cgroup bool |
| + dropIn bool |
| + wantNamed bool |
| + }{ |
| + {name: "unlisted", listing: "carlos-instance-gvisor@other.example.service loaded inactive dead x\n"}, |
| + {name: "empty listing", listing: ""}, |
| + {name: "listed escaped name", listing: sibling + " loaded inactive dead carlos gVisor demo instance\n", wantNamed: true}, |
| + {name: "listed with marker column", listing: "● " + sibling + " loaded failed failed x\n", wantNamed: true}, |
| + {name: "cgroup present", cgroup: true, wantNamed: true}, |
| + {name: "drop-in present", dropIn: true, wantNamed: true}, |
| + {name: "listing error", listErr: errors.New("bus"), wantNamed: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var calls []string |
| + s := &Server{CgroupRoot: t.TempDir(), DropInDir: t.TempDir(), SandboxEffective: execsandbox.EffectiveSystemd} |
| + s.removeSandbox = func(string) error { return nil } |
| + s.Systemctl = func(_ context.Context, args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + if args[0] == "list-units" { |
| + return tc.listing, tc.listErr |
| + } |
| + return systemd257Stopped(args[len(args)-1]), nil |
| + } |
| + if tc.cgroup { |
| + if err := os.MkdirAll(filepath.Join(s.CgroupRoot, parentSlices, SliceName(host), sibling), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if tc.dropIn { |
| + if err := os.MkdirAll(filepath.Join(s.DropInDir, sibling+".d"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := s.stopRunFamilies(context.Background(), host); err != nil { |
| + t.Fatal(err) |
| + } |
| + named := false |
| + for _, c := range calls { |
| + if strings.HasPrefix(c, "list-units") { |
| + if !strings.HasSuffix(c, " "+UnitPrefixGVisor+"*.service") || strings.Contains(c, `\`) { |
| + t.Fatalf("listing must ask the family glob, not the escaped name: %q", c) |
| + } |
| + continue |
| + } |
| + if strings.Contains(c, sibling) { |
| + named = true |
| + } |
| + } |
| + if named != tc.wantNamed { |
| + t.Fatalf("gVisor name passed to systemctl = %v, want %v\n%s", named, tc.wantNamed, strings.Join(calls, "\n")) |
| + } |
| + if !strings.Contains(strings.Join(calls, "\n"), "stop "+UnitName(RoleRun, host)) { |
| + t.Fatalf("native run not stopped:\n%s", strings.Join(calls, "\n")) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The best-effort stop (a fence that could not be taken) and demo cleanup |
| +// follow the same rule. |
| +func TestGVisorSiblingNeverLoadedBestEffortAndDemo(t *testing.T) { |
| + const host = "hs-ie.example" |
| + sibling := GVisorUnitName(host) |
| + var calls []string |
| + s := &Server{CgroupRoot: t.TempDir(), DropInDir: t.TempDir(), SandboxEffective: execsandbox.EffectiveSystemd} |
| + s.removeSandbox = func(string) error { return nil } |
| + s.Systemctl = func(_ context.Context, args ...string) (string, error) { |
| + calls = append(calls, strings.Join(args, " ")) |
| + if args[0] == "list-units" { |
| + return "", nil |
| + } |
| + return systemd257Stopped(args[len(args)-1]), nil |
| + } |
| + s.stopRunFamiliesBestEffort(context.Background(), host) |
| + if _, err := s.stopDemoUnits(context.Background(), host); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, c := range calls { |
| + if !strings.HasPrefix(c, "list-units") && strings.Contains(c, sibling) { |
| + t.Fatalf("gVisor name passed to systemctl: %q\n%s", c, strings.Join(calls, "\n")) |
| + } |
| + } |
| +} |
diff --git a/internal/instancectl/sandboxstop.go b/internal/instancectl/sandboxstop.go| index 643b6493f..9858a9a76 100644 |
| --- a/internal/instancectl/sandboxstop.go |
| +++ b/internal/instancectl/sandboxstop.go |
| @@ -59,6 +59,9 @@ func runInactive(m map[string]string) bool { |
| m["MainPID"] == "0" && m["ControlPID"] == "0" && (m["Job"] == "" || m["Job"] == "0") |
| } |
| func (s *Server) stopAndProveRun(ctx context.Context, host, unit string) error { |
| + if s.gvisorUnitNeverLoaded(ctx, host, unit) { |
| + return nil |
| + } |
| if strings.HasPrefix(unit, UnitPrefixRun) && s.effectiveSandbox() == execsandbox.EffectiveSystemd { |
| if _, err := s.Systemctl(ctx, "stop", unit); err != nil { |
| return fmt.Errorf("%s: %w", unit, err) |
| @@ -81,6 +84,9 @@ func (s *Server) stopAndProveRun(ctx context.Context, host, unit string) error { |
| } |
| func (s *Server) proveRunGone(ctx context.Context, host, unit string) error { |
| + if s.gvisorUnitNeverLoaded(ctx, host, unit) { |
| + return nil |
| + } |
| out, err := s.Systemctl(ctx, "show", "-p", runProofProperties, unit) |
| if err != nil { |
| return fmt.Errorf("%s: %w", unit, err) |
| @@ -148,3 +154,47 @@ func (s *Server) sandboxRunFilesPresent(host string) (bool, error) { |
| } |
| return false, nil |
| } |
| + |
| +// gvisorUnitNeverLoaded proves a carlos-instance-gvisor@ instance gone |
| +// without naming it to systemd. The template ships an empty ExecStart= that |
| +// only a per-start drop-in fills, so `systemctl show` or `stop` of a name |
| +// that was never started makes systemd load it and log "Service has no |
| +// ExecStart=... Refusing" on every stop of a systemd-mode box. The proof |
| +// here: no cgroup directory, no drop-in directory a start could have used, |
| +// and systemd does not list the name among the units it holds (a running |
| +// unit, or one with a queued job, is always loaded). The listing asks for |
| +// the family glob, never the escaped name: fnmatch would read the \x2d |
| +// backslashes as escapes. Anything else, including any error, is false and |
| +// the caller runs the existing show/stop proof. |
| +func (s *Server) gvisorUnitNeverLoaded(ctx context.Context, host, unit string) bool { |
| + if !strings.HasPrefix(unit, UnitPrefixGVisor) || s.Systemctl == nil || s.CgroupRoot == "" || s.DropInDir == "" { |
| + return false |
| + } |
| + for _, path := range []string{ |
| + filepath.Join(s.CgroupRoot, parentSlices, SliceName(host), unit), |
| + filepath.Join(s.DropInDir, unit+".d"), |
| + } { |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + return false |
| + } |
| + } |
| + out, err := s.Systemctl(ctx, "list-units", "--all", "--plain", "--no-legend", "--no-pager", UnitPrefixGVisor+"*.service") |
| + if err != nil { |
| + return false |
| + } |
| + return !unitListed(out, unit) |
| +} |
| + |
| +// unitListed reads list-units output loosely: any field equal to the name |
| +// counts, so a marker column systemd may add can only turn the answer into |
| +// "listed", which keeps the full proof. |
| +func unitListed(out, unit string) bool { |
| + for _, line := range strings.Split(out, "\n") { |
| + for _, f := range strings.Fields(line) { |
| + if f == unit { |
| + return true |
| + } |
| + } |
| + } |
| + return false |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index e1115e31d..6ef8a02df 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -136,4 +136,5 @@ plan14-root-reads-edge-page-cache-1.tsv 2774b43ac5970e4340339b859204bce5eb9f83d4 |
| plan14-root-reads-cli-default-console-carloku.tsv 2774b43ac5970e4340339b859204bce5eb9f83d4c2551f0984e919a2853d0216 |
| plan14-root-reads-gvisor-demos.tsv f05716181a82721b38cba9b2d89c47925dc2ca426e5c4876ebf1df7b45895ee3 |
| plan14-root-reads-dns-fresh-lookup-724.tsv 7ac2bde8301c37c7546e9aa19d375f1468fc8061876a618fa8f93dd4543c5652 |
| -plan14-root-reads-region-ha-held-build.tsv 318d254cf1f1bd33b50bed810332a2d95e89c43b558c5d305d3e64e3d8d9ff9e |
| +plan14-root-reads-gvisor-update-dirs.tsv 1f1b2fdb569b7be42e75e10d1943d7e512708299364f912c2f72dccf1bd5b678 |
| +plan14-root-reads-region-ha-held-build.tsv beb085e4c6cdb3d430d12a8dc3c93f25cc3faf1aa7d62be37698ff9c9c82ecce |
diff --git a/internal/provision/testdata/plan14-root-reads-gvisor-update-dirs.tsv b/internal/provision/testdata/plan14-root-reads-gvisor-update-dirs.tsv| new file mode 100644 |
| index 000000000..ca9326dd2 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-gvisor-update-dirs.tsv |
| @@ -0,0 +1,29 @@ |
| +# Census overlay gvisor-update-dirs, written by census-propose (#369). census-ruling-gvisor-update-dirs, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-gvisor-update-dirs.md. |
| +# 5 body, 1 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 5 new dispositions: 0 reads re-frozen at their disposition with the claim, 5 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy a31d936c380a6060704b40c6d6e569e0fb4b00b52894baf52728b5ef8328b092 internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@7163,file:Stat@5535 6965ff178aa9e83348531a6efde9079afb5b854fedd7f3ef7c583ddd85b7ab53 |
| +@legacy 2a09834a13b7680f82c908ba234f22ec57d6132d078ab506dd434bc8b39f979f internal/host/units/carlos-runsc.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Root oneshot reads fixed root-owned host.env through its applet and installs compiled runtime set only under /opt/carlos/runsc; no RemainAfterExit.;rev3=census-ruling-gvisor-update-dirs;basis=Make the existing /opt/carlos/runsc writable-path entry optional when absent so systemd-mode installation exits successfully on old boxes; gvisor still refuses absent runtime directories with EXEC-SANDBOX-RUNSC. No new path or root read. file:external@0 04810deed46d3bbfaf189b86e44cf68bf716f09b7ea3349ef007c4bceb085431 |
| +@legacy 2af8c4ae54d94dc8925e0760c52d1b03c456d36914cb67abddd2e8b1c45c4199 internal/instancectl/demo_cleanup.go Server.stopDemoUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Enumerate derived instance units, stop them and prove unit/cgroup emptiness before freeze or purge proceeds. Census read-site delta: +file:ReadDir.;rev3=census-ruling-gvisor-demos;basis=Acquire the existing original-run fence, stop/prove both original families, finish the retained runsc delete hook and remove the gVisor bundle/skeleton/drop-in before freeze or purge may stream data. Discover queued generation jobs as well as loaded units and retained generation files. Existing ReadDir inputs remain derived controller roots.;rev3=census-ruling-gvisor-update-dirs;basis=Skip the post-stop ActiveState show for the host's gVisor sibling only when gvisorUnitNeverLoaded proves it never loaded; the slice-level cgroup-empty wait still runs. No new read. file:ReadDir@1365 d8ff73c6f7f669aa9f6bd850c2e9d3d46bebf50d6bd4af46bf2c684a9b3779b0 |
| +@legacy a28f4924a540c362a66074dd29a18ff2a17afbbcf6e965fd411c9e59df95fd8f internal/instancectl/sandboxstop.go Server.proveRunGone legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Task 5: read only the validated host-derived systemd cgroup.events path under the configured root. Require complete inactive/dead state, zero jobs/MainPID/ControlPID, expected ControlGroup and exact populated 0 or absent cgroup; unreadable or malformed proof refuses cleanup. Fix round 1 C1/I1: accept the captured systemd 257 empty Job field as no queued job, also zero. Do not infer running state from LoadState; keep required-property presence, inactive/failed plus dead/failed, zero MainPID/ControlPID, expected ControlGroup and empty/absent cgroup proof. Native cleanup runs before sibling ID derivation. No new read path. Task 9: Treat omitted empty Job, InvocationID and ControlGroup as their captured systemd 257 unset defaults. Require explicit LoadState, ActiveState, SubState, MainPID and ControlPID; retain no-job, zero-PID, terminal-state, expected-group and empty/absent-cgroup checks. Same fixed derived path and read.;rev3=census-ruling-gvisor-update-dirs;basis=For a carlos-instance-gvisor@ unit only, return proven-gone without naming it to systemctl when gvisorUnitNeverLoaded holds (no cgroup dir, no drop-in dir, not listed by systemd). Every other unit, and any doubt or error, keeps the existing show/cgroup proof unchanged. file:ReadFile@916 5d67a0f1f76f5582b6a1a2a8690f7355c4724f2a0518ed59f1d5850ddfe675a2 |
| +@legacy 796be076f07a5138618981ef1c0b304f4cd1eed6d4eaf84796f184255dd9fb46 internal/activator/backend_exec.go ExecBackend.gvisorSiblingNeverLoaded legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New, agent side: Lstat of /run/systemd/system/<sibling>.d, the existing unitEvents cgroup read, and the read-only list-units family glob via UnitsListed. All must say absent; any error returns false so the full proof runs. No root decision. file:Lstat@322,whole:Route@455 70df41b956a2c1b4ce6d0c769a36f81f3facb6943229e9a744ce62fe3a5fda20 |
| +@legacy f5399a6f15da500e625eac9cfd36448779ea1051b7f7b9e5f3fe54dcba973114 internal/activator/control.go systemctlUnitsListed legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New, agent side: `systemctl list-units --all --plain --no-legend --no-pager <glob>`, read-only; the spawn guard's read-only verb list gains list-units. file:CommandContext@91 52c36953bba90fadc4ff0684877f8efe0b9d951d97693077faded8b1123ab373 |
| +@legacy 4f5cf0afb2c8cc2bb2d6bb2435d2db17c49b5cc4ca2fe5b0c1bfcbecc86cb73e internal/demobuild/unit.go gvisorBuildNeverLoaded legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New: Lstat of the build cgroup dir (emptyBuildCgroup's path) and of the job drop-in dir under unitRoot, then list-units with the fixed carlos-demo-build-gvisor@*.service glob and an exact match. Only when all say absent does stopBuildContext skip show/stop of the gVisor build unit; any error keeps the full proof. R1 P2-3: a listing at the wrapper's 128 KiB capture limit may be truncated and also returns false (full proof). file:Lstat@191 bce764f50a586475761b49c47c4c001fde1bc1f6117bf41f5502e02f248f1ae8 |
| +@legacy 0b0003a02e3adb3a95986824e49b0fc87cce21343287ad602ac03306f069d9e4 internal/host/execsandboxfloor.go var controlProcess legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=Replaces var controlMountinfo (census R1 P1). Opens /proc/<pid> once (os.OpenRoot, a directory fd) and reads cgroup and mountinfo through it with openat, so both come from one process instance and fail with ESRCH once it has exited, even if the PID is reused. The caller (refreshControlSandboxRootfsUnit) takes MainPID,InvocationID,ControlGroup from systemctl show (any error: no answer), requires the cgroup file to be exactly 0::<ControlGroup> with ControlGroup ending in /carlos-instance-control.service, re-reads the three values and requires them unchanged; any error, mismatch or exited process is unknown and never restarts. The only effect remains one try-restart of carlos-instance-control.service in effective gVisor mode when the containing mount of /var/lib/carlos/oci-rootfs is read-only. file:OpenRoot@91,file:ReadFile@212,file:ReadFile@296 5d7b01ee4d8afbf6e33eb717f5504d1c5368ca6271b748268561d2def7fb4f0d |
| +@legacy 5ef56f0c8f8c9f406f11356586c550e8d64d2f0f08c492138c3a78204c3730fb internal/instancectl/sandboxstop.go Server.gvisorUnitNeverLoaded legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New: Lstat of the host-derived cgroup directory under the configured cgroup root and of <DropInDir>/<unit>.d (both must be absent), then `systemctl list-units --all --plain --no-legend --no-pager carlos-instance-gvisor@*.service` (fixed family glob) and an exact-name match in Go. Any error or presence returns false so the full proof runs. file:Lstat@379 6c51d378fd35d05545483615163fc5a28431b97359a4de8b4c2437c6d5a4b06c |
| +@legacy 1c1fe1e038d3f677379ebd06d48c81c9cdb7b02a658529b51eeb21b3a010225e internal/activator/backend_exec.go ExecBackend.LegacyRunGone legacy accepted-legacy accepted-legacy;rev3=census-ruling-292;basis=Census ruling 292: new unit; stops the host's original run unit through instance-control's existing /stop and proves it gone from systemctl show state and cgroup.events, as the exit observer reads. The termination proof only decides release-or-keep, and never starts, wakes or admits anything; unknown or error means keep. Boundary: agent-side shutdown gates running as carlos; they refuse or stop new work once shutdown begins, and a cancelled wake releases its lease; no new read and no root decision; plus the legacy run unit's termination proof (systemctl show state and cgroup.events, as the exit observer reads), and a retried conditional lease delete of the same record.;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=a rootfs row's original run unit is the rootfs template's: it is named by unitNameFor and stopped through stopRole (the rootfs verb), and its cgroup proven by unitEvents, which for a rootfs row also reads the control group systemd reports; the Host sites became Route sites (the route passed to those three); the proof's rule is unchanged: unknown or error keeps the lease; no root decision;rev3=census-ruling-gvisor-demos;basis=Task 5: after root fenced Stop succeeds, check both native and gVisor original siblings using the existing systemd/cgroup readers; rootfs retains its existing path. A failed root proof returns immediately and keeps the lease. No mode-dependent cleanup.;rev3=census-ruling-gvisor-update-dirs;basis=Agent side (carlos user): skip the gVisor sibling's show-based proof only when gvisorSiblingNeverLoaded holds; the native unit's proof is unchanged and any doubt keeps the lease as before. registry:Host@174,registry:Host@606,whole:Route@393,whole:Route@448,whole:Route@665,whole:Route@783 036ffb949da93314622f0e15d128e5e8db794971c2546a96ddbac217209a4415 |
| +internal/host/systemunits.go ensureSystemUnitsWithGuard legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Move unit-repair body here with existing lock/unit/host.env reads; under lock require operator repair permit on groups before writes and each systemctl effect, preserve root masks/drop-in and omit automatic update/recovery units. New indirect protected marker/permit reads, never agent receipt; fixed repair unchanged.;rev3=census-ruling-gvisor-demos;basis=Create runtime/rootfs directories and repair installer plus three measured workload templates without arming them. Existing unit/host.env reads unchanged.;rev3=census-ruling-gvisor-update-dirs;basis=Create the two live sandbox directories (the same fixed ensureSandboxDirectories paths) before the apply lock and the early returns on non-group boxes; group members still create them only after the maintenance permit. A creation error still ends the pass at the original point. Then call refreshControlSandboxRootfs. No new path, input or systemctl verb beyond the try-restart below. file:OpenFile@985,file:ReadFile@5626,file:ReadFile@5759,file:ReadFile@7163,file:Stat@5535 6965ff178aa9e83348531a6efde9079afb5b854fedd7f3ef7c583ddd85b7ab53 |
| +internal/host/units/carlos-instance-control.service external authority B3,C,D,E1,J4 root-input;kept=B3,C,D,E1;scope=protected-decision-only;rev3=census-ruling-agent-start-demo-3;basis=Correct the runtime-write comment to include escaped demo snapshot .mount units alongside per-generation drop-ins; service directives are unchanged.;rev3=census-ruling-region-ha-graceful-terminate-t1;basis=Region HA T1/DR-4 final fix: retain After=nftables.service without Wants or Requires; add Restart=on-failure and RestartSec=1 so a crashed control restarts before a later edge stop can block socket activation and shutdown proofs; rewrap the header and explain this ordering. Same ExecStart and protections; no new root read, input, path, command or capability.;rev3=census-ruling-gvisor-demos;basis=Add Wants/After installer and narrowly writable rootfs parent. Keep one host.env EnvironmentFile and other hardening.;rev3=census-ruling-gvisor-update-dirs;basis=Make the existing /var/lib/carlos/oci-rootfs writable-path entry optional when absent so old updaters can start the new control unit; retain ProtectSystem=strict and the same path and environment. No new root read. file:external@0 b9d8a5520b25dc0508a0c2684d39445dfc45085776cdbb51159ecb1cee93b39c |
| +internal/host/units/carlos-runsc.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Root oneshot reads fixed root-owned host.env through its applet and installs compiled runtime set only under /opt/carlos/runsc; no RemainAfterExit.;rev3=census-ruling-gvisor-update-dirs;basis=Make the existing /opt/carlos/runsc writable-path entry optional when absent so systemd-mode installation exits successfully on old boxes; gvisor still refuses absent runtime directories with EXEC-SANDBOX-RUNSC. No new path or root read. file:external@0 04810deed46d3bbfaf189b86e44cf68bf716f09b7ea3349ef007c4bceb085431 |
| +internal/instancectl/demo_cleanup.go Server.stopDemoUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-3;basis=Enumerate derived instance units, stop them and prove unit/cgroup emptiness before freeze or purge proceeds. Census read-site delta: +file:ReadDir.;rev3=census-ruling-gvisor-demos;basis=Acquire the existing original-run fence, stop/prove both original families, finish the retained runsc delete hook and remove the gVisor bundle/skeleton/drop-in before freeze or purge may stream data. Discover queued generation jobs as well as loaded units and retained generation files. Existing ReadDir inputs remain derived controller roots.;rev3=census-ruling-gvisor-update-dirs;basis=Skip the post-stop ActiveState show for the host's gVisor sibling only when gvisorUnitNeverLoaded proves it never loaded; the slice-level cgroup-empty wait still runs. No new read. file:ReadDir@1365 d8ff73c6f7f669aa9f6bd850c2e9d3d46bebf50d6bd4af46bf2c684a9b3779b0 |
| +internal/instancectl/sandboxstop.go Server.proveRunGone legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Task 5: read only the validated host-derived systemd cgroup.events path under the configured root. Require complete inactive/dead state, zero jobs/MainPID/ControlPID, expected ControlGroup and exact populated 0 or absent cgroup; unreadable or malformed proof refuses cleanup. Fix round 1 C1/I1: accept the captured systemd 257 empty Job field as no queued job, also zero. Do not infer running state from LoadState; keep required-property presence, inactive/failed plus dead/failed, zero MainPID/ControlPID, expected ControlGroup and empty/absent cgroup proof. Native cleanup runs before sibling ID derivation. No new read path. Task 9: Treat omitted empty Job, InvocationID and ControlGroup as their captured systemd 257 unset defaults. Require explicit LoadState, ActiveState, SubState, MainPID and ControlPID; retain no-job, zero-PID, terminal-state, expected-group and empty/absent-cgroup checks. Same fixed derived path and read.;rev3=census-ruling-gvisor-update-dirs;basis=For a carlos-instance-gvisor@ unit only, return proven-gone without naming it to systemctl when gvisorUnitNeverLoaded holds (no cgroup dir, no drop-in dir, not listed by systemd). Every other unit, and any doubt or error, keeps the existing show/cgroup proof unchanged. file:ReadFile@916 5d67a0f1f76f5582b6a1a2a8690f7355c4724f2a0518ed59f1d5850ddfe675a2 |
| +internal/activator/backend_exec.go ExecBackend.gvisorSiblingNeverLoaded legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New, agent side: Lstat of /run/systemd/system/<sibling>.d, the existing unitEvents cgroup read, and the read-only list-units family glob via UnitsListed. All must say absent; any error returns false so the full proof runs. No root decision. file:Lstat@322,whole:Route@455 70df41b956a2c1b4ce6d0c769a36f81f3facb6943229e9a744ce62fe3a5fda20 |
| +internal/activator/control.go systemctlUnitsListed legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New, agent side: `systemctl list-units --all --plain --no-legend --no-pager <glob>`, read-only; the spawn guard's read-only verb list gains list-units. file:CommandContext@91 52c36953bba90fadc4ff0684877f8efe0b9d951d97693077faded8b1123ab373 |
| +internal/demobuild/unit.go gvisorBuildNeverLoaded legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New: Lstat of the build cgroup dir (emptyBuildCgroup's path) and of the job drop-in dir under unitRoot, then list-units with the fixed carlos-demo-build-gvisor@*.service glob and an exact match. Only when all say absent does stopBuildContext skip show/stop of the gVisor build unit; any error keeps the full proof. R1 P2-3: a listing at the wrapper's 128 KiB capture limit may be truncated and also returns false (full proof). file:Lstat@191 bce764f50a586475761b49c47c4c001fde1bc1f6117bf41f5502e02f248f1ae8 |
| +internal/host/execsandboxfloor.go var controlProcess legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=Replaces var controlMountinfo (census R1 P1). Opens /proc/<pid> once (os.OpenRoot, a directory fd) and reads cgroup and mountinfo through it with openat, so both come from one process instance and fail with ESRCH once it has exited, even if the PID is reused. The caller (refreshControlSandboxRootfsUnit) takes MainPID,InvocationID,ControlGroup from systemctl show (any error: no answer), requires the cgroup file to be exactly 0::<ControlGroup> with ControlGroup ending in /carlos-instance-control.service, re-reads the three values and requires them unchanged; any error, mismatch or exited process is unknown and never restarts. The only effect remains one try-restart of carlos-instance-control.service in effective gVisor mode when the containing mount of /var/lib/carlos/oci-rootfs is read-only. file:OpenRoot@91,file:ReadFile@212,file:ReadFile@296 5d7b01ee4d8afbf6e33eb717f5504d1c5368ca6271b748268561d2def7fb4f0d |
| +internal/instancectl/sandboxstop.go Server.gvisorUnitNeverLoaded legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-update-dirs;basis=New: Lstat of the host-derived cgroup directory under the configured cgroup root and of <DropInDir>/<unit>.d (both must be absent), then `systemctl list-units --all --plain --no-legend --no-pager carlos-instance-gvisor@*.service` (fixed family glob) and an exact-name match in Go. Any error or presence returns false so the full proof runs. file:Lstat@379 6c51d378fd35d05545483615163fc5a28431b97359a4de8b4c2437c6d5a4b06c |
| +internal/activator/backend_exec.go ExecBackend.LegacyRunGone legacy accepted-legacy accepted-legacy;rev3=census-ruling-292;basis=Census ruling 292: new unit; stops the host's original run unit through instance-control's existing /stop and proves it gone from systemctl show state and cgroup.events, as the exit observer reads. The termination proof only decides release-or-keep, and never starts, wakes or admits anything; unknown or error means keep. Boundary: agent-side shutdown gates running as carlos; they refuse or stop new work once shutdown begins, and a cancelled wake releases its lease; no new read and no root decision; plus the legacy run unit's termination proof (systemctl show state and cgroup.events, as the exit observer reads), and a retried conditional lease delete of the same record.;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=a rootfs row's original run unit is the rootfs template's: it is named by unitNameFor and stopped through stopRole (the rootfs verb), and its cgroup proven by unitEvents, which for a rootfs row also reads the control group systemd reports; the Host sites became Route sites (the route passed to those three); the proof's rule is unchanged: unknown or error keeps the lease; no root decision;rev3=census-ruling-gvisor-demos;basis=Task 5: after root fenced Stop succeeds, check both native and gVisor original siblings using the existing systemd/cgroup readers; rootfs retains its existing path. A failed root proof returns immediately and keeps the lease. No mode-dependent cleanup.;rev3=census-ruling-gvisor-update-dirs;basis=Agent side (carlos user): skip the gVisor sibling's show-based proof only when gvisorSiblingNeverLoaded holds; the native unit's proof is unchanged and any doubt keeps the lease as before. registry:Host@174,registry:Host@606,whole:Route@393,whole:Route@448,whole:Route@665,whole:Route@783 036ffb949da93314622f0e15d128e5e8db794971c2546a96ddbac217209a4415 |
| +@coverage internal/activator 10892f693ca6b72fa9cac7ec90ed25edb3cff03888f2a7365ce3d3e4d8f57ca4 |
| +@coverage internal/demobuild ec946d406609b27ff6bd70ac463163a3831656f9f3e972f92831dbc54e77406f |
| +@coverage internal/host 80777f8a695cacefef63316a89cfa55d73f32d6a13d6f190d4b757d21e4865b3 |
| +@coverage internal/host/units da7a1e3e835538ee4b56d31d0e19d671aa2b80d40d4ac3e5341806aaab13cf19 |
| +@coverage internal/instancectl 3b705c0428138f9cb85849fc917b964e4de3576d4499ce8c382ab45ae690822e |
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-held-build.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-held-build.tsv| index 45103fb4f..a78d77ba4 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-region-ha-held-build.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-region-ha-held-build.tsv |
| @@ -126,7 +126,7 @@ internal/edge/haingress.go Edge.routeHAIngress legacy accepted-legacy accepted-l |
| @coverage infra/modules/region-group-operator-document 4e6b842cc6a23bc4f2e6eaca6b110122cb30ccd3edecb1a253810f7cce1bc510 |
| @coverage infra/modules/region-host 63554d2ccdf4b6f17469cdfb8041dc63eba94bdfbb3f61fcbbd3767f8c220340 |
| @coverage infra/modules/region-host/tests 3e19da6a3614aaa043b62abce2dd03952615504dbc7b397c1b41e49235973111 |
| -@coverage internal/activator 9ea2220f386b796ece91de3ae8e26f6dcb291b16a76b55676141389ef394a8ed |
| +@coverage internal/activator 5cec37812e59998d2ba0357eb8d0bd164070fc586138e7f44f64cabfedc5f4a8 |
| @coverage internal/edge 1c39c64fa5cd46fb3ca50a572982a91b4b3b9fde12ff9c3bd94e3fbd018ad352 |
| -@coverage internal/host cc821dc0d61676187115793e71eff3260fb1f960860440125eedb05637abced5 |
| +@coverage internal/host 968fe876982b0d60df43f5020679801f2b957209c038bbcb80dc22752903f9ae |
| @coverage internal/lease b71e22ea0a4a9d894dfaf39f5012494d79ba2e5af10c80f98e0a6f11d28f7d0c |