host: bound systemctl queries; one helper for every systemd call
Batch 3 of the Go code-health plan (#1123): - internal/systemd runs every systemctl and journalctl call in the root binary (45 sites). Read-only queries and journalctl get a 30 s bound and are killed with a TimeoutError naming the verb and unit; mutating verbs (start, stop, restart, reload, daemon-reload, the system apply) keep the caller's context only, as before. Bounding job verbs needs outcome reconciliation first: #1214. - A settle deadline reached through failed observations is a temporary UnitNotUpError: the rollback restart still replaces the process and the version is not poisoned. Observed failures are unchanged. - caps keeps the timeout's type (%w). - TestSystemctlCallsAreBounded guards every invocation form, shell -c and package-level literals included. - The edge prober's dial gives up at its 2 s probe timeout. - host-context raised by 17 explicit, commented sites. Reviewed by Astra: round 1 NOT READY (scope cut), round 2 READY AFTER FIXES (stopping rule 2; Paul chose the central fix), scoped check passed. Census (root-read and record-write) approved on #280. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from bounded-systemctl into main.
53 files changed,
+2,041
−105
.amadan/code-health.tsv+17 −0docs/superpowers/notes/census-proposal-bounded-systemctl.md+89 −0docs/superpowers/reviews/CHECK-BRIEF-bounded-systemctl-R2-fix.md+28 −0docs/superpowers/reviews/CHECK-bounded-systemctl-R2-fix.md+33 −0docs/superpowers/reviews/FINDINGS-bounded-systemctl-R1.md+140 −0docs/superpowers/reviews/FINDINGS-bounded-systemctl-R2.md+115 −0docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl-R2.md+56 −0docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl.md+58 −0internal/activator/backend_unit.go+2 −2internal/activator/control.go+5 −4internal/caps/converge.go+8 −3internal/caps/systemctl_error_test.go+30 −0internal/demobuild/unit.go+4 −6internal/edge/prober.go+12 −5internal/edge/upstreamdial.go+19 −7internal/edge/upstreamdial_test.go+56 −0internal/hairpin/native_linux.go+2 −1internal/host/adopt_advice.go+4 −1internal/host/agent.go+9 −6internal/host/bootstrap.go+4 −1internal/host/claimfilesseed_delegation_linux.go+2 −2internal/host/claimjournal_migration_linux.go+2 −2internal/host/claimlaunch_production.go+2 −2internal/host/claimstop_production.go+2 −2internal/host/claimstop_writers_linux.go+3 −3internal/host/claimunit_socket_migration_linux.go+2 −2internal/host/dbreads_linux.go+3 −2internal/host/egress_source.go+2 −2internal/host/group_maintenance_verbs_linux.go+5 −6internal/host/probes.go+10 −5internal/host/restartwatch.go+3 −3internal/host/rootgeneration_services_linux.go+2 −2internal/host/runscensure.go+2 −2internal/host/settle_verdict_adopt_test.go+115 −0internal/host/systemapply.go+7 −2internal/host/systemunits.go+4 −2internal/host/unitops.go+8 −4internal/host/unitsettle.go+37 −8internal/host/unitsettle_test.go+41 −4internal/instancectl/gvisor_claim_rootrunner_linux_test.go+4 −0internal/instancectl/gvisorprobe.go+2 −2internal/instancectl/gvisorprobe_flow_linux_test.go+4 −4internal/instancectl/hairpin.go+2 −2internal/instancectl/peer_linux.go+3 −2internal/instancectl/server.go+10 −1internal/ops/ops.go+2 −2internal/provision/bounded_systemctl_census_test.go+35 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-bounded-systemctl.tsv+92 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/systemd/command.go+276 −0internal/systemd/command_test.go+231 −0internal/systemd/guard_test.go+435 −0
CI failed — run details
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index f7870e1d4..22c4f90bb 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -2081,6 +2081,7 @@ host-context internal/host RunSystemJournalMigrate context.Background 1 |
| host-context internal/host RunSystemProxyAllowsPrev context.Background 1 |
| host-context internal/host RunSystemRunscEnsure context.Background 1 |
| host-context internal/host adoptLoop context.Background 1 |
| +host-context internal/host adoptTimerActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host agentEntry context.Background 2 |
| host-context internal/host armDBReads context.Background 1 |
| host-context internal/host armHAPlacement context.Background 1 |
| @@ -2092,9 +2093,11 @@ host-context internal/host boxRecordLoop context.Background 1 |
| host-context internal/host checkedUnitRestart context.Background 4 |
| host-context internal/host closeReplicaCoordinator context.Background 1 |
| host-context internal/host configGenLoop context.Background 1 |
| +host-context internal/host configPathActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host configSyncLoop context.Background 1 |
| host-context internal/host configureGroupHairpinClient context.Background 2 |
| host-context internal/host createClaimEdgeMask context.Background 1 |
| +host-context internal/host daemonReload context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host domainsLoop context.Background 2 |
| host-context internal/host edgeFenceStatusReport context.Background 1 |
| host-context internal/host edgesFileLoop context.Background 2 |
| @@ -2125,7 +2128,9 @@ host-context internal/host package-level context.Background 1 |
| host-context internal/host parkRecoveryJournal context.Background 1 |
| host-context internal/host parkRevertJournal context.Background 1 |
| host-context internal/host platformUnitRestarts context.Background 1 |
| +host-context internal/host probeUnits context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host productionRootRestartChecks context.Background 1 |
| +host-context internal/host productionSysOps context.Background 2 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host proofObserver.observe context.Background 2 |
| host-context internal/host proofRoot.stillLive context.Background 1 |
| host-context internal/host publishResidentFleetBindings context.Background 1 |
| @@ -2139,6 +2144,7 @@ host-context internal/host releaseHousekeeperLease context.Background 1 |
| host-context internal/host releaseOwnLease context.Background 1 |
| host-context internal/host resolveHost context.Background 1 |
| host-context internal/host restartBoundUnit context.Background 4 |
| +host-context internal/host restartPathActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host retentionLoop context.Background 1 |
| host-context internal/host rollbackUnitRestart context.Background 5 |
| host-context internal/host rootInstallationHostApp context.Background 3 |
| @@ -2160,7 +2166,18 @@ host-context internal/host startHousekeeper context.Background 1 |
| host-context internal/host statusLoop context.Background 1 |
| host-context internal/host steeringLoop context.Background 1 |
| host-context internal/host sweepStagedVersions context.Background 1 |
| +host-context internal/host systemUpdatePathActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctl context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlProbe context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlRestartUnit context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlStartUnit context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlTryRestart context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlTryRestartUnit context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemctlVerb context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemdUnits.JournalTail context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| +host-context internal/host systemdUnits.Show context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host tunnelLoop context.Background 1 |
| +host-context internal/host unitsAreActive context.Background 1 # raised: bounded-systemctl: systemctl/journalctl through internal/systemd from a function with no context to pass; an explicit, counted Background, not a hidden one (Astra r1 P2-5) |
| host-context internal/host usageLoop context.Background 1 |
| host-context internal/host validateServingParkRecord context.Background 2 |
| host-context internal/host wireRawSecretPages context.Background 1 |
diff --git a/docs/superpowers/notes/census-proposal-bounded-systemctl.md b/docs/superpowers/notes/census-proposal-bounded-systemctl.md| new file mode 100644 |
| index 000000000..cf3c678e1 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-bounded-systemctl.md |
| @@ -0,0 +1,89 @@ |
| +# Census approval: bounded-systemctl |
| + |
| +Ruling `census-ruling-bounded-systemctl`. The independent reviewer approves or rejects every change below, 27 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/caps/converge.go` `Ops.query` | body | unchanged (3) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/caps/converge.go` `Ops.systemctl` | body | unchanged (1) | behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input; its error now wraps systemctl's with %w instead of %v, same text | |
| +| `internal/host/adopt_advice.go` `unitsAreActive` | body | unchanged (1) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/host/agent.go` `systemctlStartUnit` | body | unchanged (1) | behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input | |
| +| `internal/host/agent.go` `systemctlTryRestart` | body | unchanged (1) | behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input | |
| +| `internal/host/agent.go` `systemctlTryRestartUnit` | body | unchanged (1) | behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input | |
| +| `internal/host/bootstrap.go` `systemctl` | body | unchanged (1) | behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input | |
| +| `internal/host/probes.go` `adoptTimerActive` | body | unchanged (1) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/host/probes.go` `configPathActive` | body | unchanged (1) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/host/probes.go` `restartPathActive` | body | unchanged (1) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/host/probes.go` `systemUpdatePathActive` | body | unchanged (1) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/host/systemapply.go` `productionSysOps` | body | unchanged (3) | behaviour unchanged for mutations, bounded for queries: both closures run through internal/systemd.Command under context.Background(); the sysOps seam's mutations (the edge restart, stop, start, daemon-reload) get no deadline, exactly as exec.Command, and its queries (is-active, show) and edgeStartedThisBoot's show QueryTimeout (30 s); the round-1 18 min class is removed; no new read, path or input | |
| +| `internal/host/systemunits.go` `systemctlProbe` | body | unchanged (1) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/host/unitops.go` `daemonReload` | body | unchanged (1) | behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input | |
| +| `internal/host/unitops.go` `probeUnits` | body | unchanged (1) | bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input | |
| +| `internal/host/unitops.go` `systemctlRestartUnit` | body | unchanged (1) | behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input | |
| +| `internal/host/unitsettle.go` `systemctlVerb` | body | unchanged (1) | behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input | |
| +| `internal/host/unitsettle.go` `systemdUnits.JournalTail` | body | unchanged (1) | bounded query: the same journalctl arguments and stdout through internal/systemd.Command(Journalctl), under QueryTimeout (30 s); a timeout gives an empty tail, as any failure did; no new read | |
| +| `internal/host/unitsettle.go` `systemdUnits.Show` | body | unchanged (1) | bounded query; a deadline reached through temporary observation failures is a temporary UnitNotUpError, so the rollback restart still replaces the process and the version is not poisoned: the same show properties and parser through internal/systemd.Command under context.Background() and QueryTimeout (30 s); its error, a TimeoutError included, is returned as before; no new read | |
| +| `internal/instancectl/gvisorprobe.go` `Server.runGVisorProbe` | body | unchanged (4) | the failure diagnostic calls the new Server.Journal seam with the same journalctl arguments minus the program name, instead of Server.Run with "journalctl" first; nil Journal skips it as nil Run did; no new path, input or verb | |
| +| `internal/instancectl/server.go` `type Server` | body | unchanged (1) | new field Journal, the journalctl seam for the gVisor probe's diagnostic; field declaration only; no read added | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/caps`, `internal/demobuild`, `internal/edge`, `internal/hairpin`, `internal/host`, `internal/instancectl`, `internal/ops`, `internal/systemd`. |
| + |
| +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/caps/converge.go` `Ops.query`: authority, task E4,J1,J4. Basis: root-input |
| +- `internal/caps/converge.go` `Ops.systemctl`: authority, task E4,J1,J4. Basis: root-input |
| +- `internal/host/adopt_advice.go` `unitsAreActive`: diagnostic, task H3. Basis: no-effect |
| +- `internal/host/agent.go` `systemctlStartUnit`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/agent.go` `systemctlTryRestart`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/agent.go` `systemctlTryRestartUnit`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/bootstrap.go` `systemctl`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/probes.go` `adoptTimerActive`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/probes.go` `configPathActive`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/probes.go` `restartPathActive`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/probes.go` `systemUpdatePathActive`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/systemapply.go` `productionSysOps`: authority, task D,F,J4. Basis: root-input;kept=D,F;scope=protected-decision-only |
| +- `internal/host/systemunits.go` `systemctlProbe`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/host/unitops.go` `daemonReload`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl daemon-reload, once per pass when a marker exists |
| +- `internal/host/unitops.go` `probeUnits`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl show -p Id,LoadState,EnvironmentFiles <units>, unit names already passed DeliverableUnitName; parsed positionally, a count mismatch is an error |
| +- `internal/host/unitops.go` `systemctlRestartUnit`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl restart <unit>, only for a unit root bound to the route through Bind after a successful reload and an exact EnvironmentFiles match |
| +- `internal/host/unitsettle.go` `systemctlVerb`: authority, task B3,J1,J4. Basis: root-input |
| +- `internal/host/unitsettle.go` `systemdUnits.JournalTail`: authority, task B3,J1,J4. Basis: root-input |
| +- `internal/host/unitsettle.go` `systemdUnits.Show`: authority, task B3,J1,J4. Basis: root-input |
| +- `internal/instancectl/gvisorprobe.go` `Server.runGVisorProbe`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Task 6 fix round 1, applying the controller rulings: serialized probe construction uses root random nonce/fixed paths, root-only O_EXCL fixture, abstract listener, typed verified bundle/unit and context recheck. Read bounded root-owned nonce-bound output and the guest socket handshake; inspect kernel/proc runtime and limits while guest waits. Termination uses inactive/not-loaded state, no job/PIDs and empty cgroup, never per-command stop-post records. Keep the prior pass during the run and publish report plus runtime identity once, after cleanup; any failed attempt invalidates it and records the bounded diagnostic. A private package-test-only operations struct substitutes paths, executable preparation and output opening; production keeps GVisorProbePaths, fixed output/procfs, ensureExe and execsandbox.OpenRootFile. No new tenant-controlled path, launch/source/database read, or runtime-state read. CI fix: route serialized nonce fixture/output cleanup through existing pinned removeGenFiles owner with closed gVisor selectors and fixed probe paths. Existing reads and stop proof unchanged; no new raw removal owner.;rev3=census-ruling-gvisor-probe-diag;basis=Diagnostic only: the failure dump runs journalctl for the fixed probe unit only once a start was asked for, with --since=@<this attempt's start time>, so it no longer replays earlier attempts; a failure before the start logs this attempt's own fail line (taken before the start-up mount lines are prepended) instead. No new path, input or systemctl verb; probe steps unchanged. |
| +- `internal/instancectl/server.go` `type Server`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read;rev3=census-ruling-agent-start-demo-3;basis=Retain the snapshot supervisor in instance-control state; no new request-selected path. Census read-site delta: unchanged (1).;rev3=census-ruling-gvisor-demos;basis=Retain Task 1 mode/error/readiness fields, baseline/runtime callbacks, Task 4 per-host validated staged descriptors and root-selected probe nonce. Fix round 1 adds a private writer-operation seam assigned only in package tests, after the unchanged GVisorID admission check; production defaults still call the same checked constructor, WriteRootfs, WriteBundle and verifier. No new direct read or request-controlled callback. Task 5: private injected removal seam for unprivileged tests; production default removes only root-derived bundle and skeleton after both-family proof inside existing start fence. No new request field or agent-selected unit. Task 6: Retain serialized probe nonce, runtime-set identity verifier/token, fixed claims flag, bundle discovery root, and private unprivileged identity seam. No request-controlled callback or path; existing declaration read-site classification unchanged. Task 6 fix round 1: private gvisorProbeTestOps is set only in package tests; production defaults retain all fixed paths and the checked root output opener. No externally supplied callback or new direct read. Final R1 P2: retain fixed skeleton parent and concurrent per-instance cleanup refusals; no direct read or external configuration field. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.;rev3=census-ruling-same-box-edge-fence;basis=Field declarations only: NFT (the nft runner; nil never loads the fence), EdgeFenceOff (host.env CARLOS_EDGE_FENCE=off), and under the existing denyMu/mu: fenceAddrs, fenceReason, fenceRetry, denyApplied. No read added. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/systemd/command.go:Cmd.run`: reads +file:CommandContext; written legacy, accepted-legacy, frozen |
| +- new `internal/systemd/command.go:Command`: reads +file:Command; written legacy, accepted-legacy, frozen |
| +- new `internal/systemd/command.go:bounded`: reads +file:CommandContext; written legacy, accepted-legacy, frozen |
| +- reads `internal/activator/backend_unit.go:UnitBackend.systemctl`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/activator/control.go:systemctlControlGroup`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/activator/control.go:systemctlUnitMainExit`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/activator/control.go:systemctlUnitState`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/activator/control.go:systemctlUnitsListed`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/demobuild/unit.go:var systemctl`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/hairpin/native_linux.go:MainProcess`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/host/claimfilesseed_delegation_linux.go:filesSeedEdgePID`: +file:Command, -file:CommandContext; keeps authority, task C,J4 |
| +- reads `internal/host/claimjournal_migration_linux.go:var claimSystemctl`: +file:Command, -file:CommandContext; keeps authority, task C,G,J4 |
| +- reads `internal/host/claimlaunch_production.go:claimLaunchFor`: +file:Command, -file:CommandContext; keeps authority, task C,D,J4 |
| +- reads `internal/host/claimstop_production.go:NewProductionClaimStopHandler`: +file:Command, -file:CommandContext; keeps authority, task C,J4 |
| +- reads `internal/host/claimstop_writers_linux.go:agentUnitCgroup`: +file:Command, -file:CommandContext; keeps authority, task C,G,J4 |
| +- reads `internal/host/claimstop_writers_linux.go:rootStopAgentCgroup`: +file:Command, -file:CommandContext; keeps authority, task C,J4 |
| +- reads `internal/host/claimunit_socket_migration_linux.go:captureProductionClaimUnitSocket`: +file:Command, -file:CommandContext; keeps authority, task E2 |
| +- reads `internal/host/dbreads_linux.go:dbReadUnits`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/host/egress_source.go:systemctlOutput`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/host/group_maintenance_verbs_linux.go:maintenanceEdgeProcess`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/host/restartwatch.go:platformUnitRestarts`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/host/rootgeneration_services_linux.go:generationServiceShow`: +file:Command, -file:CommandContext; keeps authority, task E2 |
| +- reads `internal/host/runscensure.go:runscSystemctl`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/instancectl/hairpin.go:newHairpinResetServer`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/instancectl/peer_linux.go:systemdEdgeMainPID`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| +- reads `internal/instancectl/server.go:runWithClaim`: +file:Command ×2, -file:CommandContext; keeps authority, task C,D,G |
| +- reads `internal/ops/ops.go:systemdDaemonReload`: +file:Command, -file:CommandContext; keeps legacy, task accepted-legacy |
| + |
| +Seal: `1610abfc476fe45d259494242243756dac9cfec49cdd7f7f7b238329392241a1` → `16cae3931aadfa57a5293d69becf318645681400777cc08972cf08eb449c2457`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-bounded-systemctl.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-bounded-systemctl-R2-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-bounded-systemctl-R2-fix.md| new file mode 100644 |
| index 000000000..0edb17051 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CHECK-BRIEF-bounded-systemctl-R2-fix.md |
| @@ -0,0 +1,28 @@ |
| +# Scoped check: bounded-systemctl, after round 2 (not a review round) |
| + |
| +Repo carlos/platform, branch `bounded-systemctl` (tip in the prompt). |
| +Round 2 (`docs/superpowers/reviews/FINDINGS-bounded-systemctl-R2.md`) ended |
| +READY AFTER FIXES with two P2s in round-1 families; stopping rule 2 |
| +applied and Paul chose the centralized fix (2026-11-17). The fix is commit |
| +0fa550f8, census 9b22c61f. AGENTS.md rule 1: the review does not reopen; |
| +root behaviour and the census are checked. Scope: `git show 0fa550f8` |
| +and the census card `docs/superpowers/notes/census-proposal-bounded-systemctl.md` |
| +(only systemdUnits.Show's claim changed since round 2). |
| + |
| +Check: |
| +1. Each round-2 P2: resolved, partly, not. |
| +2. Settle: a deadline reached through temporary observation failures |
| + returns one error that is both UnitNotUpError (errors.As) and |
| + Temporary(). Through adopt: rollback restart selected (process |
| + replaced), version not poisoned. An observed failure (failed state, |
| + wrong executable, not ready) is non-temporary as before. Any path where |
| + a genuinely broken build is now retried forever, or a plain start is |
| + used after a rollback? |
| +3. Guard: one complete AST traversal (function literals, methods, |
| + package-level var initializers, init). Any remaining bypass form? |
| +4. Census: verdict for systemdUnits.Show and the internal/host and |
| + internal/systemd envelopes at this tip, citing lines read. |
| + |
| +Answer each: OK, or a finding with file:line, failure scenario and fix, |
| +marked P1 or P2. End with exactly one line: CHECK PASSED, or CHECK FAILED |
| +with the P1s. Do not edit files, spawn reviewers or run full suites. |
diff --git a/docs/superpowers/reviews/CHECK-bounded-systemctl-R2-fix.md b/docs/superpowers/reviews/CHECK-bounded-systemctl-R2-fix.md| new file mode 100644 |
| index 000000000..c7e3b2db7 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CHECK-bounded-systemctl-R2-fix.md |
| @@ -0,0 +1,33 @@ |
| +Reviewed `fe8da668241e9c3c2d09eec6ab6184f51df98eea`, limited to fix `0fa550f8` and census update `9b22c61f`. This is the scoped post-R2 check, not another review round. No P1 or P2 findings. |
| + |
| +1. **Round-2 P2s — OK, both resolved.** |
| + |
| + The observation-timeout fix preserves both classifications: `errors.As` reaches `*release.UnitNotUpError`, and `Temporary()` returns true. See [unitsettle.go:190](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:190). |
| + |
| + The guard now visits calls throughout the file, including function literals, methods, package initializers and `init`. The original package-level function-literal counterexample and three related cases are included in [guard_test.go:126](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/guard_test.go:126). |
| + |
| +2. **Settle and adoption — OK.** |
| + |
| + A deadline reached while `Show` fails returns the combined error at [unitsettle.go:233](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:233). Adoption independently checks temporary classification and not-up classification at [adopt.go:1976](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/release/adopt.go:1976). Consequently, it does not poison the version and selects rollback restart at [adopt.go:2066](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/release/adopt.go:2066). |
| + |
| + The recovery still calls `ResetFailed` followed by `Restart`, replacing the process: [legacyrestart.go:86](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/legacyrestart.go:86). The selected root recovery also dispatches to rollback restart: [rootrestart.go:529](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/rootrestart.go:529). |
| + |
| + Observed failed states and restart evidence remain non-temporary at [unitsettle.go:253](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:253). Wrong-executable and not-ready deadline verdicts remain non-temporary at [unitsettle.go:296](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:296). I found no newly introduced path that retries an observed broken build indefinitely or substitutes plain start for rollback restart. Persistent observation failure remains retryable by design. |
| + |
| + The new [adoption regression:102](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/settle_verdict_adopt_test.go:102) checks rollback selection, absence of plain start, restored first-route version and continued adoption for the second route. |
| + |
| +3. **Guard traversal — OK.** |
| + |
| + Binding collection and invocation checking each traverse the complete file at [guard_test.go:255](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/guard_test.go:255) and [guard_test.go:275](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/guard_test.go:275). Neither excludes nested function literals or methods. No enclosing-declaration bypass remains. |
| + |
| + This remains a bounded syntax check, not general data-flow analysis. Function-produced strings and cross-package values remain outside its documented folding contract at [guard_test.go:54](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/guard_test.go:54). |
| + |
| +4. **Census — OK; approve all three scoped entries.** |
| + |
| + - **`systemdUnits.Show`: approve**, retaining authority classification B3,J1,J4. Lines 61–68 preserve the query properties, parser and wrapped error. The revised claim accurately describes the downstream settle classification. |
| + - **`internal/host` envelope: approve.** Reviewed the new error type and methods, plus the changed deadline branch at lines 181–238. No new read, executable, caller-controlled path or weakened authorization check is introduced. |
| + - **`internal/systemd` envelope: approve.** This fix changes only guard tests; production execution remains unchanged. Reviewed the guard changes and production execution at [command.go:124](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/command.go:124). |
| + |
| +Focused tests could not start: Go attempted to update `go.mod` on the read-only filesystem. Go/census diff whitespace checks passed. No files were changed, reviewers spawned or full suites run. |
| + |
| +CHECK PASSED |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/FINDINGS-bounded-systemctl-R1.md b/docs/superpowers/reviews/FINDINGS-bounded-systemctl-R1.md| new file mode 100644 |
| index 000000000..c9207e88c |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/FINDINGS-bounded-systemctl-R1.md |
| @@ -0,0 +1,140 @@ |
| +Reviewed `origin/main...f0283ee4fccf746079d4c4cc97de0a4810f9fdc3`, base `7e50962dd68738bf9fc77cd49e6e73032ce0148b`. Round 1 of 3. The requested tip adds only the brief to the commit named inside it. |
| + |
| +1. **P1 — A timed-out restart can leave the new process running after rollback restores the old symlink.** |
| + Location: [agent.go:5574](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5574), [unitsettle.go:106](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:106). |
| + |
| + Killing `systemctl` does not cancel its systemd job. If systemd starts the new build but the client remains stuck awaiting completion, the helper returns `TimeoutError`. In legacy adoption, that error reaches [adopt.go:1976](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/release/adopt.go:1976): adoption restores the previous symlink, but selects the stronger rollback restart only for `UnitNotUpError` at line 2066. A `TimeoutError` instead takes the ordinary start callback. `systemctl start` succeeds without replacing an already-running new process. The running executable and restored symlink can therefore disagree after the rollback. |
| + |
| + The void `systemctlTryRestart` path at [agent.go:5549](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5549) also logs the newly possible timeout and lets adoption continue without establishing the job’s outcome. |
| + |
| + **Invariant / fault family:** a client timeout is an unknown mutation outcome; rollback or successful adoption must establish which process actually runs. |
| + |
| + **Fix:** handle an ambiguous restart outcome explicitly. Reconcile the outstanding job and running invocation before completing adoption or rollback; a rollback must verify that the restored executable runs. Preserve existing authorization and operator-stop checks. Add a regression where the new process starts, the client times out, and a plain subsequent `start` would be a no-op. |
| + |
| +2. **P2 — Two paths turn a temporary observation failure into a verdict against the build.** |
| + Locations: [converge.go:1043](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/caps/converge.go:1043), [unitsettle.go:62](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:62). |
| + |
| + `Ops.systemctl` formats the new timeout using `%v`. Consequently, `caps.Restart → adoptHost` loses `Temporary()`, and adoption poisons the version for the remainder of the pass. |
| + |
| + Separately, `systemdUnits.Show` preserves the timeout, but `settleUnit` converts it into `UnitNotUpError` at [unitsettle.go:205](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:205). One query consuming the default 30-second settle window therefore triggers rollback, version poisoning and the not-up recovery path without evidence that the new process failed. The helper’s temporary classification does not survive that conversion. |
| + |
| + **Invariant / fault family:** inability to obtain systemd’s answer must remain distinguishable from evidence that a build is unhealthy. |
| + |
| + **Fix:** wrap the caps error with `%w`. Preserve a temporary, unknown-observation outcome when settling expires because queries failed. Keep real failed-state, wrong-executable and readiness failures distinct. Test both paths through adoption, including the poison decision. |
| + |
| +3. **P2 — The 18-minute per-command bound does not provide the stated apply/recovery budget.** |
| + Location: [systemapply.go:204](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/systemapply.go:204). |
| + |
| + Each call receives a fresh 18 minutes and a detached context. The update unit’s 20-minute limit covers the entire apply, including earlier draining and work. For example, after a 150-second drain, a hung command’s helper deadline falls after the update unit’s deadline. Systemd kills the apply before this helper returns and initiates the claimed rollback. Recovery uses the same helper despite its own **13-minute** unit limit. |
| + |
| + Thus “18 minutes is below 20 minutes” does not establish the stated behavior. It also leaves ordinary control calls such as `daemon-reload` with the edge restart’s extended allowance. |
| + |
| + **Invariant / fault family:** operation deadlines must fit within the remaining enclosing operation budget, including recovery work. |
| + |
| + **Fix:** carry an enclosing apply/recovery deadline into the command seam, distinguish the operation requiring the extended allowance, and define what happens when insufficient budget remains. Verify the complete ordered unit dependencies and reserve time for the intended failure handling. Add budget tests covering elapsed pre-command work and recovery’s shorter limit. |
| + |
| +4. **P2 — The guard permits unbounded local shell invocations.** |
| + Location: [guard_test.go:121](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/guard_test.go:121). |
| + |
| + The matcher accepts only exact program-name literals or strings ending in `/systemctl` or `/journalctl`. This bypass passes: |
| + |
| + ```go |
| + exec.Command("sh", "-c", "systemctl restart carlos-edge.service").Run() |
| + ``` |
| + |
| + So does a shell command held in a variable. Constant concatenation such as `"system" + "ctl"` also escapes the literal check. The fixture explicitly accepts `"systemctl show"` without distinguishing a message from executable shell text. |
| + |
| + **Invariant / fault family:** the guard must enforce bounded execution across supported invocation forms. |
| + |
| + **Fix:** inspect executable call sites and local shell-command arguments, resolve constant expressions, and add negative fixtures for shell execution, variables and concatenation. Preserve a narrow distinction for `grouproll/box.go`, which constructs a remote command; its existence does not justify exempting all shell-command strings. |
| + |
| +5. **P2 — `Detached()` bypasses the host-context ratchet.** |
| + Location: [command.go:82](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/command.go:82). |
| + |
| + The new host call sites create detached contexts through another package. The classifier at [scan_test.go:491](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/codehealth/scan_test.go:491) counts only direct `context.Background` and `context.TODO` uses in host packages. None of these new detached sites counts, and future callers can use the same wrapper without raising the metric. |
| + |
| + The calls previously had no context, so this is not removal of an existing cancellation guarantee. It is nevertheless a new way around the measurement boundary. |
| + |
| + **Invariant / fault family:** moving context creation behind a helper must not hide detached host operations from the ratchet. |
| + |
| + **Fix:** pass caller contexts where available. For deliberately context-free interfaces, either use explicitly justified, counted contexts at the call sites or teach the classifier to count `systemd.Detached` there, with fixtures and an explicit reviewed allowance. |
| + |
| +No P3 findings. |
| + |
| +The prober change is sound on inspection: [prober.go:143](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/edge/prober.go:143) applies the effective probe timeout, including the two-second fallback, and [upstreamdial.go:51](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/edge/upstreamdial.go:51) retains `upstreamguard.Dialer`. Its control hook still rejects link-local addresses before calling the test hook or connecting. |
| + |
| +The 30-second query bound is a reasonable finite ceiling, subject to finding 2. Five minutes covers the simple shipped-unit timings cited in the helper, but those timings cannot prove every job completes within five minutes: queued dependencies and operator-supplied named units also matter. Correct handling of an unknown outcome is therefore essential. |
| + |
| +The new process tests use fake executables, including replacement of the absolute-path program. They cover helper killing and error shape, but not the caller-level rollback and classification failures above. The prober test exercises the dial lifetime independently of the HTTP request timeout. Removing the dialer timeout would make that test fail; removing the helper deadline would make its hung-process tests fail to return promptly. |
| + |
| +`git diff --check` passed. I attempted `GOFLAGS=-mod=mod GOPROXY=off go test ./internal/systemd -count=1`, but Go could not create its work directory in the read-only sandbox. No tests executed. I ran no full suites and changed no files. |
| + |
| +The census constructor name is acceptable. The scanner deliberately recognizes `Command` conservatively, and retaining caller sites preserves their existing authority obligations. The new helper’s implementation is also covered by its own entry and envelope. This does not conceal the implementation change. |
| + |
| +The following verdicts cover all **47 units and nine envelopes** on the card. “Approve” retains the recorded disposition and basis. “Reject” withholds approval for this implementation because of the cited finding; it does not propose dropping or downgrading the unit’s existing authority classification. |
| + |
| +| Unit and source read | Recorded disposition | Verdict and basis | |
| +|---|---|---| |
| +| `Ops.query` — [converge.go:1060](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/caps/converge.go:1060) | authority E4,J1,J4 | **Approve.** Same query arguments and conservative false-on-error behavior. | |
| +| `Ops.systemctl` — [converge.go:1036](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/caps/converge.go:1036) | authority E4,J1,J4 | **Reject.** Findings 1–2 affect restart and adoption outcomes. | |
| +| `unitsAreActive` — [adopt_advice.go:49](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/adopt_advice.go:49) | diagnostic H3 | **Approve.** Same diagnostic query and host-derived arguments. | |
| +| `systemctlStartUnit` — [agent.go:5695](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5695) | legacy | **Reject.** Finding 1: this start is insufficient to resolve the newly ambiguous rollback outcome. | |
| +| `systemctlTryRestart` — [agent.go:5548](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5548) | legacy | **Reject.** Finding 1: timeout is swallowed without establishing the restart outcome. | |
| +| `systemctlTryRestartUnit` — [agent.go:5573](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5573) | legacy | **Reject.** Finding 1. | |
| +| `systemctl` — [bootstrap.go:851](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/bootstrap.go:851) | legacy | **Approve.** Same launch-plan arguments; errors still stop bootstrap. | |
| +| `adoptTimerActive` — [probes.go:44](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:44) | legacy | **Approve.** Same fixed timer query and parser. | |
| +| `configPathActive` — [probes.go:62](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:62) | legacy | **Approve.** Same fixed path-unit query and parser. | |
| +| `restartPathActive` — [probes.go:81](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:81) | legacy | **Approve.** Same fixed path-unit query and parser. | |
| +| `systemUpdatePathActive` — [probes.go:95](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:95) | legacy | **Approve.** Same fixed path-unit query and parser. | |
| +| `productionSysOps` — [systemapply.go:216](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/systemapply.go:216) | authority D,F,J4 | **Reject.** Finding 3: the claimed bounded failure/recovery behavior is not established. | |
| +| `systemctlProbe` — [systemunits.go:326](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/systemunits.go:326) | legacy | **Approve.** Same arguments, stdout and returned error. | |
| +| `daemonReload` — [unitops.go:190](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitops.go:190) | legacy | **Approve.** Fixed reload command; failure remains an error. | |
| +| `probeUnits` — [unitops.go:139](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitops.go:139) | legacy | **Approve.** Same properties and positional parser; count validation remains. | |
| +| `systemctlRestartUnit` — [unitops.go:201](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitops.go:201) | legacy | **Approve.** Existing bound-unit delivery checks remain; timeout is returned as failure. | |
| +| `systemctlVerb` — [unitsettle.go:105](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:105) | authority B3,J1,J4 | **Reject.** Finding 1: restart completion assumptions need repair. | |
| +| `systemdUnits.JournalTail` — [unitsettle.go:74](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:74) | authority B3,J1,J4 | **Approve.** Same journal selection; no added input or execution authority. Partial output can still be returned on error. | |
| +| `systemdUnits.Show` — [unitsettle.go:61](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:61) | authority B3,J1,J4 | **Reject.** Finding 2: its timeout becomes an unsupported unhealthy-build verdict. | |
| +| `Server.runGVisorProbe` — [gvisorprobe.go:154](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/gvisorprobe.go:154) | legacy | **Approve.** Fixed unit, attempt-specific journal window and five-second diagnostic context remain; cleanup proof is unchanged. | |
| +| `type Server` — [server.go:180](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/server.go:180) | legacy | **Approve.** Journal seam declaration only; no request-controlled callback. | |
| +| `Command` — [command.go:108](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/command.go:108) | new legacy | **Approve.** Conservative census site retained; constructor stores the closed program selector and arguments. | |
| +| `bounded` — [command.go:170](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/command.go:170) | new legacy | **Approve.** Existing executable choices, argv and environment are preserved through the reviewed callers; caller context and finite deadline reach `exec.CommandContext`. | |
| +| `UnitBackend.systemctl` — [backend_unit.go:104](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/backend_unit.go:104) | legacy | **Approve.** Same seam, verb, unit and caller context. | |
| +| `systemctlControlGroup` — [control.go:200](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:200) | legacy | **Approve.** Same property; errors remain errors. | |
| +| `systemctlUnitMainExit` — [control.go:167](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:167) | legacy | **Approve.** Same four properties and parser. | |
| +| `systemctlUnitState` — [control.go:121](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:121) | legacy | **Approve.** Same state/invocation query; no error-to-success conversion. | |
| +| `systemctlUnitsListed` — [control.go:144](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:144) | legacy | **Approve.** Same read-only listing and glob. | |
| +| `var systemctl` — [demobuild/unit.go:78](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/demobuild/unit.go:78) | legacy | **Approve.** Absolute executable, fixed environment and capped output remain. | |
| +| `MainProcess` — [native_linux.go:78](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/hairpin/native_linux.go:78) | legacy | **Approve.** Same fixed edge query and kernel identity binding. | |
| +| `filesSeedEdgePID` — [claimfilesseed_delegation_linux.go:19](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimfilesseed_delegation_linux.go:19) | authority C,J4 | **Approve.** Fixed edge query, three-second deadline and PID checks remain. | |
| +| `var claimSystemctl` — [claimjournal_migration_linux.go:42](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimjournal_migration_linux.go:42) | authority C,G,J4 | **Approve.** Same caller arguments, context and output/error contract. | |
| +| `claimLaunchFor` — [claimlaunch_production.go:93](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimlaunch_production.go:93) | authority C,D,J4 | **Approve.** Claim-unit runner wiring preserves authorization and caller context. | |
| +| `NewProductionClaimStopHandler` — [claimstop_production.go:49](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimstop_production.go:49) | authority C,J4 | **Approve.** Authentication query remains fixed and bounded at three seconds; errors refuse. | |
| +| `agentUnitCgroup` — [claimstop_writers_linux.go:388](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimstop_writers_linux.go:388) | authority C,G,J4 | **Approve.** Existing deadline and local-path checks remain. | |
| +| `rootStopAgentCgroup` — [claimstop_writers_linux.go:433](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimstop_writers_linux.go:433) | authority C,J4 | **Approve.** Same containment properties and fail-closed parser. | |
| +| `captureProductionClaimUnitSocket` — [claimunit_socket_migration_linux.go:86](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimunit_socket_migration_linux.go:86) | authority E2 | **Approve.** PID validation, peer binding and socket identity recheck remain. | |
| +| `dbReadUnits` — [dbreads_linux.go:20](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/dbreads_linux.go:20) | legacy | **Approve.** Fixed read-only glob and caller context remain. | |
| +| `systemctlOutput` — [egress_source.go:386](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/egress_source.go:386) | legacy | **Approve.** Same argument seam; upstream unit validation remains. | |
| +| `maintenanceEdgeProcess` — [group_maintenance_verbs_linux.go:166](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/group_maintenance_verbs_linux.go:166) | legacy | **Approve.** Absolute path, fixed environment, `/` working directory, one-second context and bounded output remain. | |
| +| `platformUnitRestarts` — [restartwatch.go:258](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/restartwatch.go:258) | legacy | **Approve.** Fixed diagnostic query and existing shorter deadline remain. | |
| +| `generationServiceShow` — [rootgeneration_services_linux.go:108](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/rootgeneration_services_linux.go:108) | authority E2 | **Approve.** Same properties and error refusal before trust decisions. | |
| +| `runscSystemctl` — [runscensure.go:36](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/runscensure.go:36) | legacy | **Approve.** Same caller-selected fixed operations and context. | |
| +| `newHairpinResetServer` — [instancectl/hairpin.go:324](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/hairpin.go:324) | legacy | **Approve.** Runner wiring only; existing hairpin checks remain. | |
| +| `systemdEdgeMainPID` — [peer_linux.go:99](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/peer_linux.go:99) | legacy | **Approve.** Fixed edge query, three-second deadline and authentication refusal remain. | |
| +| `runWithClaim` — [server.go:315](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/server.go:315) | authority C,D,G | **Approve.** Systemctl retains caller context; journal execution moves to a dedicated fixed-program seam. No added request-selected executable. | |
| +| `systemdDaemonReload` — [ops.go:232](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/ops/ops.go:232) | legacy | **Approve.** Fixed command and existing one-minute deadline remain. | |
| + |
| +Envelope verdicts include the changed functions cited above and their relevant consumers: |
| + |
| +| Envelope | Verdict | |
| +|---|---| |
| +| `internal/activator` | **Approve.** Same command inputs and state/error parsing. | |
| +| `internal/caps` | **Reject.** Findings 1–2 affect the daemon restart/restore path. | |
| +| `internal/demobuild` | **Approve.** Fixed execution environment and output limits preserved. | |
| +| `internal/edge` | **Approve.** Dial bound added without weakening destination refusal. | |
| +| `internal/hairpin` | **Approve.** Fixed systemd query and process identity verification preserved. | |
| +| `internal/host` | **Reject.** Findings 1–3 affect adoption, settling and system recovery. Finding 5 also requires correction. | |
| +| `internal/instancectl` | **Approve.** Existing command selection, authentication and cleanup proofs preserved; journal seam remains diagnostic. | |
| +| `internal/ops` | **Approve.** Fixed reload with its original shorter deadline. | |
| +| `internal/systemd` | **Approve for census scope.** Closed executable selection and bounded execution add no untrusted input authority. Guard coverage and ratchet accounting still require findings 4–5 to be fixed. | |
| + |
| +NOT READY |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/FINDINGS-bounded-systemctl-R2.md b/docs/superpowers/reviews/FINDINGS-bounded-systemctl-R2.md| new file mode 100644 |
| index 000000000..103b7ec78 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/FINDINGS-bounded-systemctl-R2.md |
| @@ -0,0 +1,115 @@ |
| +- **R1 P1 — Resolved:** mutations receive no helper deadline, removing the newly introduced ambiguous restart outcome. |
| +- **R1 P2-2 — Partly resolved:** caps now wraps with `%w`; settle still discards the temporary classification. |
| +- **R1 P2-3 — Resolved:** the 18-minute apply/recovery class is removed. |
| +- **R1 P2-4 — Partly resolved:** ordinary function bodies are covered, but package-level function literals bypass the shell scan. |
| +- **R1 P2-5 — Resolved:** `Detached()` is removed; host call sites use commented, explicitly recorded `context.Background()` calls. |
| + |
| +Reviewed `origin/main...bd3a6f3b06d962b4ef4c1a616ad01f2a73d2bbf9`, with merge base `7e50962dd68738bf9fc77cd49e6e73032ce0148b`. `origin` points to amadan. Round 2 of 3. |
| + |
| +No P1 findings. Two P2 findings remain. |
| + |
| +1. **P2 — Preserve temporary observation failure without losing rollback recovery.** |
| + |
| + Locations: [unitsettle.go:64](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:64), [unitsettle.go:215](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:215). |
| + |
| + After a successful restart, a hung `show` consumes the settle window and returns `TimeoutError`. `settleUnit` then constructs a `UnitNotUpError`, retaining only the timeout’s text. Adoption consequently poisons that version for the rest of the pass at [adopt.go:1976](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/release/adopt.go:1976), despite having no evidence that the build failed. |
| + |
| + Keeping the not-up recovery is appropriate: it replaces the process after restoring the symlink. However, this does **not** require losing the temporary classification. Adoption checks `Temporary()` and `UnitNotUpError` independently; the latter selects the stronger recovery at [adopt.go:2066](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/release/adopt.go:2066). |
| + |
| + **Invariant / fault family:** inability to observe a process must remain distinguishable from evidence that its build is unhealthy, while rollback retains process-replacement recovery. |
| + |
| + **Fix:** for a settle deadline reached through temporary observation failures, return an error that remains discoverable as `UnitNotUpError` and reports `Temporary() == true`. Preserve ordinary non-temporary verdicts for observed failures. Extend the adoption regression to prove that a timed-out observation selects rollback restart, never plain start, and does not poison the version for the second route. The existing adoption test covers an observed failed unit only. |
| + |
| +2. **P2 — Package-level function literals bypass the local-shell guard.** |
| + |
| + Location: [guard_test.go:238](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/guard_test.go:238). |
| + |
| + The shell scan visits only top-level `*ast.FuncDecl` bodies. This package-level command seam escapes it: |
| + |
| + ```go |
| + var query = func() error { |
| + return exec.Command("sh", "-c", |
| + "systemctl show carlos-edge.service").Run() |
| + } |
| + ``` |
| + |
| + The literal scan also misses it: the command string is neither exactly a program name nor a path ending in that name. Package-level function literals are an established pattern here, including `claimSystemctl` and demobuild’s `systemctl`. |
| + |
| + A future query introduced in this form can therefore hang indefinitely while the guard passes. This is a source-level counterexample; I could not execute the fixture in this sandbox. |
| + |
| + **Invariant / fault family:** routing local systemctl/journalctl execution through the helper must not depend on whether its enclosing function is declared or assigned. |
| + |
| + **Fix:** apply the invocation check throughout the file, including function literals and package initializers, with the necessary local bindings. Add a negative fixture for the example above while retaining the narrow remote-script distinction. |
| + |
| +No P3 findings. |
| + |
| +Both remaining findings belong to fault families raised in R1. The repeated-family stopping rule applies before another patch. I recommend its centralized-invariant option: preserve recovery and temporary classification together at the settle error boundary, and inspect executable calls through one complete AST traversal. Cutting bounded settle observations would remove the first branch-specific failure; removing the guard would abandon a required deliverable. No further whole-branch review round is warranted without a P1; any production fix still needs its scoped root/census check. |
| + |
| +The following census verdicts cover all **48 units and nine envelopes**. “Approve” retains the recorded disposition and obligations. “Reject” withholds approval for the implementation; it does not downgrade its classification. |
| + |
| +| Unit and source read | Recorded disposition | Verdict and basis | |
| +|---|---|---| |
| +| `Ops.query` — [converge.go:1061](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/caps/converge.go:1061) | authority E4,J1,J4 | **Approve.** Same arguments and existing false-on-error behavior. | |
| +| `Ops.systemctl` — [converge.go:1037](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/caps/converge.go:1037) | authority E4,J1,J4 | **Approve.** Mutations retain their previous lifetime; `%w` preserves the underlying error. | |
| +| `unitsAreActive` — [adopt_advice.go:52](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/adopt_advice.go:52) | diagnostic H3 | **Approve.** Same host-derived query and positional-count refusal. | |
| +| `systemctlStartUnit` — [agent.go:5697](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5697) | legacy | **Approve.** Same start arguments and error handling; no added deadline. | |
| +| `systemctlTryRestart` — [agent.go:5548](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5548) | legacy | **Approve.** No newly introduced timeout reaches the existing log-and-continue path. | |
| +| `systemctlTryRestartUnit` — [agent.go:5574](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/agent.go:5574) | legacy | **Approve.** Same single unit argument and returned mutation error. | |
| +| `systemctl` — [bootstrap.go:852](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/bootstrap.go:852) | legacy | **Approve.** Existing arguments retained; mutations remain unbounded by the helper. | |
| +| `adoptTimerActive` — [probes.go:45](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:45) | legacy | **Approve.** Fixed timer query and existing parser retained. | |
| +| `configPathActive` — [probes.go:64](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:64) | legacy | **Approve.** Fixed path-unit query and parser retained. | |
| +| `restartPathActive` — [probes.go:84](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:84) | legacy | **Approve.** Fixed path-unit query and parser retained. | |
| +| `systemUpdatePathActive` — [probes.go:99](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/probes.go:99) | legacy | **Approve.** Fixed update-path query and parser retained. | |
| +| `productionSysOps` — [systemapply.go:205](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/systemapply.go:205) | authority D,F,J4 | **Approve.** Apply/recovery mutations retain prior behavior; query arguments and protected decisions are unchanged. | |
| +| `systemctlProbe` — [systemunits.go:327](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/systemunits.go:327) | legacy | **Approve.** Same stdout and error interface, with bounded queries. | |
| +| `daemonReload` — [unitops.go:192](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitops.go:192) | legacy | **Approve.** Fixed reload command, same error handling and lifetime. | |
| +| `probeUnits` — [unitops.go:140](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitops.go:140) | legacy | **Approve.** Same properties, positional parser and count-mismatch refusal. | |
| +| `systemctlRestartUnit` — [unitops.go:204](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitops.go:204) | legacy | **Approve.** Existing bound-unit delivery prerequisites remain; no helper deadline. | |
| +| `systemctlVerb` — [unitsettle.go:107](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:107) | authority B3,J1,J4 | **Approve.** Existing mutation arguments and error wrapping retained. | |
| +| `systemdUnits.JournalTail` — [unitsettle.go:75](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:75) | authority B3,J1,J4 | **Approve.** Same journal selection and output handling; no added read source. | |
| +| `systemdUnits.Show` — [unitsettle.go:61](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/unitsettle.go:61) | authority B3,J1,J4 | **Reject.** Finding 1: the newly bounded observation reaches settle’s non-temporary build verdict. | |
| +| `Server.runGVisorProbe` — [gvisorprobe.go:154](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/gvisorprobe.go:154) | legacy | **Approve.** Fixed unit, attempt-specific journal window and five-second diagnostic context retained; cleanup proof unchanged. | |
| +| `type Server` — [server.go:180](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/server.go:180) | legacy | **Approve.** Journal callback declaration only; no request-controlled callback introduced. | |
| +| `Cmd.run` — [command.go:124](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/command.go:124) | new legacy | **Approve.** Closed program selector; caller arguments, environment and directory retained; mutations use only the caller context. | |
| +| `Command` — [command.go:98](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/command.go:98) | new legacy | **Approve.** Constructor retains conservative caller census sites and introduces no externally selected executable. | |
| +| `bounded` — [command.go:172](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/systemd/command.go:172) | new legacy | **Approve.** Query deadline and pipe-wait bound reach execution; helper timeout is distinguishable from the caller’s cancellation. | |
| +| `UnitBackend.systemctl` — [backend_unit.go:104](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/backend_unit.go:104) | legacy | **Approve.** Sandbox launch gate, seam, arguments and caller context retained. | |
| +| `systemctlControlGroup` — [control.go:200](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:200) | legacy | **Approve.** Same property; observation failure remains an error. | |
| +| `systemctlUnitMainExit` — [control.go:167](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:167) | legacy | **Approve.** Same exit properties and parser. | |
| +| `systemctlUnitState` — [control.go:121](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:121) | legacy | **Approve.** Same state/invocation query; no error-to-success conversion. | |
| +| `systemctlUnitsListed` — [control.go:144](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/activator/control.go:144) | legacy | **Approve.** Same listing arguments and glob. | |
| +| `var systemctl` — [unit.go:78](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/demobuild/unit.go:78) | legacy | **Approve.** Absolute executable, fixed environment and capped combined output retained. | |
| +| `MainProcess` — [native_linux.go:78](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/hairpin/native_linux.go:78) | legacy | **Approve.** Fixed edge query and kernel identity binding retained. | |
| +| `filesSeedEdgePID` — [claimfilesseed_delegation_linux.go:19](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimfilesseed_delegation_linux.go:19) | authority C,J4 | **Approve.** Fixed edge query, three-second caller deadline and PID validation retained. | |
| +| `var claimSystemctl` — [claimjournal_migration_linux.go:42](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimjournal_migration_linux.go:42) | authority C,G,J4 | **Approve.** Same caller context, arguments and output; no new mutation deadline. | |
| +| `claimLaunchFor` — [claimlaunch_production.go:87](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimlaunch_production.go:87) | authority C,D,J4 | **Approve.** Authentication, delegation and fixed roots retained; execution callback preserves caller context. | |
| +| `NewProductionClaimStopHandler` — [claimstop_production.go:24](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimstop_production.go:24) | authority C,J4 | **Approve.** Three-second fixed-unit query, controller verification and peer authentication retained. | |
| +| `agentUnitCgroup` — [claimstop_writers_linux.go:388](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimstop_writers_linux.go:388) | authority C,G,J4 | **Approve.** Caller deadline and local-path validation retained. | |
| +| `rootStopAgentCgroup` — [claimstop_writers_linux.go:433](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimstop_writers_linux.go:433) | authority C,J4 | **Approve.** Fixed identity properties, deadline and containment parser retained. | |
| +| `captureProductionClaimUnitSocket` — [claimunit_socket_migration_linux.go:86](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/claimunit_socket_migration_linux.go:86) | authority E2 | **Approve.** Predecessor-unit query, peer proof and socket identity recheck retained. | |
| +| `dbReadUnits` — [dbreads_linux.go:20](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/dbreads_linux.go:20) | legacy | **Approve.** Fixed read-only listing; query failure remains an error. | |
| +| `systemctlOutput` — [egress_source.go:386](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/egress_source.go:386) | legacy | **Approve.** Same caller-selected arguments, output and context; existing validation boundaries remain. | |
| +| `maintenanceEdgeProcess` — [group_maintenance_verbs_linux.go:166](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/group_maintenance_verbs_linux.go:166) | legacy | **Approve.** Absolute executable, fixed environment/directory, one-second deadline, bounded output and process identity read retained. | |
| +| `platformUnitRestarts` — [restartwatch.go:258](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/restartwatch.go:258) | legacy | **Approve.** Fixed glob, existing deadline and nil-on-error handling retained. | |
| +| `generationServiceShow` — [rootgeneration_services_linux.go:108](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/rootgeneration_services_linux.go:108) | authority E2 | **Approve.** Same service properties; failed observation returns before parsing. | |
| +| `runscSystemctl` — [runscensure.go:36](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/host/runscensure.go:36) | legacy | **Approve.** Same arguments and caller context; no added executable choice. | |
| +| `newHairpinResetServer` — [hairpin.go:324](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/hairpin.go:324) | legacy | **Approve.** Existing runner replaced without changing arguments or authority. | |
| +| `systemdEdgeMainPID` — [peer_linux.go:99](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/peer_linux.go:99) | legacy | **Approve.** Fixed query and three-second deadline retained; no peer-controlled argument. | |
| +| `runWithClaim` — [server.go:315](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/instancectl/server.go:315) | authority C,D,G | **Approve.** Existing start guard remains installed; separate journal callback preserves the diagnostic’s arguments and context. | |
| +| `systemdDaemonReload` — [ops.go:232](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/ops/ops.go:232) | legacy | **Approve.** Fixed reload command and existing one-minute caller deadline retained. | |
| + |
| +| Re-pinned envelope | Verdict and basis | |
| +|---|---| |
| +| `internal/activator` | **Approve.** Changed runner and query functions cited above preserve launch checks and observation-error handling. | |
| +| `internal/caps` | **Approve.** Changed runners preserve mutation authorization and arguments; `%w` improves error propagation. | |
| +| `internal/demobuild` | **Approve.** Fixed executable/environment and output cap remain at [unit.go:78](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/demobuild/unit.go:78). | |
| +| `internal/edge` | **Approve.** [prober.go:137](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/edge/prober.go:137) applies the effective probe timeout; [upstreamdial.go:51](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/edge/upstreamdial.go:51) retains `upstreamguard`, whose refusal precedes connection and custom hooks. | |
| +| `internal/hairpin` | **Approve.** Fixed systemd identity query and kernel binding remain at [native_linux.go:78](/home/paulca/amadan.net/carlos/platform-bounded-systemctl/internal/hairpin/native_linux.go:78). | |
| +| `internal/host` | **Reject.** Finding 1 remains in the bounded-show-to-settle path. Other changed functions retain their existing arguments, validation, environments and mutation lifetimes. | |
| +| `internal/instancectl` | **Approve.** Journal rewiring is diagnostic only; start fencing, peer checks and probe cleanup remain intact. | |
| +| `internal/ops` | **Approve.** Existing reload deadline and command retained. | |
| +| `internal/systemd` | **Approve for census authority.** Production execution preserves the reviewed callers’ executable choices, arguments and environments. Finding 2 concerns guard coverage and remains a branch-level P2. | |
| + |
| +The focused command `GOFLAGS=-mod=mod GOPROXY=off go test ./internal/systemd -count=1` could not start: Go could not create its work directory on the read-only filesystem. No tests executed, and I ran no full suites. Diff whitespace checks passed for Go, census and ratchet changes; the full check reports five Markdown hard-break lines in the saved R1 review. I changed no files and spawned no reviewers. |
| + |
| +READY AFTER FIXES |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl-R2.md b/docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl-R2.md| new file mode 100644 |
| index 000000000..fa72343f2 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl-R2.md |
| @@ -0,0 +1,56 @@ |
| +# Review brief: branch bounded-systemctl, round 2 of 3 |
| + |
| +Repo carlos/platform, branch `bounded-systemctl` (tip in the reviewer's |
| +prompt). Under review: the diff `origin/main...<tip>` (base 7e50962). |
| +Authorities: `docs/superpowers/plans/2026-11-16-go-code-health.md` (batch 3), |
| +AGENTS.md ("The census", "Writing Go here", "Stopping rules"). |
| + |
| +You are the independent reviewer and the census reviewer (card: |
| +`docs/superpowers/notes/census-proposal-bounded-systemctl.md`, 48 claims; |
| +verdict per unit and envelope, citing lines read). Root-side. |
| + |
| +## Round 2 |
| + |
| +Earlier rounds: round 1, Astra, |
| +`docs/superpowers/reviews/FINDINGS-bounded-systemctl-R1.md` (NOT READY: one |
| +P1, four P2s). First give one line per round-1 P1 and P2: resolved, |
| +partly, or not. Carry unresolved ones forward at their severity, then add |
| +new findings. The verdict covers everything outstanding. |
| + |
| +What changed since round 1 (commits 888c4b88, c306f717, 6b4c47ea, f0e81caf): |
| +- **Scope cut (answers the P1 and P2-3):** only state-free verbs (show, |
| + is-active, list-units, cat, other read-only verbs) and journalctl get a |
| + 30 s bound. Every mutating verb (start, stop, restart, try-restart, |
| + reload, daemon-reload, the system apply and recovery) runs under the |
| + caller's context only, exactly as before the branch, through the helper |
| + so the guard sees it. The 5 min and 18 min classes are gone. Bounding job |
| + verbs is moved to a spec: amadan #1214. |
| +- **P2-2:** caps Ops.systemctl wraps with %w. The settle rule is kept as |
| + before: a show that fails until the deadline stays UnitNotUpError, so the |
| + not-up recovery (reset-failed + restart) replaces the process. A first |
| + attempt to make it an "unknown" outcome was reverted because rollback |
| + plus a plain start would recreate the P1 mismatch; that change is now |
| + part of #1214. Judge whether keeping the old rule is right for this |
| + branch. |
| +- **P2-4:** the guard folds constants and inspects local sh/bash/dash -c |
| + arguments, fmt.Sprintf command lines, vars and concatenation; grouproll's |
| + remote script is a named, checked exception. |
| +- **P2-5:** Detached() removed; context-free callers use an explicit, |
| + commented context.Background(), raising host-context by 17 sites, each |
| + with a `# raised: bounded-systemctl: ...` record line. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| +- **P2**: wrong or missing. Fixed without reopening this review (root and |
| + census changes in the fix still get a scoped check). |
| +- **P3**: clarity or polish. Follow-up list only. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix, and |
| +the invariant each breaks. Then the census verdicts. End with exactly one |
| +verdict: READY, READY AFTER FIXES, or NOT READY. In round 2 a NOT READY |
| +also says whether the P1s share one cause with round 1's, and whether |
| +cutting further would remove them. Do not edit files, spawn reviewers or |
| +run full suites. |
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl.md b/docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl.md| new file mode 100644 |
| index 000000000..f5e24d0ba |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-BRIEF-bounded-systemctl.md |
| @@ -0,0 +1,58 @@ |
| +# Review brief: branch bounded-systemctl, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `bounded-systemctl`, commit bfc764e62b5c69a441c4c2609ef26a6e33935374. |
| +Under review: the diff `origin/main...bfc764e62b5c69a441c4c2609ef26a6e33935374` (base 7e50962). |
| +Authorities: `docs/superpowers/plans/2026-11-16-go-code-health.md` (batch 3), |
| +AGENTS.md ("The census", "Writing Go here", "Stopping rules"). |
| + |
| +You are the independent reviewer and the census reviewer (card: |
| +`docs/superpowers/notes/census-proposal-bounded-systemctl.md`; verdict per |
| +unit and envelope, citing lines read). This is **root-side and |
| +termination-adjacent**: 45 systemctl/journalctl call sites across host, |
| +activator, caps, demobuild, hairpin, ops and instancectl now go through a |
| +new `internal/systemd` helper with timeouts (30 s read-only and journalctl, |
| +5 min job verbs, 18 min system apply/recovery), killed at the bound with a |
| +1 s WaitDelay; guard `TestSystemctlCallsAreBounded`; the edge prober's |
| +dial bounded at its 2 s probe timeout. |
| + |
| +## What to check |
| + |
| +1. Values: are 30 s / 5 min / 18 min right against the units' own |
| + TimeoutStartSec/TimeoutStopSec, the drain and recovery units, and the |
| + update unit's 20 min? Could any legitimate operation now be cut? |
| +2. Outcome changes the implementer lists: adopt restart past 5 min errors |
| + (rollback without poisoning the version); settle's `show` timing out |
| + counts "not up" and triggers rollback (left as the existing rule); system |
| + apply past 18 min fails and rolls back. Is each safe? Is any rollback now |
| + triggered by a slow-but-healthy systemd where it wasn't before? |
| +3. `systemd.Detached()` (context.Background() inside the helper) is used by |
| + host callers with no context. **It also hides those sites from the |
| + ratchet's host-context metric.** Is that a dodge of the ratchet (fault |
| + family: measurement boundary), and should those callers thread a context |
| + or count? |
| +4. The constructor is named `Command` so the census keeps counting the |
| + exec sites (otherwise 38 units would lose their only counted site and be |
| + retired). Is that sound census practice, or does it hide a change the |
| + census should see? Do all dispositions remain correct? |
| +5. Kill at the bound: does killing systemctl mid-job leave systemd's job |
| + running (it does: the job lives in PID 1)? Does any caller assume the |
| + job stopped when the call returns an error? |
| +6. The guard: catches exec of systemctl/journalctl by any spelling |
| + (exec.Command, CommandContext, sh -c, a path, a var)? Empty allowlist |
| + correct (grouproll/box.go builds a remote script, not a local call)? |
| +7. The prober dial: link-local refusal kept; 2 s right? |
| +8. Tests: fake systemctl on PATH only; would each fail on the old code. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| +- **P2**: wrong or missing. Fixed without reopening this review (root, |
| + termination and census changes in the fix still get a scoped check). |
| +- **P3**: clarity or polish. Follow-up list only. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix, and |
| +the invariant each breaks. Then the census verdicts. End with exactly one |
| +verdict: READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn |
| +reviewers or run full suites. |
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index 63edbb2a6..c901a2e5b 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -53,7 +53,6 @@ import ( |
| "io" |
| "net" |
| "net/http" |
| - "os/exec" |
| "strings" |
| "sync" |
| "time" |
| @@ -65,6 +64,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/upstreamguard" |
| ) |
| @@ -110,7 +110,7 @@ func (b *UnitBackend) systemctl(ctx context.Context, verb, unit string) error { |
| if b.Systemctl != nil { |
| return b.Systemctl(ctx, verb, unit) |
| } |
| - out, err := exec.CommandContext(ctx, "systemctl", verb, unit).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, verb, unit).CombinedOutput(ctx) |
| if err != nil { |
| return fmt.Errorf("systemctl %s %s: %v: %s", verb, unit, err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/activator/control.go b/internal/activator/control.go| index a4dc01826..c65391361 100644 |
| --- a/internal/activator/control.go |
| +++ b/internal/activator/control.go |
| @@ -10,6 +10,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // Control is what the exec backend needs from the root instance-control |
| @@ -118,7 +119,7 @@ var _ StagedExeControl = (*instancectl.Client)(nil) |
| type UnitState func(ctx context.Context, unit string) (active, invocation string, err error) |
| func systemctlUnitState(ctx context.Context, unit string) (string, string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ActiveState,InvocationID", unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ActiveState,InvocationID", unit).Output(ctx) |
| if err != nil { |
| return "", "", unitStateError(err) |
| } |
| @@ -141,7 +142,7 @@ func systemctlUnitState(ctx context.Context, unit string) (string, string, error |
| 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() |
| + out, err := systemd.Command(systemd.Systemctl, "list-units", "--all", "--plain", "--no-legend", "--no-pager", glob).Output(ctx) |
| if err != nil { |
| return "", unitStateError(err) |
| } |
| @@ -164,7 +165,7 @@ type MainExit struct { |
| } |
| func systemctlUnitMainExit(ctx context.Context, unit string) (MainExit, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus", unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus", unit).Output(ctx) |
| if err != nil { |
| return MainExit{}, unitStateError(err) |
| } |
| @@ -197,7 +198,7 @@ type CgroupEvents func(slice, unit string) (exists, populated bool, err error) |
| type ControlGroupOf func(ctx context.Context, unit string) (string, error) |
| func systemctlControlGroup(ctx context.Context, unit string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ControlGroup", "--value", unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ControlGroup", "--value", unit).Output(ctx) |
| if err != nil { |
| return "", unitStateError(err) |
| } |
diff --git a/internal/caps/converge.go b/internal/caps/converge.go| index 177d95bcd..d8305eb72 100644 |
| --- a/internal/caps/converge.go |
| +++ b/internal/caps/converge.go |
| @@ -10,6 +10,7 @@ package caps |
| import ( |
| "bytes" |
| + "context" |
| "errors" |
| "fmt" |
| "os" |
| @@ -19,6 +20,8 @@ import ( |
| "sort" |
| "strconv" |
| "strings" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| const ( |
| @@ -1035,9 +1038,10 @@ func (o Ops) systemctl(args ...string) error { |
| if o.Systemctl != nil { |
| return o.Systemctl(args...) |
| } |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + // Background: Ops.systemctl takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(context.Background()) |
| if err != nil { |
| - return fmt.Errorf("systemctl %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| + return fmt.Errorf("systemctl %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
| return nil |
| } |
| @@ -1058,7 +1062,8 @@ func (o Ops) query(args ...string) bool { |
| if o.Query != nil { |
| return o.Query(args...) |
| } |
| - return exec.Command("systemctl", args...).Run() == nil |
| + // Background: Ops.query takes no context; QueryTimeout is this query's deadline. |
| + return systemd.Command(systemd.Systemctl, args...).Run(context.Background(), nil, nil) == nil |
| } |
| // ensureUser creates the locked, home-less, nologin system user a host_role |
diff --git a/internal/caps/systemctl_error_test.go b/internal/caps/systemctl_error_test.go| new file mode 100644 |
| index 000000000..f9e408eba |
| --- /dev/null |
| +++ b/internal/caps/systemctl_error_test.go |
| @@ -0,0 +1,30 @@ |
| +package caps |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// Ops.systemctl wraps systemctl's error with %w, so a caller can still read |
| +// it: the exit status here, and a TimeoutError's Temporary() through |
| +// caps.Restart into adoption, which decides on it whether to poison a |
| +// version. A fake systemctl on PATH answers; the real one never runs. |
| +func TestOpsSystemctlKeepsTheErrorReadable(t *testing.T) { |
| + bin := t.TempDir() |
| + if err := os.WriteFile(filepath.Join(bin, "systemctl"), []byte("#!/bin/sh\necho \"Unit $2 not found.\"\nexit 5\n"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) |
| + err := Ops{}.systemctl("restart", "carlos-app@shop.example.com.service") |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) || ee.ExitCode() != 5 { |
| + t.Fatalf("err = %v, want systemctl's *exec.ExitError (exit 5) wrapped", err) |
| + } |
| + if !strings.Contains(err.Error(), "systemctl restart carlos-app@shop.example.com.service") || !strings.Contains(err.Error(), "not found") { |
| + t.Fatalf("err = %q, want the command and systemctl's words", err) |
| + } |
| +} |
diff --git a/internal/demobuild/unit.go b/internal/demobuild/unit.go| index ebecd28d9..8dbc86ea0 100644 |
| --- a/internal/demobuild/unit.go |
| +++ b/internal/demobuild/unit.go |
| @@ -9,7 +9,6 @@ import ( |
| "io/fs" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -18,6 +17,7 @@ import ( |
| "github.com/carlosframework/platform/internal/execsandbox" |
| "github.com/carlosframework/platform/internal/instancefs" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| var unitRoot = "/run/systemd/system" |
| @@ -76,12 +76,10 @@ func mountName(p string) string { |
| } |
| var systemctl = func(ctx context.Context, args ...string) (string, error) { |
| - c := exec.CommandContext(ctx, "/usr/bin/systemctl", args...) |
| - c.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "SYSTEMD_COLORS=0", "SYSTEMD_PAGER="} |
| var b limitedLog |
| - c.Stdout = &b |
| - c.Stderr = &b |
| - err := c.Run() |
| + c := systemd.Command(systemd.SystemctlAbsolute, args...) |
| + c.Env = []string{"PATH=/usr/bin:/bin", "LANG=C", "SYSTEMD_COLORS=0", "SYSTEMD_PAGER="} |
| + err := c.Run(ctx, &b, &b) |
| if err != nil { |
| err = fmt.Errorf("systemctl %v: %w: %s", args, err, strings.TrimSpace(string(b.b))) |
| } |
diff --git a/internal/edge/prober.go b/internal/edge/prober.go| index 4dc10dd7e..aa13e2429 100644 |
| --- a/internal/edge/prober.go |
| +++ b/internal/edge/prober.go |
| @@ -34,6 +34,7 @@ import ( |
| "fmt" |
| "io" |
| "log" |
| + "net" |
| "net/http" |
| "slices" |
| "sync" |
| @@ -129,17 +130,23 @@ type proberSet struct { |
| // newProberSet builds the set with hold.probe as the probe timeout (T in |
| // the readmission formula, spec §3), and hold.dialer, when set, as the |
| // probes' dialer, so a test's instrumented dialer sees the probes too; |
| -// unset (production), the probes dial with upstreamDialer, which refuses |
| -// link-local and IMDS addresses. A non-positive probe falls back to |
| -// probeTimeout: an unbounded probe would stall every tick behind one |
| -// black-holed upstream. |
| +// unset (production), the probes dial with probeDialer, which refuses |
| +// link-local and IMDS addresses and gives up a connect at the probe |
| +// timeout. A non-positive probe falls back to probeTimeout: an unbounded |
| +// probe would stall every tick behind one black-holed upstream. |
| func newProberSet(hold localHold) *proberSet { |
| + return newProberSetDialing(hold, net.Dialer{}) |
| +} |
| + |
| +// newProberSetDialing is newProberSet with base as the dialer probeDialer |
| +// starts from: a plain net.Dialer in production, a test's black hole. |
| +func newProberSetDialing(hold localHold, base net.Dialer) *proberSet { |
| if hold.probe <= 0 { |
| hold.probe = probeTimeout |
| } |
| dial := hold.dialer |
| if dial == nil { |
| - dial = upstreamDialer().DialContext |
| + dial = probeDialer(base, hold.probe).DialContext |
| } |
| return &proberSet{ |
| hosts: make(map[string]*hostProber), |
diff --git a/internal/edge/upstreamdial.go b/internal/edge/upstreamdial.go| index c9b081407..6c3d4c52c 100644 |
| --- a/internal/edge/upstreamdial.go |
| +++ b/internal/edge/upstreamdial.go |
| @@ -10,13 +10,10 @@ import ( |
| // upstreamDialer is the dialer for a TCP upstream when no test dialer is set |
| // (hold.dialer nil, as in production): the plain net.Dialer the transports |
| // used before, behind upstreamguard, which refuses link-local and IMDS |
| -// addresses after resolution and before connect. multiProxy and the prober |
| -// use it; tcpProxy uses tcpUpstreamDialer; unix sockets, backhaul hops and |
| -// tunnels use neither. multiProxy bounds each dial with a context deadline |
| -// (multiDialTimeout). The prober's dial is still unbounded: its |
| -// http.Client.Timeout and ResponseHeaderTimeout do not reach the dial, |
| -// since net/http strips the request's deadline before dialing. Bounding it |
| -// is follow-up work. |
| +// addresses after resolution and before connect. multiProxy uses it, and |
| +// bounds each dial with a context deadline (multiDialTimeout); tcpProxy |
| +// uses tcpUpstreamDialer and the prober probeDialer, which carry their own |
| +// connect bounds; unix sockets, backhaul hops and tunnels use none of them. |
| func upstreamDialer() *net.Dialer { |
| return upstreamguard.Dialer(net.Dialer{}) |
| } |
| @@ -39,3 +36,18 @@ const ( |
| func tcpUpstreamDialer() *net.Dialer { |
| return upstreamguard.Dialer(net.Dialer{Timeout: tcpUpstreamDialTimeout, KeepAlive: tcpUpstreamKeepAlive}) |
| } |
| + |
| +// probeDialer is the prober's dialer when no test dialer is set: base (a |
| +// plain net.Dialer in production) with a connect bound of the probe |
| +// timeout, behind upstreamguard, so the link-local refusal holds. The |
| +// bound has to be on the dialer: the prober's http.Client.Timeout and |
| +// ResponseHeaderTimeout end the request, but net/http dials outside the |
| +// request's deadline, so without it every tick against a black-holed |
| +// upstream leaves a dial behind for the kernel's connect timeout (about |
| +// two minutes on Linux). The probe timeout is the right size because the |
| +// spec gives a whole probe, connect through body, that long (probeTimeout, |
| +// 2 s): a connect that takes longer has already failed its probe. |
| +func probeDialer(base net.Dialer, timeout time.Duration) *net.Dialer { |
| + base.Timeout = timeout |
| + return upstreamguard.Dialer(base) |
| +} |
diff --git a/internal/edge/upstreamdial_test.go b/internal/edge/upstreamdial_test.go| index 672bf1bd0..b3a533013 100644 |
| --- a/internal/edge/upstreamdial_test.go |
| +++ b/internal/edge/upstreamdial_test.go |
| @@ -3,10 +3,12 @@ package edge |
| import ( |
| "context" |
| "errors" |
| + "net" |
| "net/http" |
| "net/http/httptest" |
| "net/http/httputil" |
| "strings" |
| + "syscall" |
| "testing" |
| "time" |
| @@ -163,3 +165,57 @@ func TestTCPUpstreamDialerIsBounded(t *testing.T) { |
| t.Fatalf("dial err = %v, want upstreamguard.ErrLinkLocal", err) |
| } |
| } |
| + |
| +// TestProberDialIsBounded: a probe whose connect never completes gives up |
| +// at the probe timeout. The prober's http.Client.Timeout ends the request |
| +// but not the dial, which net/http runs outside the request's deadline, so |
| +// without a dialer Timeout a black-holed upstream leaves a dial behind on |
| +// every tick for the kernel's two minutes. The black hole is a Control |
| +// hook that holds the connect until the dial's own context ends: the dial |
| +// gives up only if the dialer carries the bound. Nothing is connected. |
| +func TestProberDialIsBounded(t *testing.T) { |
| + const bound = 200 * time.Millisecond |
| + stop := make(chan struct{}) |
| + defer close(stop) |
| + gaveUp := make(chan time.Duration, 8) |
| + base := net.Dialer{ControlContext: func(ctx context.Context, _, _ string, _ syscall.RawConn) error { |
| + start := time.Now() |
| + select { |
| + case <-ctx.Done(): |
| + gaveUp <- time.Since(start) |
| + return ctx.Err() |
| + case <-stop: |
| + return errors.New("test over") |
| + } |
| + }} |
| + ps := newProberSetDialing(localHold{probe: bound}, base) |
| + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:9/", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if resp, err := ps.client.Do(req); err == nil { |
| + resp.Body.Close() |
| + t.Fatal("a black-holed probe answered") |
| + } |
| + select { |
| + case took := <-gaveUp: |
| + if took > bound+time.Second { |
| + t.Fatalf("the dial gave up after %s, want about the %s probe timeout", took, bound) |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the probe's dial is still connecting 5 s after its request ended: it has no bound") |
| + } |
| + |
| + // The bound keeps the link-local refusal in front of it. |
| + d := probeDialer(net.Dialer{}, bound) |
| + if d.Timeout != bound { |
| + t.Fatalf("probe dialer Timeout %v, want %v", d.Timeout, bound) |
| + } |
| + conn, err := d.DialContext(context.Background(), "tcp", "169.254.169.254:80") |
| + if conn != nil { |
| + conn.Close() |
| + } |
| + if !errors.Is(err, upstreamguard.ErrLinkLocal) { |
| + t.Fatalf("dial err = %v, want upstreamguard.ErrLinkLocal", err) |
| + } |
| +} |
diff --git a/internal/hairpin/native_linux.go b/internal/hairpin/native_linux.go| index 2fb9c409e..4537b119b 100644 |
| --- a/internal/hairpin/native_linux.go |
| +++ b/internal/hairpin/native_linux.go |
| @@ -18,6 +18,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -75,7 +76,7 @@ func Authenticate(ctx context.Context, conn net.Conn, p Process) error { |
| return Current(ctx, p) |
| } |
| func MainProcess(ctx context.Context) (Process, error) { |
| - raw, err := exec.CommandContext(ctx, "systemctl", "show", "carlos-edge.service", "--property=MainPID", "--property=LoadState").CombinedOutput() |
| + raw, err := systemd.Command(systemd.Systemctl, "show", "carlos-edge.service", "--property=MainPID", "--property=LoadState").CombinedOutput(ctx) |
| fields := map[string]string{} |
| for _, line := range strings.Split(string(raw), "\n") { |
| if k, v, ok := strings.Cut(line, "="); ok { |
diff --git a/internal/host/adopt_advice.go b/internal/host/adopt_advice.go| index dea7fa9df..9cdf30faf 100644 |
| --- a/internal/host/adopt_advice.go |
| +++ b/internal/host/adopt_advice.go |
| @@ -5,6 +5,7 @@ |
| package host |
| import ( |
| + "context" |
| "log" |
| "os/exec" |
| "os/user" |
| @@ -14,6 +15,7 @@ import ( |
| "github.com/carlosframework/platform/internal/caps" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // warnBackingMismatch reports hosts whose route claims exec backing |
| @@ -52,7 +54,8 @@ func unitsAreActive(hosts []string) map[string]bool { |
| for _, h := range hosts { |
| args = append(args, "carlos-app@"+h+".service") |
| } |
| - out, _ := exec.Command("systemctl", args...).Output() |
| + // Background: unitsAreActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, args...).Output(context.Background()) |
| return parseIsActiveBatch(out, hosts) |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 3283fd277..a9cd9b53b 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -165,7 +165,6 @@ import ( |
| "net" |
| "net/http" |
| "os" |
| - "os/exec" |
| "os/signal" |
| "path" |
| "path/filepath" |
| @@ -217,6 +216,7 @@ import ( |
| "github.com/carlosframework/platform/internal/rootstate" |
| "github.com/carlosframework/platform/internal/schedule" |
| "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -5546,7 +5546,8 @@ func makeStartRoute(reg *registry.Registry, startUnit func(unit string) error) f |
| // line; they simply have nothing here to restart, and pick the new version |
| // up on their next wake. |
| func systemctlTryRestart(host string) { |
| - out, err := exec.Command("systemctl", "try-restart", activator.UnitName(host)).CombinedOutput() |
| + // Background: systemctlTryRestart takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "try-restart", activator.UnitName(host)).CombinedOutput(context.Background()) |
| if err != nil { |
| log.Printf("adopt: try-restart carlos-app@%s: %v: %s (continuing)", host, err, strings.TrimSpace(string(out))) |
| } |
| @@ -5566,12 +5567,13 @@ func systemctlTryRestart(host string) { |
| // summary line per host; the exit status and systemctl's own words belong in |
| // the journal where an operator greps for the unit name. |
| // |
| -// The unit reaches exec.Command as ONE argv element, so there is no shell for |
| +// The unit reaches systemctl as ONE argv element, so there is no shell for |
| // a name to escape into; the shape rail lives at the write (registry's |
| // ValidUnitName), where a typo can still be reported to the person who typed |
| // it. |
| func systemctlTryRestartUnit(unit string) error { |
| - out, err := exec.Command("systemctl", "try-restart", unit).CombinedOutput() |
| + // Background: systemctlTryRestartUnit takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "try-restart", unit).CombinedOutput(context.Background()) |
| if err != nil { |
| log.Printf("adopt: try-restart %s: %v: %s", unit, err, strings.TrimSpace(string(out))) |
| return fmt.Errorf("try-restart %s: %w: %s", unit, err, strings.TrimSpace(string(out))) |
| @@ -5691,9 +5693,10 @@ func agentRollbackUnitRestart(reg *registry.Registry, sys unitSystem, optDir str |
| // nothing, and the caller's one summary line per host must say so while the |
| // exit status and systemd's own words stay in the journal under the unit |
| // name an operator would grep for. Same no-shell shape too: the unit reaches |
| -// exec.Command as ONE argv element. |
| +// systemctl as ONE argv element. |
| func systemctlStartUnit(unit string) error { |
| - out, err := exec.Command("systemctl", "start", unit).CombinedOutput() |
| + // Background: systemctlStartUnit takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "start", unit).CombinedOutput(context.Background()) |
| if err != nil { |
| log.Printf("adopt: start %s: %v: %s", unit, err, strings.TrimSpace(string(out))) |
| return fmt.Errorf("start %s: %w: %s", unit, err, strings.TrimSpace(string(out))) |
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go| index e5228f4ce..1020bc6ca 100644 |
| --- a/internal/host/bootstrap.go |
| +++ b/internal/host/bootstrap.go |
| @@ -10,9 +10,11 @@ |
| package host |
| import ( |
| + "context" |
| "github.com/carlosframework/platform/internal/cliflag" |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/hostenv" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "embed" |
| "encoding/json" |
| @@ -848,7 +850,8 @@ func bootstrapOwner(owner, group string) (int, int, error) { |
| } |
| func systemctl(args ...string) error { |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + // Background: systemctl takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(context.Background()) |
| if err != nil { |
| return fmt.Errorf("systemctl %s: %v: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/host/claimfilesseed_delegation_linux.go b/internal/host/claimfilesseed_delegation_linux.go| index c9d540795..773064cea 100644 |
| --- a/internal/host/claimfilesseed_delegation_linux.go |
| +++ b/internal/host/claimfilesseed_delegation_linux.go |
| @@ -6,10 +6,10 @@ import ( |
| "context" |
| "fmt" |
| "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| "net" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -19,7 +19,7 @@ import ( |
| func filesSeedEdgePID(ctx context.Context) (int, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - b, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", "carlos-edge.service").Output() |
| + b, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/host/claimjournal_migration_linux.go b/internal/host/claimjournal_migration_linux.go| index a62b5edb6..9064d0a62 100644 |
| --- a/internal/host/claimjournal_migration_linux.go |
| +++ b/internal/host/claimjournal_migration_linux.go |
| @@ -11,7 +11,6 @@ import ( |
| "fmt" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -19,6 +18,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostbox" |
| "github.com/carlosframework/platform/internal/safefile" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -40,7 +40,7 @@ type claimEdgeMaskRecord struct { |
| } |
| var claimSystemctl = func(ctx context.Context, args ...string) ([]byte, error) { |
| - return exec.CommandContext(ctx, "systemctl", args...).Output() |
| + return systemd.Command(systemd.Systemctl, args...).Output(ctx) |
| } |
| func claimEdgeMaskAnchor(token string) string { |
diff --git a/internal/host/claimlaunch_production.go b/internal/host/claimlaunch_production.go| index b4beebc41..3649a4f13 100644 |
| --- a/internal/host/claimlaunch_production.go |
| +++ b/internal/host/claimlaunch_production.go |
| @@ -4,7 +4,6 @@ import ( |
| "context" |
| "net/http" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strings" |
| @@ -13,6 +12,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostclaim" |
| execlease "github.com/carlosframework/platform/internal/hostexec" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // ClaimRootWithLaunch is the claim-mode root handler with the isolated |
| @@ -92,7 +92,7 @@ func claimLaunchFor(root ClaimRootHTTP, actor func(context.Context) (hostbox.Act |
| } |
| units := instancectl.ClaimUnits{ |
| Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| }, |
| CgroupRoot: "/sys/fs/cgroup", |
diff --git a/internal/host/claimstop_production.go b/internal/host/claimstop_production.go| index 883ce1896..176af8633 100644 |
| --- a/internal/host/claimstop_production.go |
| +++ b/internal/host/claimstop_production.go |
| @@ -7,7 +7,6 @@ import ( |
| "encoding/hex" |
| "net" |
| "net/http" |
| - "os/exec" |
| "os/user" |
| "strconv" |
| "strings" |
| @@ -15,6 +14,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostbox" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| type StopControllerReader interface { |
| @@ -49,7 +49,7 @@ func NewProductionClaimStopHandler(c ClaimStopCoordinator, j hostbox.StopKernelJ |
| authenticate := func(ctx context.Context, conn net.Conn) (StopPeer, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", "carlos-edge.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return StopPeer{}, err |
| } |
diff --git a/internal/host/claimstop_writers_linux.go b/internal/host/claimstop_writers_linux.go| index a9334e2b5..9c1a1b424 100644 |
| --- a/internal/host/claimstop_writers_linux.go |
| +++ b/internal/host/claimstop_writers_linux.go |
| @@ -8,7 +8,6 @@ import ( |
| "fmt" |
| "io/fs" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "reflect" |
| "sort" |
| @@ -22,6 +21,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/stopevidence" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // stopKernelRoots are the trees root observes. Production uses the real |
| @@ -388,7 +388,7 @@ func emptyContainmentAt(ctx context.Context, dir, name string) (string, error) { |
| func agentUnitCgroup(ctx context.Context) (string, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ControlGroup", "--value", "carlos-edge.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ControlGroup", "--value", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return "", err |
| } |
| @@ -433,7 +433,7 @@ func noProcessGroups(ctx context.Context, roots stopKernelRoots, host string, re |
| func rootStopAgentCgroup(ctx context.Context) (string, error) { |
| ctx, cancel := context.WithTimeout(ctx, 3*time.Second) |
| defer cancel() |
| - raw, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "ControlGroup,Id,Slice,ActiveState", "carlos-edge.service").Output() |
| + raw, err := systemd.Command(systemd.Systemctl, "show", "-p", "ControlGroup,Id,Slice,ActiveState", "carlos-edge.service").Output(ctx) |
| if err != nil { |
| return "", err |
| } |
diff --git a/internal/host/claimunit_socket_migration_linux.go b/internal/host/claimunit_socket_migration_linux.go| index a1fe099bb..85a5ff31d 100644 |
| --- a/internal/host/claimunit_socket_migration_linux.go |
| +++ b/internal/host/claimunit_socket_migration_linux.go |
| @@ -6,7 +6,6 @@ import ( |
| "errors" |
| "net" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -14,6 +13,7 @@ import ( |
| "github.com/carlosframework/platform/internal/rootstate" |
| "github.com/carlosframework/platform/internal/safefile" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -95,7 +95,7 @@ func captureProductionClaimUnitSocket(ctx context.Context, s claimUnitShape, p c |
| if err != nil { |
| return before, err |
| } |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", p.Unit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", p.Unit).Output(ctx) |
| if err != nil { |
| return before, err |
| } |
diff --git a/internal/host/dbreads_linux.go b/internal/host/dbreads_linux.go| index e58f7c232..ecf2e4b9b 100644 |
| --- a/internal/host/dbreads_linux.go |
| +++ b/internal/host/dbreads_linux.go |
| @@ -5,9 +5,10 @@ package host |
| import ( |
| "context" |
| "net" |
| - "os/exec" |
| "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| func dialDBReadWorker(ctx context.Context) (net.Conn, error) { |
| @@ -17,7 +18,7 @@ func dialDBReadWorker(ctx context.Context) (net.Conn, error) { |
| // dbReadUnits lists carlos-dbread@ units, readable without privilege. |
| func dbReadUnits(ctx context.Context) (int, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "list-units", "--all", "--plain", "--no-legend", "--no-pager", "carlos-dbread@*.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "list-units", "--all", "--plain", "--no-legend", "--no-pager", "carlos-dbread@*.service").Output(ctx) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/host/egress_source.go b/internal/host/egress_source.go| index 2f66d2993..d08b3b160 100644 |
| --- a/internal/host/egress_source.go |
| +++ b/internal/host/egress_source.go |
| @@ -18,7 +18,6 @@ import ( |
| "errors" |
| "fmt" |
| "log" |
| - "os/exec" |
| "os/user" |
| "path/filepath" |
| "strconv" |
| @@ -32,6 +31,7 @@ import ( |
| "github.com/carlosframework/platform/internal/layout" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // boxWhollyNested: no row is a sidecar member (IsSidecar, Kind "sidecar": |
| @@ -384,7 +384,7 @@ func userUID(name string) (string, bool, error) { |
| // systemctlOutput runs systemctl and returns its combined output. |
| func systemctlOutput(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| } |
diff --git a/internal/host/group_maintenance_verbs_linux.go b/internal/host/group_maintenance_verbs_linux.go| index d2a2c928b..935c79ae9 100644 |
| --- a/internal/host/group_maintenance_verbs_linux.go |
| +++ b/internal/host/group_maintenance_verbs_linux.go |
| @@ -10,13 +10,14 @@ import ( |
| "errors" |
| "io" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| "time" |
| "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // Open every ancestor by descriptor. Production starts at /; the test anchor |
| @@ -165,13 +166,11 @@ func (b *maintenanceBoundedOutput) Write(p []byte) (int, error) { |
| func maintenanceEdgeProcess(ctx context.Context) (int, string, error) { |
| ctx, cancel := context.WithTimeout(ctx, time.Second) |
| defer cancel() |
| - cmd := exec.CommandContext(ctx, "/usr/bin/systemctl", "show", "--property=MainPID", "--value", "carlos-edge.service") |
| + var out maintenanceBoundedOutput |
| + cmd := systemd.Command(systemd.SystemctlAbsolute, "show", "--property=MainPID", "--value", "carlos-edge.service") |
| cmd.Env = []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C"} |
| cmd.Dir = "/" |
| - cmd.WaitDelay = time.Second |
| - var out maintenanceBoundedOutput |
| - cmd.Stdout = &out |
| - if err := cmd.Run(); err != nil { |
| + if err := cmd.Run(ctx, &out, nil); err != nil { |
| return 0, "", err |
| } |
| pid, err := maintenanceMainPID(out.body) |
diff --git a/internal/host/probes.go b/internal/host/probes.go| index 9140019bb..3931760db 100644 |
| --- a/internal/host/probes.go |
| +++ b/internal/host/probes.go |
| @@ -12,14 +12,15 @@ package host |
| import ( |
| "bufio" |
| + "context" |
| "io" |
| "os" |
| - "os/exec" |
| "strconv" |
| "strings" |
| "sync" |
| "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -42,7 +43,8 @@ const adoptTimerUnit = "carlos-adopt.timer" |
| // does. A systemctl that couldn't run at all prints nothing, and nothing maps |
| // to nil. |
| func adoptTimerActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", adoptTimerUnit).Output() |
| + // Background: adoptTimerActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", adoptTimerUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
| @@ -60,7 +62,8 @@ const configPathUnit = "carlos-adopt.path" |
| // happily, and nothing ever reads it — so this probe is the only thing that |
| // can tell an operator the box quietly fell back to the hourly config floor. |
| func configPathActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", configPathUnit).Output() |
| + // Background: configPathActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", configPathUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
| @@ -79,7 +82,8 @@ const restartPathUnit = "carlos-restart.path" |
| // pass comes round. Nothing inside the agent can see the difference: it writes |
| // its marker either way. |
| func restartPathActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", restartPathUnit).Output() |
| + // Background: restartPathActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", restartPathUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
| @@ -93,7 +97,8 @@ const systemUpdatePathUnit = "carlos-system-update.path" |
| // the self-update relay: an unarmed path here means an agent that fetched and |
| // verified a new build touches its marker and nothing ever picks it up. |
| func systemUpdatePathActive() *bool { |
| - out, _ := exec.Command("systemctl", "is-active", systemUpdatePathUnit).Output() |
| + // Background: systemUpdatePathActive takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Systemctl, "is-active", systemUpdatePathUnit).Output(context.Background()) |
| return parseIsActive(string(out)) |
| } |
diff --git a/internal/host/restartwatch.go b/internal/host/restartwatch.go| index 66e6be32b..74e710358 100644 |
| --- a/internal/host/restartwatch.go |
| +++ b/internal/host/restartwatch.go |
| @@ -14,13 +14,13 @@ import ( |
| "context" |
| "encoding/json" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strconv" |
| "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // restartWindow is how far back a unit's restarts are counted. A unit's |
| @@ -258,8 +258,8 @@ func saveRestartWatch(path string, w restartWatch) error { |
| func platformUnitRestarts() map[string]unitRestartState { |
| ctx, cancel := context.WithTimeout(context.Background(), restartProbeTimeout) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", |
| - "--property=Id", "--property=NRestarts", "--property=ActiveState", "carlos-*.service").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", |
| + "--property=Id", "--property=NRestarts", "--property=ActiveState", "carlos-*.service").Output(ctx) |
| if err != nil { |
| return nil |
| } |
diff --git a/internal/host/rootgeneration_services_linux.go b/internal/host/rootgeneration_services_linux.go| index 9075333ef..baf22bf12 100644 |
| --- a/internal/host/rootgeneration_services_linux.go |
| +++ b/internal/host/rootgeneration_services_linux.go |
| @@ -10,13 +10,13 @@ import ( |
| "fmt" |
| "io" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "slices" |
| "strconv" |
| "strings" |
| "github.com/carlosframework/platform/internal/rootstate" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "golang.org/x/sys/unix" |
| ) |
| @@ -106,7 +106,7 @@ type generationExeBinding struct { |
| } |
| func generationServiceShow(ctx context.Context, unit string) (map[string]string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", unit, "-p", "ControlGroup", "-p", "MainPID", "-p", "ExecStart", "-p", "FragmentPath", "-p", "DropInPaths").Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", unit, "-p", "ControlGroup", "-p", "MainPID", "-p", "ExecStart", "-p", "FragmentPath", "-p", "DropInPaths").Output(ctx) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/host/runscensure.go b/internal/host/runscensure.go| index 52a43bf6b..2dcc7cb29 100644 |
| --- a/internal/host/runscensure.go |
| +++ b/internal/host/runscensure.go |
| @@ -7,7 +7,6 @@ import ( |
| "io/fs" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "runtime" |
| "strings" |
| @@ -17,6 +16,7 @@ import ( |
| "github.com/carlosframework/platform/internal/execsandbox" |
| "github.com/carlosframework/platform/internal/instancectl" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| func RunSystemRunscEnsure(args []string) { |
| @@ -34,7 +34,7 @@ func RunSystemRunscEnsure(args []string) { |
| } |
| } |
| func runscSystemctl(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| } |
diff --git a/internal/host/settle_verdict_adopt_test.go b/internal/host/settle_verdict_adopt_test.go| new file mode 100644 |
| index 000000000..c38c8cc4a |
| --- /dev/null |
| +++ b/internal/host/settle_verdict_adopt_test.go |
| @@ -0,0 +1,115 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "errors" |
| + "runtime" |
| + "slices" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| +) |
| + |
| +// settleOutcomeThroughAdoption runs one adoption pass of v2 over two |
| +// named-unit routes of one app that both run v1. The first restart the pass |
| +// asks for returns first (an error settleUnit produced); every later one |
| +// succeeds. It reports which hosts were restarted, which got the not-up |
| +// recovery (WithRollbackRestart), which got the plain start, and the |
| +// version each live link names after the pass. |
| +func settleOutcomeThroughAdoption(t *testing.T, first error) (restarted, recovered, started []string, live map[string]string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + optDir := t.TempDir() |
| + s := release.NewDirStore(t.TempDir()) |
| + plat := runtime.GOOS + "-" + runtime.GOARCH |
| + pub, priv, err := ed25519.GenerateKey(nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := restartTestRegistry(t) |
| + hosts := []string{"a.console.test", "b.console.test"} |
| + for i, h := range hosts { |
| + // Different upstreams: two processes, so a not-up group rollback |
| + // does not take the other route with it. |
| + if err := reg.Upsert(registry.Route{Host: h, Kind: "instance", App: "console", Channel: "canary/console", |
| + Addr: []string{"127.0.0.1:8091", "127.0.0.1:8092"}[i], Status: "ready", Unit: "console-" + string(rune('a'+i)) + ".service"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, v := range []string{"v1", "v2"} { |
| + m := release.Manifest{App: "console", Version: v, Kind: "binary", Artifacts: map[string]release.Artifact{plat: {}}} |
| + if err := release.Ship(ctx, s, "bab", m, map[string][]byte{plat: []byte("build " + v)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := release.StageArtifact(optDir, "bab", "v1", "console", []byte("build v1")); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, h := range hosts { |
| + if err := release.PointLive(optDir, h, "bab", "v1", "console"); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := release.Promote(ctx, s, priv, "bab", "console", "canary/console", "v2"); err != nil { |
| + t.Fatal(err) |
| + } |
| + restart := func(h string) error { |
| + restarted = append(restarted, h) |
| + if len(restarted) == 1 { |
| + return first |
| + } |
| + return nil |
| + } |
| + _ = release.Pass(ctx, reg, s, pub, optDir, restart, |
| + release.WithStartUnit(func(h string) error { started = append(started, h); return nil }), |
| + release.WithRollbackRestart(func(h string) error { recovered = append(recovered, h); return nil })) |
| + live = map[string]string{} |
| + for _, h := range hosts { |
| + live[h], _ = release.LiveVersion(optDir, h) |
| + } |
| + return restarted, recovered, started, live |
| +} |
| + |
| +// A unit settle saw fail is a verdict through adoption: v2 is poisoned for |
| +// the pass (the second route is not tried) and the route gets the not-up |
| +// recovery, not the plain start. |
| +func TestFailedSettleStillPoisonsAndRecovers(t *testing.T) { |
| + failed := settleUnit(&fakeUnits{shows: []unitProps{{ActiveState: "failed", SubState: "failed", InvocationID: "new"}}}, |
| + "console-a.service", "old", opts(func() error { return nil })) |
| + var nu *release.UnitNotUpError |
| + if !errors.As(failed, &nu) { |
| + t.Fatalf("settle = %v, want UnitNotUpError for a failed unit", failed) |
| + } |
| + restarted, recovered, started, live := settleOutcomeThroughAdoption(t, failed) |
| + if len(restarted) != 1 { |
| + t.Fatalf("restarted %v, want one: a failed build poisons v2 for the pass", restarted) |
| + } |
| + if !slices.Equal(recovered, restarted) || len(started) != 0 { |
| + t.Fatalf("recovered %v, started %v; want the not-up recovery for %s and no plain start", recovered, started, restarted[0]) |
| + } |
| + if live[restarted[0]] != "v1" { |
| + t.Fatalf("live = %v, want %s back on v1", live, restarted[0]) |
| + } |
| +} |
| + |
| +// A settle that timed out observing the unit, through adoption: it is still |
| +// not up, so the route gets the rollback restart (reset-failed and restart, |
| +// which replaces whatever runs) and never the plain start; and it is |
| +// temporary, so v2 is not poisoned and the second route still adopts it. |
| +func TestTimedOutSettleRecoversWithoutPoisoning(t *testing.T) { |
| + timedOut := settleUnit(&showErrs{fakeUnits: &fakeUnits{}, err: &systemd.TimeoutError{Program: "systemctl", Verb: "show", Units: []string{"console-a.service"}, After: systemd.QueryTimeout}}, |
| + "console-a.service", "old", opts(func() error { return nil })) |
| + restarted, recovered, started, live := settleOutcomeThroughAdoption(t, timedOut) |
| + if len(restarted) != 2 { |
| + t.Fatalf("restarted %v, want both routes: a timed-out observation must not poison v2 for the pass", restarted) |
| + } |
| + if !slices.Equal(recovered, restarted[:1]) || len(started) != 0 { |
| + t.Fatalf("recovered %v, started %v; want the rollback restart for %s and never a plain start", recovered, started, restarted[0]) |
| + } |
| + if live[restarted[0]] != "v1" || live[restarted[1]] != "v2" { |
| + t.Fatalf("live = %v, want %s back on v1 and %s on v2", live, restarted[0], restarted[1]) |
| + } |
| +} |
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go| index e8678e08b..6e891c6fc 100644 |
| --- a/internal/host/systemapply.go |
| +++ b/internal/host/systemapply.go |
| @@ -30,6 +30,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/rootparticipation" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -204,7 +205,10 @@ func openSystemRegistry(dataDir string) (*registry.Registry, error) { |
| func productionSysOps() sysOps { |
| return sysOps{ |
| systemctl: func(args ...string) (string, error) { |
| - out, err := exec.Command("systemctl", args...).CombinedOutput() |
| + // Background: the sysOps seam takes no context. A query is bounded |
| + // by QueryTimeout; a mutation (the edge restart above all) has no |
| + // deadline of its own, as before (internal/systemd). |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(context.Background()) |
| if err != nil { |
| return string(out), fmt.Errorf("systemctl %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out))) |
| } |
| @@ -242,7 +246,8 @@ func productionSysOps() sysOps { |
| return nil |
| }, |
| edgeStartedThisBoot: func() bool { |
| - out, err := exec.Command("systemctl", "show", "-p", "ActiveEnterTimestampMonotonic", "--value", systemEdgeUnit).Output() |
| + // Background: edgeStartedThisBoot takes no context; QueryTimeout is this query's deadline. |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "ActiveEnterTimestampMonotonic", "--value", systemEdgeUnit).Output(context.Background()) |
| return err == nil && strings.TrimSpace(string(out)) != "" && strings.TrimSpace(string(out)) != "0" |
| }, |
| logf: log.Printf, |
diff --git a/internal/host/systemunits.go b/internal/host/systemunits.go| index 79e480172..cf920974b 100644 |
| --- a/internal/host/systemunits.go |
| +++ b/internal/host/systemunits.go |
| @@ -2,10 +2,11 @@ package host |
| import ( |
| "bytes" |
| + "context" |
| "errors" |
| "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "slices" |
| "strings" |
| @@ -324,7 +325,8 @@ func parseIsEnabled(out string) *bool { |
| // rather than productionSysOps().systemctl's fail-on-non-zero. The error |
| // comes back only so a caller left with no word to read can say why. |
| func systemctlProbe(args ...string) (string, error) { |
| - out, err := exec.Command("systemctl", args...).Output() |
| + // Background: systemctlProbe takes no context; QueryTimeout is this query's deadline. |
| + out, err := systemd.Command(systemd.Systemctl, args...).Output(context.Background()) |
| return string(out), err |
| } |
diff --git a/internal/host/unitops.go b/internal/host/unitops.go| index 1e8cf7200..4c960b3ba 100644 |
| --- a/internal/host/unitops.go |
| +++ b/internal/host/unitops.go |
| @@ -6,14 +6,15 @@ package host |
| import ( |
| "bytes" |
| + "context" |
| "fmt" |
| "log" |
| "os" |
| - "os/exec" |
| "path/filepath" |
| "strings" |
| "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // dropInRoot is where systemd looks for a unit's drop-ins whichever tree |
| @@ -138,7 +139,8 @@ func lockConfigSync(path string) (unlock func(), err error) { |
| // post-reload verification compare against. |
| func probeUnits(units []string) (map[string]appconfig.UnitState, error) { |
| args := append([]string{"show", "-p", "Id,LoadState,EnvironmentFiles"}, units...) |
| - out, err := exec.Command("systemctl", args...).Output() |
| + // Background: probeUnits takes no context; QueryTimeout is this query's deadline. |
| + out, err := systemd.Command(systemd.Systemctl, args...).Output(context.Background()) |
| if err != nil && len(out) == 0 { |
| return nil, fmt.Errorf("systemctl show: %w", err) |
| } |
| @@ -188,7 +190,8 @@ func parseSystemctlShow(out []byte, units []string) (map[string]appconfig.UnitSt |
| } |
| func daemonReload() error { |
| - out, err := exec.Command("systemctl", "daemon-reload").CombinedOutput() |
| + // Background: daemonReload takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "daemon-reload").CombinedOutput(context.Background()) |
| if err != nil { |
| return fmt.Errorf("daemon-reload: %w: %s", err, strings.TrimSpace(string(out))) |
| } |
| @@ -199,7 +202,8 @@ func daemonReload() error { |
| // unit owes a restart even when a previous one left it inactive (spec |
| // §3.2 step 4). Logs and returns like systemctlTryRestartUnit. |
| func systemctlRestartUnit(unit string) error { |
| - out, err := exec.Command("systemctl", "restart", unit).CombinedOutput() |
| + // Background: systemctlRestartUnit takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, "restart", unit).CombinedOutput(context.Background()) |
| if err != nil { |
| log.Printf("adopt: restart %s: %v: %s", unit, err, strings.TrimSpace(string(out))) |
| return fmt.Errorf("restart %s: %w: %s", unit, err, strings.TrimSpace(string(out))) |
diff --git a/internal/host/unitsettle.go b/internal/host/unitsettle.go| index 6dfe95d79..7ad773f4d 100644 |
| --- a/internal/host/unitsettle.go |
| +++ b/internal/host/unitsettle.go |
| @@ -20,7 +20,6 @@ import ( |
| "net" |
| "net/http" |
| "os" |
| - "os/exec" |
| "regexp" |
| "strconv" |
| "strings" |
| @@ -29,6 +28,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/upstreamguard" |
| ) |
| @@ -59,8 +59,9 @@ type unitSystem interface { |
| type systemdUnits struct{} |
| func (systemdUnits) Show(unit string) (unitProps, error) { |
| - out, err := exec.Command("systemctl", "show", unit, |
| - "-p", "Id", "-p", "FragmentPath", "-p", "DropInPaths", "-p", "ActiveState", "-p", "SubState", "-p", "InvocationID", "-p", "MainPID", "-p", "NRestarts", "-p", "ExecStart", "-p", "ActiveEnterTimestamp").Output() |
| + // Background: unitSystem.Show takes no context; QueryTimeout is this query's deadline. |
| + out, err := systemd.Command(systemd.Systemctl, "show", unit, |
| + "-p", "Id", "-p", "FragmentPath", "-p", "DropInPaths", "-p", "ActiveState", "-p", "SubState", "-p", "InvocationID", "-p", "MainPID", "-p", "NRestarts", "-p", "ExecStart", "-p", "ActiveEnterTimestamp").Output(context.Background()) |
| if err != nil { |
| return unitProps{}, fmt.Errorf("systemctl show %s: %w", unit, err) |
| } |
| @@ -72,7 +73,8 @@ func (systemdUnits) Restart(unit string) error { return systemctlVerb("resta |
| func (systemdUnits) ResetFailed(unit string) error { return systemctlVerb("reset-failed", unit) } |
| func (systemdUnits) JournalTail(unit string, n int) string { |
| - out, _ := exec.Command("journalctl", "-u", unit, "-o", "cat", "-n", strconv.Itoa(n), "--no-pager").Output() |
| + // Background: unitSystem.JournalTail takes no context; QueryTimeout is this query's deadline. |
| + out, _ := systemd.Command(systemd.Journalctl, "-u", unit, "-o", "cat", "-n", strconv.Itoa(n), "--no-pager").Output(context.Background()) |
| return strings.TrimSpace(string(out)) |
| } |
| @@ -103,7 +105,8 @@ func (systemdUnits) StartTime(pid int) (string, error) { |
| } |
| func systemctlVerb(verb, unit string) error { |
| - out, err := exec.Command("systemctl", verb, unit).CombinedOutput() |
| + // Background: systemctlVerb takes no context; a mutation has no deadline of its own (internal/systemd), as with exec.Command. |
| + out, err := systemd.Command(systemd.Systemctl, verb, unit).CombinedOutput(context.Background()) |
| if err != nil { |
| return fmt.Errorf("systemctl %s %s: %w: %s", verb, unit, err, strings.TrimSpace(string(out))) |
| } |
| @@ -175,6 +178,23 @@ type settleOpts struct { |
| // nothing and restarts nothing. |
| var errUnitStopped = errors.New("unit was stopped during settle") |
| +// unobservedNotUp is settleUnit's answer when its deadline passed while |
| +// systemctl show kept failing (refused, a D-Bus error, killed at its |
| +// QueryTimeout): ONE error that adoption reads two ways. It is a |
| +// *release.UnitNotUpError (errors.As), so adoption gives the route the |
| +// not-up recovery, whose reset-failed and restart replace whatever runs. |
| +// And it is temporary, because nothing was seen to fail, so adoption does |
| +// not poison the version for the rest of the pass. A failure settle did see |
| +// (failed, restarted, the wrong executable, not ready) is a plain |
| +// UnitNotUpError, not temporary. |
| +type unobservedNotUp struct { |
| + *release.UnitNotUpError |
| + show error // the last show's error |
| +} |
| + |
| +func (e *unobservedNotUp) Unwrap() []error { return []error{e.UnitNotUpError, e.show} } |
| +func (e *unobservedNotUp) Temporary() bool { return true } |
| + |
| // settleUnit watches unit after a try-restart. beforeInvocation is the |
| // InvocationID before the restart; "" means the unit was not running, and an |
| // inactive unit is then "nothing started", not a failure. Otherwise a unit |
| @@ -200,10 +220,19 @@ func settleUnit(sys unitSystem, unit, beforeInvocation string, o settleOpts) err |
| p, err := sys.Show(unit) |
| if err != nil { |
| // One failed `systemctl show` says nothing about the build (a |
| - // busy bus, a timed-out D-Bus call). Retried until the deadline, |
| - // and only a deadline that still cannot observe the unit fails. |
| + // busy bus, a timed-out D-Bus call, a show killed at its |
| + // QueryTimeout). Retried until the deadline, and only a deadline |
| + // that still cannot observe the unit fails: as a temporary |
| + // UnitNotUpError (unobservedNotUp), so the not-up recovery |
| + // (reset-failed and restart) replaces whatever runs and the |
| + // version is not poisoned. Reading this as an unknown outcome |
| + // instead belongs to the outcome-reconciliation follow-up (amadan |
| + // discussion #1214): adoption would roll the symlink back and |
| + // plain-start the unit, which leaves a new process that did come |
| + // up running under the old link. |
| if !o.Now().Before(deadline) { |
| - return notUp(fmt.Sprintf("cannot observe %s: %v", unit, err)) |
| + return &unobservedNotUp{show: err, UnitNotUpError: &release.UnitNotUpError{ |
| + Unit: unit, Reason: fmt.Sprintf("cannot observe %s: %v", unit, err), Journal: sys.JournalTail(unit, 20)}} |
| } |
| o.Sleep(o.Poll) |
| continue |
diff --git a/internal/host/unitsettle_test.go b/internal/host/unitsettle_test.go| index a6b37e81b..3adcf1c52 100644 |
| --- a/internal/host/unitsettle_test.go |
| +++ b/internal/host/unitsettle_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| type fakeUnits struct { |
| @@ -188,15 +189,51 @@ func TestSettleRetriesATransientShowError(t *testing.T) { |
| } |
| } |
| +// A settle whose deadline passes while systemd cannot be asked about the |
| +// unit is a UnitNotUpError ("cannot observe"), whether the show was refused |
| +// or killed at its QueryTimeout: the not-up recovery (reset-failed and |
| +// restart) then replaces whatever runs, so the restored symlink and the |
| +// running process agree. The same error is temporary, because nothing was |
| +// seen to fail: adoption does not poison the version over it. A failure |
| +// settle did see (here, the unit failed) is a UnitNotUpError that is not |
| +// temporary. Reading the unobserved case as an unknown outcome instead |
| +// waits for the outcome-reconciliation follow-up (amadan discussion #1214). |
| func TestSettleShowErrorAtTheDeadline(t *testing.T) { |
| - sys := &showFails{fakeUnits: &fakeUnits{}} |
| + for name, showErr := range map[string]error{ |
| + "refused": errors.New("Access denied"), |
| + "timed out": &systemd.TimeoutError{Program: "systemctl", Verb: "show", Units: []string{"console.service"}, After: systemd.QueryTimeout}, |
| + } { |
| + sys := &showErrs{fakeUnits: &fakeUnits{}, err: showErr} |
| + err := settleUnit(sys, "console.service", "old", opts(func() error { return nil })) |
| + var nu *release.UnitNotUpError |
| + if !errors.As(err, &nu) || nu.Reason != "cannot observe console.service: "+showErr.Error() { |
| + t.Errorf("%s: settle = %v, want a deadline UnitNotUpError saying the unit could not be observed", name, err) |
| + } |
| + if !temporary(err) { |
| + t.Errorf("%s: settle = %v, want it temporary: nothing was seen to fail", name, err) |
| + } |
| + } |
| + failed := settleUnit(&fakeUnits{shows: []unitProps{{ActiveState: "failed", SubState: "failed", InvocationID: "new"}}}, |
| + "console.service", "old", opts(func() error { return nil })) |
| var nu *release.UnitNotUpError |
| - err := settleUnit(sys, "console.service", "old", opts(func() error { return nil })) |
| - if !errors.As(err, &nu) || !strings.Contains(nu.Reason, "cannot observe console.service: Access denied") { |
| - t.Fatalf("settle = %v, want a deadline UnitNotUpError saying the unit could not be observed", err) |
| + if !errors.As(failed, &nu) || temporary(failed) { |
| + t.Errorf("failed unit: settle = %v, want a UnitNotUpError that is not temporary", failed) |
| } |
| } |
| +// temporary is the check adoption makes before it poisons a version. |
| +func temporary(err error) bool { |
| + var t interface{ Temporary() bool } |
| + return errors.As(err, &t) && t.Temporary() |
| +} |
| + |
| +type showErrs struct { |
| + *fakeUnits |
| + err error |
| +} |
| + |
| +func (s showErrs) Show(string) (unitProps, error) { return unitProps{}, s.err } |
| + |
| // Final review F2: inactive/dead after the restart is an operator's stop. |
| func TestSettleStoppedUnitIsErrUnitStopped(t *testing.T) { |
| f := &fakeUnits{shows: []unitProps{ |
diff --git a/internal/instancectl/gvisor_claim_rootrunner_linux_test.go b/internal/instancectl/gvisor_claim_rootrunner_linux_test.go| index 29ba8df55..ff39dd188 100644 |
| --- a/internal/instancectl/gvisor_claim_rootrunner_linux_test.go |
| +++ b/internal/instancectl/gvisor_claim_rootrunner_linux_test.go |
| @@ -55,6 +55,10 @@ func rootrunnerClaimControl() error { |
| Run: func(ctx context.Context, args ...string) (string, error) { |
| b, e := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput() |
| return string(b), e |
| + }, |
| + Journal: func(ctx context.Context, args ...string) (string, error) { |
| + b, e := exec.CommandContext(ctx, "journalctl", args...).CombinedOutput() |
| + return string(b), e |
| }} |
| s.snapshots = newDemoSnapshotSupervisor(s) |
| prepare := s.snapshots.prepare |
diff --git a/internal/instancectl/gvisorprobe.go b/internal/instancectl/gvisorprobe.go| index e82f328f4..897536b5d 100644 |
| --- a/internal/instancectl/gvisorprobe.go |
| +++ b/internal/instancectl/gvisorprobe.go |
| @@ -178,10 +178,10 @@ func (s *Server) runGVisorProbe(ctx context.Context) (report ProbeReport) { |
| } |
| s.report, s.probed = report, true |
| s.mu.Unlock() |
| - if !report.Ready && s.Run != nil && attempted { |
| + if !report.Ready && s.Journal != nil && attempted { |
| diag, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| defer cancel() |
| - out, err := s.Run(diag, "journalctl", "--no-pager", "--output=cat", "--lines=20", "--since=@"+strconv.FormatInt(started.Unix(), 10), "--unit="+gvisorProbeUnit) |
| + out, err := s.Journal(diag, "--no-pager", "--output=cat", "--lines=20", "--since=@"+strconv.FormatInt(started.Unix(), 10), "--unit="+gvisorProbeUnit) |
| if len(out) > 4096 { |
| out = out[len(out)-4096:] |
| } |
diff --git a/internal/instancectl/gvisorprobe_flow_linux_test.go b/internal/instancectl/gvisorprobe_flow_linux_test.go| index 45a4bb811..586de8ddc 100644 |
| --- a/internal/instancectl/gvisorprobe_flow_linux_test.go |
| +++ b/internal/instancectl/gvisorprobe_flow_linux_test.go |
| @@ -170,14 +170,14 @@ func newProbeFlow(t *testing.T) *probeFlow { |
| } |
| return nil |
| } |
| - s.Run = func(ctx context.Context, args ...string) (string, error) { |
| + s.Journal = func(ctx context.Context, args ...string) (string, error) { |
| // Only this attempt's lines: a --since bound no earlier than the |
| // probe's start, so a failure never replays older probes' journal. |
| - if len(args) != 6 || strings.Join(args[:4], " ") != "journalctl --no-pager --output=cat --lines=20" || args[5] != "--unit="+gvisorProbeUnit || !strings.HasPrefix(args[4], "--since=@") { |
| + if len(args) != 5 || strings.Join(args[:3], " ") != "--no-pager --output=cat --lines=20" || args[4] != "--unit="+gvisorProbeUnit || !strings.HasPrefix(args[3], "--since=@") { |
| t.Error(args) |
| - } else if since, err := strconv.ParseInt(strings.TrimPrefix(args[4], "--since=@"), 10, 64); err != nil || since > time.Now().Unix() || (!f.callStart.IsZero() && since < f.callStart.Unix()) { |
| + } else if since, err := strconv.ParseInt(strings.TrimPrefix(args[3], "--since=@"), 10, 64); err != nil || since > time.Now().Unix() || (!f.callStart.IsZero() && since < f.callStart.Unix()) { |
| // Within this probe call, allowing whole-second truncation. |
| - t.Error("journal window not bounded to this attempt", args[4], f.callStart) |
| + t.Error("journal window not bounded to this attempt", args[3], f.callStart) |
| } |
| deadline, ok := ctx.Deadline() |
| if !ok || time.Until(deadline) > 5*time.Second { |
diff --git a/internal/instancectl/hairpin.go b/internal/instancectl/hairpin.go| index fe37e1737..67b18ae70 100644 |
| --- a/internal/instancectl/hairpin.go |
| +++ b/internal/instancectl/hairpin.go |
| @@ -10,12 +10,12 @@ import ( |
| "net/http" |
| "net/netip" |
| "os" |
| - "os/exec" |
| "slices" |
| "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/hairpin" |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| var ( |
| @@ -323,7 +323,7 @@ func ClearGroupHairpin(ctx context.Context) error { |
| } |
| func newHairpinResetServer() *Server { |
| return &Server{LocalAddrs: LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| }} |
| } |
diff --git a/internal/instancectl/peer_linux.go b/internal/instancectl/peer_linux.go| index 50475715a..dc58cbef4 100644 |
| --- a/internal/instancectl/peer_linux.go |
| +++ b/internal/instancectl/peer_linux.go |
| @@ -9,7 +9,6 @@ import ( |
| "log" |
| "net" |
| "os" |
| - "os/exec" |
| "os/user" |
| "strconv" |
| "strings" |
| @@ -17,6 +16,8 @@ import ( |
| "time" |
| "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/systemd" |
| ) |
| // peerCred reads SO_PEERCRED from a connected unix socket. |
| @@ -98,7 +99,7 @@ func EdgePeerRuleFor(carlosUID int, mainPID func() (int, error)) func(net.Conn) |
| func systemdEdgeMainPID() (int, error) { |
| ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "show", "-p", "MainPID", "--value", edgeUnit).Output() |
| + out, err := systemd.Command(systemd.Systemctl, "show", "-p", "MainPID", "--value", edgeUnit).Output(ctx) |
| if err != nil { |
| return 0, err |
| } |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index a0e487a55..5b44d06b5 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -32,6 +32,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "github.com/carlosframework/platform/internal/version" |
| ) |
| @@ -179,6 +180,10 @@ type Server struct { |
| // inspectMountpoints uses it, and every argument it passes is a |
| // constant: nothing from a request reaches it. |
| Run func(ctx context.Context, args ...string) (string, error) |
| + // Journal runs journalctl with args and returns its combined output; |
| + // production is internal/systemd's bounded journalctl Command, tests |
| + // record. nil skips the journal tail a failed gVisor probe logs. |
| + Journal func(ctx context.Context, args ...string) (string, error) |
| // Build is the build this process runs (version.Build), answered on |
| // every /ready as the BuildHeader so the agent can see it talks to |
| @@ -330,7 +335,11 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV |
| ClaimStop: claim, |
| ClaimHeldRelease: heldRelease, |
| Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| + return string(out), err |
| + }, |
| + Journal: func(ctx context.Context, args ...string) (string, error) { |
| + out, err := systemd.Command(systemd.Journalctl, args...).CombinedOutput(ctx) |
| return string(out), err |
| }, |
| Run: func(ctx context.Context, args ...string) (string, error) { |
diff --git a/internal/ops/ops.go b/internal/ops/ops.go| index 15bd44131..408010035 100644 |
| --- a/internal/ops/ops.go |
| +++ b/internal/ops/ops.go |
| @@ -7,6 +7,7 @@ package ops |
| import ( |
| "github.com/carlosframework/platform/internal/cliflag" |
| "github.com/carlosframework/platform/internal/clireg" |
| + "github.com/carlosframework/platform/internal/systemd" |
| "context" |
| "encoding/json" |
| @@ -17,7 +18,6 @@ import ( |
| "io/fs" |
| "log" |
| "os" |
| - "os/exec" |
| "os/signal" |
| "path/filepath" |
| "strings" |
| @@ -232,7 +232,7 @@ const daemonReloadTimeout = time.Minute |
| func systemdDaemonReload() error { |
| ctx, cancel := context.WithTimeout(context.Background(), daemonReloadTimeout) |
| defer cancel() |
| - out, err := exec.CommandContext(ctx, "systemctl", "daemon-reload").CombinedOutput() |
| + out, err := systemd.Command(systemd.Systemctl, "daemon-reload").CombinedOutput(ctx) |
| if err != nil { |
| return fmt.Errorf("systemctl daemon-reload: %v: %s", err, strings.TrimSpace(string(out))) |
| } |
diff --git a/internal/provision/bounded_systemctl_census_test.go b/internal/provision/bounded_systemctl_census_test.go| new file mode 100644 |
| index 000000000..08d7aa57b |
| --- /dev/null |
| +++ b/internal/provision/bounded_systemctl_census_test.go |
| @@ -0,0 +1,35 @@ |
| +package provision |
| + |
| +// Record-write census re-pin for bounded systemctl (code-health batch 3, |
| +// branch bounded-systemctl), layered on consoleRequestCtxWriteCensusInventory. |
| +// No record write is added, moved or reclassified, and no unit writes |
| +// anything new. One unit changed only in a systemctl runner it wires: |
| +// - claimLaunchFor (host): the instancectl.ClaimUnits Systemctl closure |
| +// runs systemd.Command(systemd.Systemctl, args...).CombinedOutput(ctx) |
| +// instead of exec.CommandContext(ctx, "systemctl", args...) |
| +// .CombinedOutput(): the same program, arguments, context and output, |
| +// plus internal/systemd's 30 s bound on a query verb (a mutating verb |
| +// keeps the caller's context alone). Every other line of the body, the |
| +// instances literal and the guards ahead of it, is unchanged. Kinds |
| +// unchanged: lit:instances. |
| +func boundedSystemctlWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), consoleRequestCtxWriteCensusInventory()...) |
| + repins := []censusEntry{ |
| + {"internal/host/claimlaunch_production.go", "claimLaunchFor", "key-site", "lit:instances", "d3bf3b9fe12a445ecef2dfc73b2ac9533cd661c538dfee3ebe8c821481cde601"}, |
| + } |
| + for _, r := range repins { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + if e.Class != r.Class || e.Kinds != r.Kinds { |
| + panic("bounded-systemctl re-pin changes the class or kinds of " + r.File + ":" + r.Unit) |
| + } |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + panic("bounded-systemctl re-pin of an unlisted unit " + r.File + ":" + r.Unit) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 8cf02f418..9a7c36ecf 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := consoleRequestCtxWriteCensusInventory() |
| + inventory := boundedSystemctlWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-bounded-systemctl.tsv b/internal/provision/testdata/plan14-root-reads-bounded-systemctl.tsv| new file mode 100644 |
| index 000000000..bd37b5f1f |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-bounded-systemctl.tsv |
| @@ -0,0 +1,92 @@ |
| +# Census overlay bounded-systemctl, written by census-propose (#369). census-ruling-bounded-systemctl, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-bounded-systemctl.md. |
| +# 21 body, 0 sites, 9 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 27 new dispositions: 24 reads re-frozen at their disposition with the claim, 3 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy abc4cb1e6d3656479ad85c687f25f264686744154d92a7226e3da4ebe3e876ce internal/host/agent.go systemctlStartUnit legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@191 e48d6f752a6ed9962add99c9c56fe62f24d1dcfa7c32acb83c61ab42dcc4ed9e |
| +@legacy 265ca4ce9dc48d44e88399482c020b5ddeb05292d286550bb319928efdaf9a20 internal/host/agent.go systemctlTryRestart legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@187 a1d2f2fc4c0d06dddc02d29ab762060a7b7aa7793e59b90d95a8c4d8fcadf92e |
| +@legacy 9aad79b06c7eb630b1dc9720cbfda5ac93beae4f412a0a59ae21c93bdbe20d19 internal/host/agent.go systemctlTryRestartUnit legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@201 31d32fd1e711bf81ab0da6fff590f993e4e1baf79ceb1d2a456a9fcc3d0c4952 |
| +@legacy eb8f2a739591c98833bc7f1ad1681dcbf6419f13d088f55f925d94e30167accb internal/host/bootstrap.go systemctl legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@176 e284a9691f4263cad090bc0021285ed1bf64cb4b66be4d10d54acc74505da175 |
| +@legacy f92ef992bc503107d15458ec331ac19a0d6cca0105888fc8096495c7ad9cdb98 internal/host/probes.go adoptTimerActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@133 b4c0f0b143d6b2f9965c7274d8963699fc85d3097d240d8502e02f5315eba69c |
| +@legacy 182a79653427e547876c9190ed6bd958ad101ed98128910ccae9c53c0faaaff9 internal/host/probes.go configPathActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@133 d10e078a2dd56a50e84d6e228c2f3378f349829ec878053a4e31cabfdb37f301 |
| +@legacy 5aa76816455480de8ee0346ac38f42f3703548356db3f188dd0a90baa0b099df internal/host/probes.go restartPathActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@135 df88c565c10c82811bb2a9fe6812a20b0f9020077340d7976ff8dd96c27bdc12 |
| +@legacy 1c959429b1afb6c2d73ada8a63de66faf5777b3b5ae1b7737cadae835dd13daf internal/host/probes.go systemUpdatePathActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@145 4bd96b1b34d911a67c46c2e6bb87f594ee12e0fb65a37007265f18c417b34a19 |
| +@legacy 3e5c6aa2e3e3d89a7fecf5ddf7827712531e1071050939668f97ca49fad9ad0a internal/host/systemunits.go systemctlProbe legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@155 ca1780c62a0f1bbf2fc2dccffc7e2bc207a2d4de5d39470ce5f2e008b19c626f |
| +@legacy aa410ae97b9742eea9cf39a2f481b4a9ac12e4034d4f6cb0383450cb41e04853 internal/host/unitops.go daemonReload legacy accepted-legacy accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl daemon-reload, once per pass when a marker exists;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@168 4eb5d810cd716bf51d3f4577e78ece730811984e4e606aa3c5f2aab73c3251f6 |
| +@legacy 5028d6d682eb060bfabbbc24e85b7ab63e66d5ee8599ba231e49e097452c57b5 internal/host/unitops.go probeUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl show -p Id,LoadState,EnvironmentFiles <units>, unit names already passed DeliverableUnitName; parsed positionally, a count mismatch is an error;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@254 738441a6ac4e3bc65f7b445d12c9c11da76b7f88f504cd3886ff41c3a3d5eb92 |
| +@legacy c63bda03e694c7f54cc4c59db0ab4a50fb0e65f62a23d7e590f56f4351e20a7a internal/host/unitops.go systemctlRestartUnit legacy accepted-legacy accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl restart <unit>, only for a unit root bound to the route through Bind after a successful reload and an exact EnvironmentFiles match;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@195 2022d180cf309b786208541502b510fead1d07bd4fefdccaaf273a2ab06387c5 |
| +@legacy d55c33e995eb3a6345ce31034cdfae37a3d6929f3eff743d894826a54f021c9f internal/instancectl/gvisorprobe.go Server.runGVisorProbe legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Task 6 fix round 1, applying the controller rulings: serialized probe construction uses root random nonce/fixed paths, root-only O_EXCL fixture, abstract listener, typed verified bundle/unit and context recheck. Read bounded root-owned nonce-bound output and the guest socket handshake; inspect kernel/proc runtime and limits while guest waits. Termination uses inactive/not-loaded state, no job/PIDs and empty cgroup, never per-command stop-post records. Keep the prior pass during the run and publish report plus runtime identity once, after cleanup; any failed attempt invalidates it and records the bounded diagnostic. A private package-test-only operations struct substitutes paths, executable preparation and output opening; production keeps GVisorProbePaths, fixed output/procfs, ensureExe and execsandbox.OpenRootFile. No new tenant-controlled path, launch/source/database read, or runtime-state read. CI fix: route serialized nonce fixture/output cleanup through existing pinned removeGenFiles owner with closed gVisor selectors and fixed probe paths. Existing reads and stop proof unchanged; no new raw removal owner.;rev3=census-ruling-gvisor-probe-diag;basis=Diagnostic only: the failure dump runs journalctl for the fixed probe unit only once a start was asked for, with --since=@<this attempt's start time>, so it no longer replays earlier attempts; a failure before the start logs this attempt's own fail line (taken before the start-up mount lines are prepended) instead. No new path, input or systemctl verb; probe steps unchanged.;rev3=census-ruling-bounded-systemctl;basis=the failure diagnostic calls the new Server.Journal seam with the same journalctl arguments minus the program name, instead of Server.Run with "journalctl" first; nil Journal skips it as nil Run did; no new path, input or verb file:Lstat@3275,file:OpenFile@2638,file:Read@2328,file:ReadAll@5637 90c42203b2b5bc263f0f337991e3138e54c1e4cf17f69c10fc7614cce0527255 |
| +@legacy c2885e27485a6e4c67f823a00c70652037ea8499191afca3734db00852033bd2 internal/instancectl/server.go type Server legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read;rev3=census-ruling-agent-start-demo-3;basis=Retain the snapshot supervisor in instance-control state; no new request-selected path. Census read-site delta: unchanged (1).;rev3=census-ruling-gvisor-demos;basis=Retain Task 1 mode/error/readiness fields, baseline/runtime callbacks, Task 4 per-host validated staged descriptors and root-selected probe nonce. Fix round 1 adds a private writer-operation seam assigned only in package tests, after the unchanged GVisorID admission check; production defaults still call the same checked constructor, WriteRootfs, WriteBundle and verifier. No new direct read or request-controlled callback. Task 5: private injected removal seam for unprivileged tests; production default removes only root-derived bundle and skeleton after both-family proof inside existing start fence. No new request field or agent-selected unit. Task 6: Retain serialized probe nonce, runtime-set identity verifier/token, fixed claims flag, bundle discovery root, and private unprivileged identity seam. No request-controlled callback or path; existing declaration read-site classification unchanged. Task 6 fix round 1: private gvisorProbeTestOps is set only in package tests; production defaults retain all fixed paths and the checked root output opener. No externally supplied callback or new direct read. Final R1 P2: retain fixed skeleton parent and concurrent per-instance cleanup refusals; no direct read or external configuration field. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.;rev3=census-ruling-same-box-edge-fence;basis=Field declarations only: NFT (the nft runner; nil never loads the fence), EdgeFenceOff (host.env CARLOS_EDGE_FENCE=off), and under the existing denyMu/mu: fenceAddrs, fenceReason, fenceRetry, denyApplied. No read added.;rev3=census-ruling-bounded-systemctl;basis=new field Journal, the journalctl seam for the gVisor probe's diagnostic; field declaration only; no read added file:Statfs@5239 d5c89f7179dcd67a27771c87050f340a2c9637b2b760ff322ca600ab8d3d1144 |
| +@legacy bebaab24b62b8935f5040e16d6c99dfaef2f08c5c1e59f13777c6d3ad7d13a5d internal/systemd/command.go Cmd.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-bounded-systemctl;basis=new: the exec.CommandContext for a mutation: the fixed program under the caller's context alone, no deadline or WaitDelay of its own (as exec.CommandContext before); queries go to bounded; reads nothing itself file:CommandContext@451 82e395ec0a5c8281445471b2419badb060994cc098f4a091b1ae27ee54e5f2f6 |
| +@legacy 02f94eb168e0796ded3294e4827d341de03f0554ed150bb4e2849a800794791c internal/systemd/command.go Command legacy accepted-legacy accepted-legacy;rev3=census-ruling-bounded-systemctl;basis=new: constructor of a systemctl/journalctl run; the program is one of three fixed names (systemctl, /usr/bin/systemctl, journalctl), never caller-supplied; arguments are the caller's, as with exec.Command file:Command@5 89666d774272947697007ae0f8c43133bd4b42b355173011021f559cb83a92ec |
| +@legacy 80613e2fb581e69f4099613b3e8cacbb89cfa1bca49e227afd85255f3f6354f5 internal/systemd/command.go bounded legacy accepted-legacy accepted-legacy;rev3=census-ruling-bounded-systemctl;basis=new: runs a query's fixed program under the caller's context and QueryTimeout, kills at the bound (WaitDelay 1 s) and returns a TimeoutError; reads nothing itself file:CommandContext@255 09e124141295f87c9db2272e59bac14c4af36715418ee11c87ece3432dbb910d |
| +@legacy f54e2d6f929d9028a8deb9bf9f37e1fc20e89e91f7bff15cec4046c407bd0e92 internal/activator/backend_unit.go UnitBackend.systemctl legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source.;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@332 e2065e995f5280ef568751e4e2ee3ffd5123d043c7c67c7f565aed9a4ce389db |
| +@legacy a11e58218b588ebe0ebe25d100df01cbbf2274bf58497965a7aa1bce3d4ed7af internal/activator/control.go systemctlControlGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input (J4, as systemctlUnitState): new (rootfs Plan 2 Task 9): runs systemctl show -p ControlGroup --value <unit> as carlos, an unprivileged query of PID 1, for a unit name built by unitNameFor from the row's host; the answer is systemd's own; it starts and stops nothing; no root decision;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: a failed systemctl show now returns unitStateError(err), appending systemctl's own stderr (<=200 bytes) to the error text for the log; the command, its arguments, the unit name and the parsing of a successful answer are unchanged;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@92 088595678d0fac6077364a69bb82f2ab6b5899e2929e14bdb653effa74d955cb |
| +@legacy d3aa266287b251ec3b8fa54b976920a6bed55a9d6f9d32f8a69a17d0578846ea internal/activator/control.go systemctlUnitMainExit legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-worker-exit;basis=new: runs `systemctl show -p InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus <unit>` as the agent (no privilege), the same shape as systemctlUnitState and systemctlControlGroup; the unit name is the handle's own (unitNameFor/rootfsUnitFor), not tenant input; output parsed as four key=value strings into MainExit (Astra R1 P2: SuccessExitStatus is the unit's clean-exit policy as systemd loaded it from the shipped template);rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@94 349a27a6fea02bdd1c779fed6bd7897d413de7efdd5f66d83d2bfa00924fb840 |
| +@legacy 39e6bd69d653796b3503c07d4bf096d0462f067e912b40dacebcb76aad075a24 internal/activator/control.go systemctlUnitState legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged (#451 diagnosis: tells a lost D-Bus at shutdown from other failures);rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@97 00b7cb62402c9a253da54b7ea5b025e44d30ea8eacb11fac7eff96598bc1534f |
| +@legacy d6f51086f60da147818c40d1ca5f4aa817b350b10b03a50cbe3832bf1cb45b5d 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.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@91 e41d8b5a405f2d90848811e07e0d65192bb8fc62c6ea20c2e954a65bb966995d |
| +@legacy 3ebfc92c06e7c2be3d4439efefb9c9551f0590448b4eadac3a86bdffbbb91899 internal/demobuild/unit.go var systemctl legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Executes fixed /usr/bin/systemctl with a scrubbed fixed environment and bounded output; callers supply platform-derived unit names and fixed operations for offline build supervision.;rev3=census-ruling-gvisor-demos;basis=Task 9: Preserve fixed executable/environment/arguments/bounded output; attach captured output to internal errors for root logging before sanitization.;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: /usr/bin/systemctl through internal/systemd.Command(SystemctlAbsolute) with the same fixed Env and capped stdout/stderr writer under the caller's context; mutations get no deadline of their own, queries also QueryTimeout; no new read, path or input file:Command@100 d3d82d8be48093d75731d6f2c035b0d36370b2d229d2cbae7e312b7e2b05af15 |
| +@legacy 3bd150216a17aa0a59c82a33ebd803b649152aa3808b312ea6da1b74d9022686 internal/hairpin/native_linux.go MainProcess legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Execute fixed systemctl show carlos-edge.service MainPID/LoadState, parse PID and bind kernel starttime/boot via Identity. Root trusts systemd/kernel identity, not request PID alone; executable resolved through service PATH, no request-controlled command or arguments.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@70 6af37721143f0b9201be654a1de80d2db09abf8946efa29274090af281898904 |
| +@legacy 171c0cfa503352343fa9e3dd5358999afdcb3261e06d60d589aa0bd1c5975e62 internal/host/dbreads_linux.go dbReadUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-db-region-forward-1;basis=root-input (J4); the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): new, systemctl list-units of carlos-dbread@ units, readable without privilege, for the orphan rule; makes no root decision;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@66 02ddf059357bb3fe7454bcedcbe0a9806e3f6d9533ffcd2615148a2c35653a85 |
| +@legacy 58bc4ee721cae67c6f9c08cbd7868d378716f36435b0f050c3aef27cd1295599 internal/host/egress_source.go systemctlOutput legacy accepted-legacy accepted-legacy;rev3=census-ruling-instance-egress-sizes-328-329;identity=instance control (/opt/carlos/carlos instance-control, carlos-instance-control.service, root), on both branches;basis=root-input (J4, as UnitBackend.systemctl): new (#328 plan 2 Task 5): runs systemctl (by name, as instancectl's runWithClaim already does) with its caller's arguments and returns the combined output; one CommandContext site. Its callers: the rail's batched show of '*.service' (a constant), unitRunsAsAgent's show -p User -p DynamicUser of a named-unit row's Route.Unit (agent-written; ValidUnitName, no leading -, one argument, a read-only verb, once per snapshot), and the EgressAsserter's set-property, show and try-restart on host slices and the services in their cgroups (instancectl, its own rows); it decides nothing itself;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@89 117512b6a961870cc484d541e083fa9910cfb261ed0f801b32c99a83a01280ce |
| +@legacy 4443d07994efabb921d98acf1ff2b05cf8ecf4548de9410336f21c5bf6ec5584 internal/host/group_maintenance_verbs_linux.go maintenanceEdgeProcess legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2;basis=Runs fixed /usr/bin/systemctl show carlos-edge (fixed env, timeout) and reads /proc/<pid>/stat for the edge identity; observational.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5 fix 2: systemctl's MainPID answer is parsed by maintenanceMainPID, which tells a confirmed stop (MainPID 0, errEdgeStopped) from a malformed answer (errEdgeMainPID); both keep the existing error text; the reads are unchanged;rev3=census-ruling-bounded-systemctl;basis=bounded query: /usr/bin/systemctl show MainPID through internal/systemd.Command(SystemctlAbsolute) with the same fixed Env, Dir / and bounded stdout writer, under the same 1 s caller deadline (WaitDelay stays 1 s); no new read file:Command@184,file:Open@539,file:ReadAll@655 3ce80470274c16a87b2ab5f06a64872cc0068ad3d7b76617032c738b582cac2c |
| +@legacy 3cbdc1f08f13b1f118208e4ed65b07dcfdd45d8c04431dff19d7ae97e1df91cc internal/host/restartwatch.go platformUnitRestarts legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs fixed argv "systemctl show --property=Id --property=NRestarts --property=ActiveState carlos-*.service" under a 5s deadline; the glob is a constant, parsed output only feeds the restarts alert;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@166 56e234ed7f6f059823e79fa2fc39129af88f53009c0f96d4ddea03c92385a852 |
| +@legacy a69c9d191c02e1680f3355efd0af68dfacb343be30edddf372b57f0321f9288a internal/host/runscensure.go runscSystemctl legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Execute systemctl with fixed enumeration/start verbs and root-generated unit names, context bounded. No shell or request-provided executable.;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@88 2b0ca83ee738c3bd92367e988572b5ba6b757d703871bb07a2ba620e787117f0 |
| +@legacy c9b8cde48856a9147defeb19381b66069bc48e430d1c7e8cc250f2d77947cb91 internal/instancectl/hairpin.go newHairpinResetServer legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new function, same Systemctl runner as the one previously built inline in ClearGroupHairpin;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@168 f5447b281cde2fe93a8faf5ee4df9ec787e11cd1d6b997d2ec9ffde7626abf56 |
| +@legacy f02da6932ef41c83324a25c7c7e0b27a92bbdb9d4526dd2d31303daa4b85ec90 internal/instancectl/peer_linux.go systemdEdgeMainPID legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@143 a66697246ffe04f2567dc53266272e134f2e4f000ee3f0ac75ad9b21429536b4 |
| +@legacy b4cdcd5963121fb12773a6357eea6832145d3d20be6e5e9b83400bfcd1ed8c6f internal/ops/ops.go systemdDaemonReload legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs the fixed argv "systemctl daemon-reload" under a one-minute deadline; no input from any caller;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same daemon-reload under its existing 1 min context through internal/systemd.Command; a mutation gets no deadline of its own; no new read file:Command@143 bc3a85e5fd165ec26ca9e7f27d08ee4fb0c57a9205dac58571b3c581af211acf |
| +internal/caps/converge.go Ops.query authority E4,J1,J4 root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@183,file:Query@46,file:Query@72 9bfc1d226bea2f1b22b0673f3db8445020e31dc1c1c255a264c74bd56f75a696 |
| +internal/caps/converge.go Ops.systemctl authority E4,J1,J4 root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input; its error now wraps systemctl's with %w instead of %v, same text file:Command@246 8e9bdb9239b69abf208684bf90d14838468c6634c6bd0720a60190f198ba1285 |
| +internal/host/adopt_advice.go unitsAreActive diagnostic H3 no-effect;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@264 803af2fa5482e4960c8a98a499dd8ed1715f9346a2e6ff1a253a9ba1b3211b88 |
| +internal/host/agent.go systemctlStartUnit legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@191 e48d6f752a6ed9962add99c9c56fe62f24d1dcfa7c32acb83c61ab42dcc4ed9e |
| +internal/host/agent.go systemctlTryRestart legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@187 a1d2f2fc4c0d06dddc02d29ab762060a7b7aa7793e59b90d95a8c4d8fcadf92e |
| +internal/host/agent.go systemctlTryRestartUnit legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@201 31d32fd1e711bf81ab0da6fff590f993e4e1baf79ceb1d2a456a9fcc3d0c4952 |
| +internal/host/bootstrap.go systemctl legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@176 e284a9691f4263cad090bc0021285ed1bf64cb4b66be4d10d54acc74505da175 |
| +internal/host/probes.go adoptTimerActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@133 b4c0f0b143d6b2f9965c7274d8963699fc85d3097d240d8502e02f5315eba69c |
| +internal/host/probes.go configPathActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@133 d10e078a2dd56a50e84d6e228c2f3378f349829ec878053a4e31cabfdb37f301 |
| +internal/host/probes.go restartPathActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@135 df88c565c10c82811bb2a9fe6812a20b0f9020077340d7976ff8dd96c27bdc12 |
| +internal/host/probes.go systemUpdatePathActive legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@145 4bd96b1b34d911a67c46c2e6bb87f594ee12e0fb65a37007265f18c417b34a19 |
| +internal/host/systemapply.go productionSysOps authority D,F,J4 root-input;kept=D,F;scope=protected-decision-only;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: both closures run through internal/systemd.Command under context.Background(); the sysOps seam's mutations (the edge restart, stop, start, daemon-reload) get no deadline, exactly as exec.Command, and its queries (is-active, show) and edgeStartedThisBoot's show QueryTimeout (30 s); the round-1 18 min class is removed; no new read, path or input file:Command@2092,file:Command@314,file:CommandContext@760 a40e0882ecd7c38cbefb4a1b757d2dfaa503b42b9aa0b20e3629f8fb75e5f127 |
| +internal/host/systemunits.go systemctlProbe legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@155 ca1780c62a0f1bbf2fc2dccffc7e2bc207a2d4de5d39470ce5f2e008b19c626f |
| +internal/host/unitops.go daemonReload legacy accepted-legacy accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl daemon-reload, once per pass when a marker exists;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@168 4eb5d810cd716bf51d3f4577e78ece730811984e4e606aa3c5f2aab73c3251f6 |
| +internal/host/unitops.go probeUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl show -p Id,LoadState,EnvironmentFiles <units>, unit names already passed DeliverableUnitName; parsed positionally, a count mismatch is an error;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@254 738441a6ac4e3bc65f7b445d12c9c11da76b7f88f504cd3886ff41c3a3d5eb92 |
| +internal/host/unitops.go systemctlRestartUnit legacy accepted-legacy accepted-legacy;rev3=census-ruling-named-unit-delivery-114;basis=new: exec systemctl restart <unit>, only for a unit root bound to the route through Bind after a successful reload and an exact EnvironmentFiles match;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@195 2022d180cf309b786208541502b510fead1d07bd4fefdccaaf273a2ab06387c5 |
| +internal/host/unitsettle.go systemctlVerb authority B3,J1,J4 root-input;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same mutating systemctl verb, arguments and output through internal/systemd.Command; a mutation gets no deadline of its own, so it runs under context.Background() exactly as exec.Command ran it; no new read, path or input file:Command@187 ea9326edf452f9f15d51f1d4bcf50f8498681df9dd94716aa9ce5f306052af0c |
| +internal/host/unitsettle.go systemdUnits.JournalTail authority B3,J1,J4 root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same journalctl arguments and stdout through internal/systemd.Command(Journalctl), under QueryTimeout (30 s); a timeout gives an empty tail, as any failure did; no new read file:Command@168 66c01bcdc845552c0434d85d1515426774b75f5d2b280dd67940734555fa8416 |
| +internal/host/unitsettle.go systemdUnits.Show authority B3,J1,J4 root-input;rev3=census-ruling-bounded-systemctl;basis=bounded query; a deadline reached through temporary observation failures is a temporary UnitNotUpError, so the rollback restart still replaces the process and the version is not poisoned: the same show properties and parser through internal/systemd.Command under context.Background() and QueryTimeout (30 s); its error, a TimeoutError included, is returned as before; no new read file:Command@161 a3158f480bd14d1d964c71ca4701c730dadeef879bf6ea2ea8d797fbbd724e1f |
| +internal/instancectl/gvisorprobe.go Server.runGVisorProbe legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Task 6 fix round 1, applying the controller rulings: serialized probe construction uses root random nonce/fixed paths, root-only O_EXCL fixture, abstract listener, typed verified bundle/unit and context recheck. Read bounded root-owned nonce-bound output and the guest socket handshake; inspect kernel/proc runtime and limits while guest waits. Termination uses inactive/not-loaded state, no job/PIDs and empty cgroup, never per-command stop-post records. Keep the prior pass during the run and publish report plus runtime identity once, after cleanup; any failed attempt invalidates it and records the bounded diagnostic. A private package-test-only operations struct substitutes paths, executable preparation and output opening; production keeps GVisorProbePaths, fixed output/procfs, ensureExe and execsandbox.OpenRootFile. No new tenant-controlled path, launch/source/database read, or runtime-state read. CI fix: route serialized nonce fixture/output cleanup through existing pinned removeGenFiles owner with closed gVisor selectors and fixed probe paths. Existing reads and stop proof unchanged; no new raw removal owner.;rev3=census-ruling-gvisor-probe-diag;basis=Diagnostic only: the failure dump runs journalctl for the fixed probe unit only once a start was asked for, with --since=@<this attempt's start time>, so it no longer replays earlier attempts; a failure before the start logs this attempt's own fail line (taken before the start-up mount lines are prepended) instead. No new path, input or systemctl verb; probe steps unchanged.;rev3=census-ruling-bounded-systemctl;basis=the failure diagnostic calls the new Server.Journal seam with the same journalctl arguments minus the program name, instead of Server.Run with "journalctl" first; nil Journal skips it as nil Run did; no new path, input or verb file:Lstat@3275,file:OpenFile@2638,file:Read@2328,file:ReadAll@5637 90c42203b2b5bc263f0f337991e3138e54c1e4cf17f69c10fc7614cce0527255 |
| +internal/instancectl/server.go type Server legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read;rev3=census-ruling-agent-start-demo-3;basis=Retain the snapshot supervisor in instance-control state; no new request-selected path. Census read-site delta: unchanged (1).;rev3=census-ruling-gvisor-demos;basis=Retain Task 1 mode/error/readiness fields, baseline/runtime callbacks, Task 4 per-host validated staged descriptors and root-selected probe nonce. Fix round 1 adds a private writer-operation seam assigned only in package tests, after the unchanged GVisorID admission check; production defaults still call the same checked constructor, WriteRootfs, WriteBundle and verifier. No new direct read or request-controlled callback. Task 5: private injected removal seam for unprivileged tests; production default removes only root-derived bundle and skeleton after both-family proof inside existing start fence. No new request field or agent-selected unit. Task 6: Retain serialized probe nonce, runtime-set identity verifier/token, fixed claims flag, bundle discovery root, and private unprivileged identity seam. No request-controlled callback or path; existing declaration read-site classification unchanged. Task 6 fix round 1: private gvisorProbeTestOps is set only in package tests; production defaults retain all fixed paths and the checked root output opener. No externally supplied callback or new direct read. Final R1 P2: retain fixed skeleton parent and concurrent per-instance cleanup refusals; no direct read or external configuration field. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.;rev3=census-ruling-same-box-edge-fence;basis=Field declarations only: NFT (the nft runner; nil never loads the fence), EdgeFenceOff (host.env CARLOS_EDGE_FENCE=off), and under the existing denyMu/mu: fenceAddrs, fenceReason, fenceRetry, denyApplied. No read added.;rev3=census-ruling-bounded-systemctl;basis=new field Journal, the journalctl seam for the gVisor probe's diagnostic; field declaration only; no read added file:Statfs@5239 d5c89f7179dcd67a27771c87050f340a2c9637b2b760ff322ca600ab8d3d1144 |
| +internal/systemd/command.go Cmd.run legacy accepted-legacy accepted-legacy;rev3=census-ruling-bounded-systemctl;basis=new: the exec.CommandContext for a mutation: the fixed program under the caller's context alone, no deadline or WaitDelay of its own (as exec.CommandContext before); queries go to bounded; reads nothing itself file:CommandContext@451 82e395ec0a5c8281445471b2419badb060994cc098f4a091b1ae27ee54e5f2f6 |
| +internal/systemd/command.go Command legacy accepted-legacy accepted-legacy;rev3=census-ruling-bounded-systemctl;basis=new: constructor of a systemctl/journalctl run; the program is one of three fixed names (systemctl, /usr/bin/systemctl, journalctl), never caller-supplied; arguments are the caller's, as with exec.Command file:Command@5 89666d774272947697007ae0f8c43133bd4b42b355173011021f559cb83a92ec |
| +internal/systemd/command.go bounded legacy accepted-legacy accepted-legacy;rev3=census-ruling-bounded-systemctl;basis=new: runs a query's fixed program under the caller's context and QueryTimeout, kills at the bound (WaitDelay 1 s) and returns a TimeoutError; reads nothing itself file:CommandContext@255 09e124141295f87c9db2272e59bac14c4af36715418ee11c87ece3432dbb910d |
| +internal/activator/backend_unit.go UnitBackend.systemctl legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-gvisor-demos;basis=Task 5: gate launch using startup-captured mode and existing route/role/layout before preparation or execution; migrate structured root start identity and reject mismatches. Unsupported gVisor paths refuse; native behavior and existing root authority checks retained. No new root read source.;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@332 e2065e995f5280ef568751e4e2ee3ffd5123d043c7c67c7f565aed9a4ce389db |
| +internal/activator/control.go systemctlControlGroup legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=root-input (J4, as systemctlUnitState): new (rootfs Plan 2 Task 9): runs systemctl show -p ControlGroup --value <unit> as carlos, an unprivileged query of PID 1, for a unit name built by unitNameFor from the row's host; the answer is systemd's own; it starts and stops nothing; no root decision;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: a failed systemctl show now returns unitStateError(err), appending systemctl's own stderr (<=200 bytes) to the error text for the log; the command, its arguments, the unit name and the parsing of a successful answer are unchanged;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@92 088595678d0fac6077364a69bb82f2ab6b5899e2929e14bdb653effa74d955cb |
| +internal/activator/control.go systemctlUnitMainExit legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-worker-exit;basis=new: runs `systemctl show -p InvocationID,ExecMainCode,ExecMainStatus,SuccessExitStatus <unit>` as the agent (no privilege), the same shape as systemctlUnitState and systemctlControlGroup; the unit name is the handle's own (unitNameFor/rootfsUnitFor), not tenant input; output parsed as four key=value strings into MainExit (Astra R1 P2: SuccessExitStatus is the unit's clean-exit policy as systemd loaded it from the shipped template);rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@94 349a27a6fea02bdd1c779fed6bd7897d413de7efdd5f66d83d2bfa00924fb840 |
| +internal/activator/control.go systemctlUnitState legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-managed-fleets-1c-451;basis=error path only: as systemctlControlGroup, unitStateError(err) on a failed systemctl show; command, arguments, unit name and parsing unchanged (#451 diagnosis: tells a lost D-Bus at shutdown from other failures);rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@97 00b7cb62402c9a253da54b7ea5b025e44d30ea8eacb11fac7eff96598bc1534f |
| +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.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@91 e41d8b5a405f2d90848811e07e0d65192bb8fc62c6ea20c2e954a65bb966995d |
| +internal/demobuild/unit.go var systemctl legacy accepted-legacy accepted-legacy;rev3=census-ruling-agent-start-demo-1;basis=Executes fixed /usr/bin/systemctl with a scrubbed fixed environment and bounded output; callers supply platform-derived unit names and fixed operations for offline build supervision.;rev3=census-ruling-gvisor-demos;basis=Task 9: Preserve fixed executable/environment/arguments/bounded output; attach captured output to internal errors for root logging before sanitization.;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: /usr/bin/systemctl through internal/systemd.Command(SystemctlAbsolute) with the same fixed Env and capped stdout/stderr writer under the caller's context; mutations get no deadline of their own, queries also QueryTimeout; no new read, path or input file:Command@100 d3d82d8be48093d75731d6f2c035b0d36370b2d229d2cbae7e312b7e2b05af15 |
| +internal/hairpin/native_linux.go MainProcess legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b;basis=Execute fixed systemctl show carlos-edge.service MainPID/LoadState, parse PID and bind kernel starttime/boot via Identity. Root trusts systemd/kernel identity, not request PID alone; executable resolved through service PATH, no request-controlled command or arguments.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@70 6af37721143f0b9201be654a1de80d2db09abf8946efa29274090af281898904 |
| +internal/host/claimfilesseed_delegation_linux.go filesSeedEdgePID authority C,J4 rev3=PROPOSED-seed; installed edge MainPID, stable controller identity and kernel cgroup identity, owner and delegated controls; root rejects non-controller and unprepared delegation; non-Linux refuses;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@141 8ec1fa8648d75ca423d46dbd76042cf8376fc5a87b99e18e2de2adf6a07228df |
| +internal/host/claimjournal_migration_linux.go var claimSystemctl authority C,G,J4 root-input;kept=C,G;scope=protected-decision-only;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@89 ecc5c29ab9b54955f8f020efcd5b1f262dbd9a2baf82802e50ded56bcca82243 |
| +internal/host/claimlaunch_production.go claimLaunchFor authority C,D,J4 rev3=PROPOSED-seed; authenticated capability peer and production root delegation verifier; capability validates only and creates no writer or launch;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input data-literal@414,file:Command@605 d3bf3b9fe12a445ecef2dfc73b2ac9533cd661c538dfee3ebe8c821481cde601 |
| +internal/host/claimstop_production.go NewProductionClaimStopHandler authority C,J4 rev3=PROPOSED-p3;run=20;identity=root instance-control uid 0;basis=root authority selects stopped-agent containment observation without changing peer authentication or nonparticipating construction;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@1106,file:Read@786 b9a53d1d569b144adff3e0f91ecb3d70e2b96e4c754a7d8549ad4e27a4e60596 |
| +internal/host/claimstop_writers_linux.go agentUnitCgroup authority C,G,J4 root-input;kept=C,G;scope=protected-decision-only;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@145 3a6128f5d550c8941e1822cef306821ff331e136cf1ab2d624324265294ed317 |
| +internal/host/claimstop_writers_linux.go rootStopAgentCgroup authority C,J4 rev3=PROPOSED-p3;run=20;identity=root instance-control uid 0;basis=reads systemd unit identity, active state, slice and cgroup to observe recorded containment even after the edge unit stopped;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@149 2dfa96a7f8a5ee3008b7890e633b7e149109d589662ffc3e2c5bbbf3ad1f1be8 |
| +internal/host/claimunit_socket_migration_linux.go captureProductionClaimUnitSocket authority E2 PROPOSED E52: Root reads systemd MainPID and verifies the connected Unix peer against that process/descendants and the retained predecessor cgroup, with socket identity rechecked after connect.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@417 a304bfd4c967b6dfc239fd2cc1fe64b3e5cf73e5d3341604bd956cd6b0aa64a4 |
| +internal/host/dbreads_linux.go dbReadUnits legacy accepted-legacy accepted-legacy;rev3=census-ruling-db-region-forward-1;basis=root-input (J4); the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): new, systemctl list-units of carlos-dbread@ units, readable without privilege, for the orphan rule; makes no root decision;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@66 02ddf059357bb3fe7454bcedcbe0a9806e3f6d9533ffcd2615148a2c35653a85 |
| +internal/host/egress_source.go systemctlOutput legacy accepted-legacy accepted-legacy;rev3=census-ruling-instance-egress-sizes-328-329;identity=instance control (/opt/carlos/carlos instance-control, carlos-instance-control.service, root), on both branches;basis=root-input (J4, as UnitBackend.systemctl): new (#328 plan 2 Task 5): runs systemctl (by name, as instancectl's runWithClaim already does) with its caller's arguments and returns the combined output; one CommandContext site. Its callers: the rail's batched show of '*.service' (a constant), unitRunsAsAgent's show -p User -p DynamicUser of a named-unit row's Route.Unit (agent-written; ValidUnitName, no leading -, one argument, a read-only verb, once per snapshot), and the EgressAsserter's set-property, show and try-restart on host slices and the services in their cgroups (instancectl, its own rows); it decides nothing itself;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@89 117512b6a961870cc484d541e083fa9910cfb261ed0f801b32c99a83a01280ce |
| +internal/host/group_maintenance_verbs_linux.go maintenanceEdgeProcess legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2;basis=Runs fixed /usr/bin/systemctl show carlos-edge (fixed env, timeout) and reads /proc/<pid>/stat for the edge identity; observational.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 5 fix 2: systemctl's MainPID answer is parsed by maintenanceMainPID, which tells a confirmed stop (MainPID 0, errEdgeStopped) from a malformed answer (errEdgeMainPID); both keep the existing error text; the reads are unchanged;rev3=census-ruling-bounded-systemctl;basis=bounded query: /usr/bin/systemctl show MainPID through internal/systemd.Command(SystemctlAbsolute) with the same fixed Env, Dir / and bounded stdout writer, under the same 1 s caller deadline (WaitDelay stays 1 s); no new read file:Command@184,file:Open@539,file:ReadAll@655 3ce80470274c16a87b2ab5f06a64872cc0068ad3d7b76617032c738b582cac2c |
| +internal/host/restartwatch.go platformUnitRestarts legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs fixed argv "systemctl show --property=Id --property=NRestarts --property=ActiveState carlos-*.service" under a 5s deadline; the glob is a constant, parsed output only feeds the restarts alert;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@166 56e234ed7f6f059823e79fa2fc39129af88f53009c0f96d4ddea03c92385a852 |
| +internal/host/rootgeneration_services_linux.go generationServiceShow authority E2 rev3=PROPOSED-claims-on-gate-recover;identity=root generation kernel reader uid 0;basis=new unit, the systemctl show of ControlGroup, MainPID, ExecStart, FragmentPath and DropInPaths moved out of generationServiceReader unchanged, at its class.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@103 8953d2fbdde4fa9c2d2cc01bbb79eb17afc54b38b8395655d769bc215d5d3569 |
| +internal/host/runscensure.go runscSystemctl legacy accepted-legacy accepted-legacy;rev3=census-ruling-gvisor-demos;basis=Execute systemctl with fixed enumeration/start verbs and root-generated unit names, context bounded. No shell or request-provided executable.;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@88 2b0ca83ee738c3bd92367e988572b5ba6b757d703871bb07a2ba620e787117f0 |
| +internal/instancectl/hairpin.go newHairpinResetServer legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new function, same Systemctl runner as the one previously built inline in ClearGroupHairpin;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged for mutations, bounded for queries: the same caller-supplied systemctl arguments and output through internal/systemd.Command under the caller's context; a mutating verb gets no deadline of its own (exactly as before), a query verb also QueryTimeout (30 s); no new read, path or input file:Command@168 f5447b281cde2fe93a8faf5ee4df9ec787e11cd1d6b997d2ec9ffde7626abf56 |
| +internal/instancectl/peer_linux.go systemdEdgeMainPID legacy accepted-legacy accepted-legacy;rev3=census-ruling-ha-p1a-433;basis=root (carlos-instance-control.service): the same exec productionPeerOK's closure ran before, moved out unchanged: systemctl show -p MainPID --value carlos-edge.service, fixed argv, 3 s timeout; output that does not parse is 0 (no MainPID), which edgePeer refuses. No input from a peer, tenant or agent reaches the argv.;rev3=census-ruling-bounded-systemctl;basis=bounded query: the same systemctl query (show, is-active, is-enabled or list-units), arguments and output, now run through internal/systemd.Command under the caller's context and QueryTimeout (30 s), whichever ends first; at the bound the process is killed and a temporary TimeoutError naming the verb and unit is returned; no new read, path or input file:Command@143 a66697246ffe04f2567dc53266272e134f2e4f000ee3f0ac75ad9b21429536b4 |
| +internal/instancectl/server.go runWithClaim authority C,D,G Claim instance controller adds held-release RPC dispatch within existing launch/participation execution boundary.;rev3=census-ruling-rootfs-apps-2;basis=takes a RegistryView (HostApp and HostRuntime) for the bare hostApp, and the production Server literal gains HostRuntime, ProbeImage: BuildProbeImage, ProbeImageFile: ProbeImagePath, RootfsProbeOut under /run/carlos-control and DenyEvery: 10s; this body reads nothing new itself; the readers it wires (instanceRegistryHostRuntime, BuildProbeImage, the rootfs probe's output) are decision rows;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 4 and #329 plan 3 Task 5: takes the egress asserter as a parameter, sets it on the production Server literal (Egress) and starts its 30 s Loop beside probeLoop and diskLoop; the literal also names the fixture check ProbeFixturesOK (renamed in plan 2 Task 14). It sets no control drop-in directory: plan 3's ControlDropInDir default (/run/systemd/system.control) was deleted with removeGenControlDropIn in ef38e13b (the P1 EROFS fix), so instance control names systemd's control directory only to read it (TrustedDropinReader). The same four sites (the two exec.CommandContext closures, statfsBytes, the data literal), offsets moved; no read added.;rev3=census-ruling-agent-start-demo-1;basis=Wires root-owned demo config and existing fixed paths into the service.;rev3=census-ruling-region-ha-p3b;basis=Resume root-owned hairpin state before probes/control service work; verify current systemd agent identity and kernel fence/addresses, restore pidfd watch or revoke stale state. Same direct exec/statfs/data sites; indirect inputs are protected root snapshot/state and kernel evidence, never receipt data.;rev3=census-ruling-agent-start-demo-3;basis=Construct the demo snapshot supervisor for configured demo boxes; startup cleanup gates builder readiness. Census read-site delta: unchanged (4).;rev3=census-ruling-gvisor-demos;basis=Retain sandbox modes and error; bind host-provided baseline and runtime callbacks without importing host templates. Existing reads unchanged. Task 6: Capture HostClaims once from ControlConfig/hostwrite.Enabled and set the fixed root-owned bundle discovery directory. Existing command and configuration reads unchanged. Task 7: enable gVisor worker construction through fixed unitFamily(roleBuild); readiness proof rechecks sandbox admission and current Ready without reaching the constructor fatal path for transient refusals. Existing command/config reads unchanged. Final R1 P2: wire the fixed /var/lib/carlos/oci-rootfs parent for native readiness evidence; no request-supplied path. Carry the root-only host.env validation callback into Ready; no agent read or caller-selected path.;rev3=census-ruling-same-box-edge-fence;basis=Root. Sets NFT: edgefence.Exec (runs /usr/sbin/nft from PATH with fixed arguments and root-derived stdin, see the envelope) and EdgeFenceOff from os.Getenv; wraps s.Systemctl with guardStarts and calls bindEgressFence; calls denyLocalAddrs once before Serve so a leftover runtime exemption is checked or replaced by the whole deny before any request is served. No new file read; the exec is nft's.;rev3=census-ruling-bounded-systemctl;basis=the production Systemctl closure runs through internal/systemd.Command (same args, combined output, caller ctx; mutations no deadline of their own, queries also QueryTimeout); the new Journal closure runs journalctl through internal/systemd.Command(Journalctl) for the gVisor probe diagnostic only, with the arguments that closure used to pass to Run; no new read, path or input data-literal@2844,file:Command@1151,file:Command@1333,file:CommandContext@1512,file:Exec@2713,file:Statfs@2865 df9e5410ba6b74058bf17b3cbc030c34eefac6cec084688379c85fe63a4da87b |
| +internal/ops/ops.go systemdDaemonReload legacy accepted-legacy accepted-legacy;rev3=census-ruling-ls284;basis=new: runs the fixed argv "systemctl daemon-reload" under a one-minute deadline; no input from any caller;rev3=census-ruling-bounded-systemctl;basis=behaviour unchanged: the same daemon-reload under its existing 1 min context through internal/systemd.Command; a mutation gets no deadline of its own; no new read file:Command@143 bc3a85e5fd165ec26ca9e7f27d08ee4fb0c57a9205dac58571b3c581af211acf |
| +@coverage internal/activator 8592ac09bc0d492a1fbee4e349f184fca7c7a6c68a94d1090e714c81c3a8949c |
| +@coverage internal/caps 14c924de112289dfd0074a473858a0b14eeed717017176474a2e6559f8713860 |
| +@coverage internal/demobuild 34c0e3f2ce8b26e3582aaa0e1386c64fd20e5374dd628ae4462269298074bb32 |
| +@coverage internal/edge 87c5bf0df9843af3c64dca8ab8c1a598d02e37bfaeb324478b168b2dc2a6051f |
| +@coverage internal/hairpin 1bb1d7df97aae8a909d30c98a23d4b6a2ce0f74df88f0455b67740570be2a5fc |
| +@coverage internal/host 90c9040e05de90019de6a794d74b4b161a3fb94df402ba679d521628367bc58f |
| +@coverage internal/instancectl 63f504eaf7adaf5f27ca86fcd432f06034eb13f8df6ba1eccdc93a472f2f3020 |
| +@coverage internal/ops c8359fd403d38e8dee61510c83172554b44108db53f8f9d6a55d0ca67968267e |
| +@coverage internal/systemd e12f9f107581ab1a52e65d345f0f43d40a024f0e25d707a113092eb94feabe25 |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index cb0019cd5..e5eb08f88 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -243,3 +243,4 @@ plan14-root-reads-ha-generations-floor.tsv 7ca068c5c146a679b4726d74fe43cf9c47f97 |
| plan14-root-reads-fix-1193-wal-close-test.tsv 7ca068c5c146a679b4726d74fe43cf9c47f97080f9c08b761a36a9a12a5a3c54 |
| plan14-root-reads-ha-1192.tsv 8df52839a0c961d3721f3a5c3247d06202dae4e00d011844b7117f8e918803d4 |
| plan14-root-reads-audit-bugs-2.tsv 1610abfc476fe45d259494242243756dac9cfec49cdd7f7f7b238329392241a1 |
| +plan14-root-reads-bounded-systemctl.tsv 16cae3931aadfa57a5293d69becf318645681400777cc08972cf08eb449c2457 |
diff --git a/internal/systemd/command.go b/internal/systemd/command.go| new file mode 100644 |
| index 000000000..cb46b1763 |
| --- /dev/null |
| +++ b/internal/systemd/command.go |
| @@ -0,0 +1,276 @@ |
| +// Package systemd runs systemctl and journalctl. Every call in the root |
| +// binary goes through Command (TestSystemctlCallsAreBounded), and the verbs |
| +// fall in two classes: |
| +// |
| +// - A query (show, is-active, is-enabled, list-units, cat, and every |
| +// journalctl call) only reads systemd's state. It runs under the |
| +// caller's context and QueryTimeout, whichever ends first: a systemd |
| +// that stalls (a PID 1 waiting on a child that never execs, a D-Bus |
| +// that never answers) must fail a pass, not hold it, and the host |
| +// agent's loops ask while holding reconcileMu or configSyncMu. At the |
| +// bound the process is killed and the error is a *TimeoutError naming |
| +// the verb and the units. |
| +// - A mutation (start, stop, restart, try-restart, reload, daemon-reload, |
| +// reset-failed, enable, set-property, kill, and any verb not listed as |
| +// a query) gets NO deadline of its own: it runs under the caller's |
| +// context alone, exactly as exec.CommandContext did before this |
| +// package. Killing systemctl does not cancel the job it queued, so a |
| +// timed-out restart is an unknown outcome: the unit may be running the |
| +// new build or still stopping the old one. Every caller today reads a |
| +// mutation's error as "it did not happen" (adoption rolls back and |
| +// starts the old build, which is a no-op over a new process that did |
| +// come up), so bounding mutations needs a way to reconcile the job's |
| +// outcome first. That is follow-up work with its own spec (amadan |
| +// discussion #1214), and so is reading a query that failed until a |
| +// deadline as an unknown outcome rather than a failure: host's settle |
| +// check still calls that "not up", because its recovery replaces the |
| +// process, where a rollback with a plain start would leave a new |
| +// process running under the old link. |
| +// |
| +// When the caller's own context ends a call, the error is os/exec's, |
| +// unchanged. Every other result (output, exit status, *exec.ExitError with |
| +// its Stderr) is exactly what exec.Cmd gives. |
| +// |
| +// The constructor is called Command on purpose: the root-read census |
| +// (internal/provision) counts a call by that name as running a command, |
| +// so each caller keeps its own site there, as it had with exec.Command. |
| +package systemd |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "io" |
| + "os/exec" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// QueryTimeout bounds a verb that only reads (show, is-active, list-units, |
| +// cat, ...) and every journalctl call. systemctl's own D-Bus method calls |
| +// give up after 25 s (sd-bus's default), so a systemd that answers late |
| +// still gets systemctl's own error first; this bound is for a systemctl |
| +// that hangs past that. It also matches the settle check's default window |
| +// (CARLOS_UNIT_SETTLE, 30 s), so one stuck query costs a settle no more |
| +// than its whole window. |
| +const QueryTimeout = 30 * time.Second |
| + |
| +// killWait is a query's exec.Cmd.WaitDelay: how long after the kill the |
| +// call waits for the process's output pipes to close (a child that |
| +// inherited them) before closing them itself. A second, as the group |
| +// maintenance verbs' own MainPID read used before this package. A mutation |
| +// sets none, as before. |
| +const killWait = time.Second |
| + |
| +// Program is the program a Command runs. |
| +type Program int |
| + |
| +const ( |
| + // Systemctl is systemctl, looked up on PATH as exec.Command does. |
| + Systemctl Program = iota |
| + // SystemctlAbsolute is /usr/bin/systemctl, for a caller that runs with |
| + // a fixed environment and no PATH lookup. |
| + SystemctlAbsolute |
| + // Journalctl is journalctl, looked up on PATH. Every verb of it is a |
| + // query. |
| + Journalctl |
| +) |
| + |
| +// programPaths names each Program. Only this package names them (the |
| +// guard test); a test may point one at a fake. |
| +var programPaths = map[Program]string{ |
| + Systemctl: "systemctl", |
| + SystemctlAbsolute: "/usr/bin/systemctl", |
| + Journalctl: "journalctl", |
| +} |
| + |
| +// Cmd is one systemctl or journalctl run. Its exported fields may be set |
| +// before it runs; it runs once. |
| +type Cmd struct { |
| + // Env and Dir are exec.Cmd's: nil and "" inherit the caller's. |
| + Env []string |
| + Dir string |
| + |
| + program Program |
| + args []string |
| +} |
| + |
| +// Command returns the Cmd running program with args. |
| +func Command(program Program, args ...string) *Cmd { |
| + return &Cmd{program: program, args: args} |
| +} |
| + |
| +// Output runs the command and returns its stdout, as exec.Cmd.Output: an |
| +// *exec.ExitError carries stderr. |
| +func (c *Cmd) Output(ctx context.Context) ([]byte, error) { |
| + return c.run(ctx, func(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }) |
| +} |
| + |
| +// CombinedOutput runs the command and returns stdout and stderr together, |
| +// as exec.Cmd.CombinedOutput. |
| +func (c *Cmd) CombinedOutput(ctx context.Context) ([]byte, error) { |
| + return c.run(ctx, func(cmd *exec.Cmd) ([]byte, error) { return cmd.CombinedOutput() }) |
| +} |
| + |
| +// Run runs the command with stdout and stderr going to the given writers |
| +// (nil discards, as exec.Cmd does). |
| +func (c *Cmd) Run(ctx context.Context, stdout, stderr io.Writer) error { |
| + _, err := c.run(ctx, func(cmd *exec.Cmd) ([]byte, error) { |
| + cmd.Stdout, cmd.Stderr = stdout, stderr |
| + return nil, cmd.Run() |
| + }) |
| + return err |
| +} |
| + |
| +func (c *Cmd) run(ctx context.Context, do func(*exec.Cmd) ([]byte, error)) ([]byte, error) { |
| + path, ok := programPaths[c.program] |
| + if !ok { |
| + return nil, fmt.Errorf("systemd: unknown program %d", c.program) |
| + } |
| + setup := func(cmd *exec.Cmd) ([]byte, error) { |
| + cmd.Env, cmd.Dir = c.Env, c.Dir |
| + return do(cmd) |
| + } |
| + bound := c.bound() |
| + if bound == 0 { |
| + // A mutation: the caller's context alone, as before (see the |
| + // package comment). |
| + return setup(exec.CommandContext(ctx, path, c.args...)) |
| + } |
| + return bounded(ctx, path, c.args, bound, setup, c.describe) |
| +} |
| + |
| +// bound is the deadline this command's class gets: QueryTimeout for a |
| +// query, 0 (none of its own) for a mutation. |
| +func (c *Cmd) bound() time.Duration { |
| + if c.query() { |
| + return QueryTimeout |
| + } |
| + return 0 |
| +} |
| + |
| +// query reports whether the command is in the query class: journalctl, or |
| +// a systemctl verb in queryVerbs. Everything else is a mutation. |
| +func (c *Cmd) query() bool { |
| + verb, _ := describe(c.args) |
| + return c.program == Journalctl || queryVerbs[verb] |
| +} |
| + |
| +// describe names the command for a TimeoutError. |
| +func (c *Cmd) describe() (program, verb string, units []string) { |
| + if c.program == Journalctl { |
| + return "journalctl", "", journalUnits(c.args) |
| + } |
| + verb, units = describe(c.args) |
| + return "systemctl", verb, units |
| +} |
| + |
| +// bounded runs a query's path under parent and the bound, killing it when |
| +// either ends, and turns a kill at the bound into a *TimeoutError. When parent |
| +// ended first (the caller's own deadline or cancel), the error is os/exec's, |
| +// unchanged: a caller deadline earlier than the bound ends parent before |
| +// the context derived from it, so parent's state tells the two apart. |
| +func bounded(parent context.Context, path string, args []string, bound time.Duration, do func(*exec.Cmd) ([]byte, error), name func() (string, string, []string)) ([]byte, error) { |
| + ctx, cancel := context.WithTimeout(parent, bound) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, path, args...) |
| + cmd.WaitDelay = killWait |
| + out, err := do(cmd) |
| + if err == nil || ctx.Err() == nil || parent.Err() != nil { |
| + return out, err |
| + } |
| + program, verb, units := name() |
| + return out, &TimeoutError{Program: program, Verb: verb, Units: units, After: bound, Err: err} |
| +} |
| + |
| +// TimeoutError is a query that did not finish within QueryTimeout and was |
| +// killed. It is temporary: the next pass asks again, and an unanswered |
| +// question is not a verdict on a build (release's adopt reads Temporary |
| +// before it poisons a version). |
| +type TimeoutError struct { |
| + Program string // "systemctl" or "journalctl" |
| + Verb string // systemctl's verb; "" for journalctl |
| + Units []string // the units, patterns or assignments the call named |
| + After time.Duration |
| + Err error // os/exec's error after the kill |
| +} |
| + |
| +func (e *TimeoutError) Error() string { |
| + name := e.Program |
| + if e.Verb != "" { |
| + name += " " + e.Verb |
| + } |
| + if len(e.Units) > 0 { |
| + if e.Program == "journalctl" { |
| + name += " -u" |
| + } |
| + name += " " + strings.Join(e.Units, " ") |
| + } |
| + return fmt.Sprintf("%s: no answer within %s; killed", name, e.After) |
| +} |
| + |
| +// Unwrap is context.DeadlineExceeded, so errors.Is sees a timeout. The |
| +// killed process's *exec.ExitError is not exposed: its exit status is the |
| +// kill's, not an answer a caller should read. |
| +func (e *TimeoutError) Unwrap() error { return context.DeadlineExceeded } |
| +func (e *TimeoutError) Timeout() bool { return true } |
| +func (e *TimeoutError) Temporary() bool { return true } |
| + |
| +// queryVerbs only read systemd's state: the query class. Every other verb |
| +// is a mutation. |
| +var queryVerbs = map[string]bool{ |
| + "show": true, "status": true, "cat": true, "help": true, |
| + "is-active": true, "is-enabled": true, "is-failed": true, "is-system-running": true, |
| + "list-units": true, "list-unit-files": true, "list-jobs": true, "list-timers": true, |
| + "list-sockets": true, "list-dependencies": true, "list-automounts": true, "list-paths": true, |
| + "get-default": true, "show-environment": true, |
| +} |
| + |
| +// valueFlags are systemctl's options that take their value as the next |
| +// argument; the value is neither the verb nor a unit. |
| +var valueFlags = map[string]bool{ |
| + "-p": true, "--property": true, "-t": true, "--type": true, "--state": true, |
| + "-s": true, "--signal": true, "--kill-whom": true, "--kill-value": true, |
| + "-H": true, "--host": true, "-M": true, "--machine": true, |
| + "-n": true, "--lines": true, "-o": true, "--output": true, |
| + "--job-mode": true, "--root": true, "--image": true, "--what": true, |
| + "--timestamp": true, "--message": true, "--preset-mode": true, "--drop-in": true, "--when": true, |
| +} |
| + |
| +// describe splits systemctl's arguments into its verb (the first that is |
| +// not an option) and the rest that are not options: the units, patterns or |
| +// assignments the verb acts on. |
| +func describe(args []string) (verb string, units []string) { |
| + for i := 0; i < len(args); i++ { |
| + a := args[i] |
| + if strings.HasPrefix(a, "-") { |
| + if valueFlags[a] { |
| + i++ |
| + } |
| + continue |
| + } |
| + if verb == "" { |
| + verb = a |
| + continue |
| + } |
| + units = append(units, a) |
| + } |
| + return verb, units |
| +} |
| + |
| +// journalUnits is the units a journalctl call reads (-u X, -uX, --unit X, |
| +// --unit=X). |
| +func journalUnits(args []string) []string { |
| + var units []string |
| + for i := 0; i < len(args); i++ { |
| + switch a := args[i]; { |
| + case (a == "-u" || a == "--unit") && i+1 < len(args): |
| + units = append(units, args[i+1]) |
| + i++ |
| + case strings.HasPrefix(a, "--unit="): |
| + units = append(units, strings.TrimPrefix(a, "--unit=")) |
| + case strings.HasPrefix(a, "-u") && len(a) > 2: |
| + units = append(units, a[2:]) |
| + } |
| + } |
| + return units |
| +} |
diff --git a/internal/systemd/command_test.go b/internal/systemd/command_test.go| new file mode 100644 |
| index 000000000..7ab9af3a1 |
| --- /dev/null |
| +++ b/internal/systemd/command_test.go |
| @@ -0,0 +1,231 @@ |
| +package systemd |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// fakeSystemctl puts scripts named systemctl and journalctl first on PATH |
| +// and points SystemctlAbsolute at the systemctl one. Each records its pid |
| +// in dir/pid and then runs body. Nothing here runs the real programs. |
| +func fakeSystemctl(t *testing.T, body string) (dir string) { |
| + t.Helper() |
| + dir = t.TempDir() |
| + script := "#!/bin/sh\necho $$ > " + filepath.Join(dir, "pid") + "\n" + body + "\n" |
| + for _, name := range []string{"systemctl", "journalctl"} { |
| + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) |
| + old := programPaths[SystemctlAbsolute] |
| + programPaths[SystemctlAbsolute] = filepath.Join(dir, "systemctl") |
| + t.Cleanup(func() { programPaths[SystemctlAbsolute] = old }) |
| + return dir |
| +} |
| + |
| +// hang is a fake that never answers: exec replaces the shell, so the kill |
| +// reaches the process holding the pipes. |
| +const hang = "exec sleep 600" |
| + |
| +// gone reports whether the fake's recorded process no longer exists: the |
| +// kill reached it (and Wait reaped it). |
| +func gone(t *testing.T, dir string) bool { |
| + t.Helper() |
| + b, err := os.ReadFile(filepath.Join(dir, "pid")) |
| + if err != nil { |
| + t.Fatalf("the fake never ran: %v", err) |
| + } |
| + pid, err := strconv.Atoi(strings.TrimSpace(string(b))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return errors.Is(syscall.Kill(pid, 0), syscall.ESRCH) |
| +} |
| + |
| +// A query that hangs is killed at the bound, and the error says which verb |
| +// and unit, is a timeout, and is temporary. The bound is QueryTimeout's |
| +// class; the test hands bounded a short one so it need not wait 30 s. |
| +func TestHungQueryIsKilledAtTheBound(t *testing.T) { |
| + dir := fakeSystemctl(t, hang) |
| + const bound = 300 * time.Millisecond |
| + c := Command(Systemctl, "show", "-p", "MainPID", "--value", "carlos-app@shop.example.com.service") |
| + if c.bound() != QueryTimeout { |
| + t.Fatalf("show's bound is %s, want QueryTimeout", c.bound()) |
| + } |
| + start := time.Now() |
| + _, err := bounded(context.Background(), programPaths[Systemctl], c.args, bound, func(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }, c.describe) |
| + took := time.Since(start) |
| + var te *TimeoutError |
| + if !errors.As(err, &te) { |
| + t.Fatalf("err = %v (%T), want a *TimeoutError", err, err) |
| + } |
| + if took < bound || took > bound+killWait+time.Second { |
| + t.Fatalf("returned after %s, want at the %s bound", took, bound) |
| + } |
| + want := "systemctl show carlos-app@shop.example.com.service: no answer within 300ms; killed" |
| + if err.Error() != want { |
| + t.Fatalf("err = %q, want %q", err, want) |
| + } |
| + if !errors.Is(err, context.DeadlineExceeded) || !te.Timeout() || !te.Temporary() { |
| + t.Fatal("a TimeoutError must read as a temporary deadline") |
| + } |
| + var ee *exec.ExitError |
| + if errors.As(err, &ee) { |
| + t.Fatal("a TimeoutError must not expose the kill's exit status as an answer") |
| + } |
| + if !gone(t, dir) { |
| + t.Fatal("the hung systemctl is still running") |
| + } |
| +} |
| + |
| +// journalctl is bounded the same way, and its error names the unit it read. |
| +func TestHungJournalctlIsKilledAtTheBound(t *testing.T) { |
| + dir := fakeSystemctl(t, hang) |
| + c := Command(Journalctl, "-u", "carlos-edge.service", "-o", "cat", "-n", "20", "--no-pager") |
| + if c.bound() != QueryTimeout { |
| + t.Fatalf("journalctl bound %s, want QueryTimeout", c.bound()) |
| + } |
| + _, err := bounded(context.Background(), programPaths[Journalctl], c.args, 200*time.Millisecond, func(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }, c.describe) |
| + want := "journalctl -u carlos-edge.service: no answer within 200ms; killed" |
| + if err == nil || err.Error() != want { |
| + t.Fatalf("err = %v, want %q", err, want) |
| + } |
| + if !gone(t, dir) { |
| + t.Fatal("the hung journalctl is still running") |
| + } |
| +} |
| + |
| +// A verb that changes state gets no deadline of its own: killing systemctl |
| +// does not cancel systemd's job, so a timed-out restart is an unknown |
| +// outcome no caller handles yet. It runs under the caller's context alone, |
| +// as it did before this package: a caller deadline still kills it, with |
| +// os/exec's error and no TimeoutError. |
| +func TestMutatingVerbHasOnlyTheCallersDeadline(t *testing.T) { |
| + for _, args := range [][]string{ |
| + {"restart", "u"}, {"try-restart", "u"}, {"start", "--no-block", "u"}, {"stop", "u"}, |
| + {"reload", "u"}, {"daemon-reload"}, {"reset-failed", "u"}, {"enable", "u"}, {"set-property", "u", "X=1"}, nil, |
| + } { |
| + if b := Command(Systemctl, args...).bound(); b != 0 { |
| + t.Errorf("%v: bound %s, want none", args, b) |
| + } |
| + } |
| + fakeSystemctl(t, hang) |
| + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| + defer cancel() |
| + err := Command(SystemctlAbsolute, "restart", "carlos-edge.service").Run(ctx, nil, nil) |
| + var te *TimeoutError |
| + var ee *exec.ExitError |
| + if errors.As(err, &te) || !errors.As(err, &ee) { |
| + t.Fatalf("err = %v (%T), want the killed process's *exec.ExitError from the caller's deadline", err, err) |
| + } |
| +} |
| + |
| +// SystemctlAbsolute runs the absolute path with no PATH lookup. |
| +func TestAbsoluteSystemctlRunsTheFixedPath(t *testing.T) { |
| + fakeSystemctl(t, `echo "abs $*"`) |
| + t.Setenv("PATH", "/nonexistent") |
| + c := Command(SystemctlAbsolute, "show", "carlos-edge.service") |
| + c.Env = []string{"PATH=/usr/bin:/bin"} |
| + var out strings.Builder |
| + if err := c.Run(context.Background(), &out, nil); err != nil || out.String() != "abs show carlos-edge.service\n" { |
| + t.Fatalf("out = %q, err = %v", out.String(), err) |
| + } |
| +} |
| + |
| +// A caller whose own deadline ends a query first gets os/exec's error, as |
| +// before the helper: the bound did not end it. |
| +func TestCallerDeadlineKeepsExecError(t *testing.T) { |
| + fakeSystemctl(t, hang) |
| + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| + defer cancel() |
| + _, err := Command(Systemctl, "show", "-p", "MainPID", "--value", "carlos-edge.service").Output(ctx) |
| + var te *TimeoutError |
| + if err == nil || errors.As(err, &te) { |
| + t.Fatalf("err = %v, want os/exec's error, not a TimeoutError", err) |
| + } |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) { |
| + t.Fatalf("err = %v (%T), want the killed process's *exec.ExitError", err, err) |
| + } |
| +} |
| + |
| +// Everything that is not a timeout is exec.Cmd's: output, exit status and |
| +// stderr on the ExitError. |
| +func TestAnswersPassThrough(t *testing.T) { |
| + fakeSystemctl(t, `echo "args: $*"; echo complaint >&2; exit 3`) |
| + out, err := Command(Systemctl, "is-active", "carlos-adopt.timer").Output(context.Background()) |
| + if string(out) != "args: is-active carlos-adopt.timer\n" { |
| + t.Fatalf("stdout = %q", out) |
| + } |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) || ee.ExitCode() != 3 || strings.TrimSpace(string(ee.Stderr)) != "complaint" { |
| + t.Fatalf("err = %v, want exit 3 with stderr", err) |
| + } |
| + out, err = Command(Systemctl, "try-restart", "x.service").CombinedOutput(context.Background()) |
| + if !strings.Contains(string(out), "complaint") || err == nil { |
| + t.Fatalf("combined = %q, %v", out, err) |
| + } |
| + out, err = Command(Journalctl, "-u", "x.service").Output(context.Background()) |
| + if string(out) != "args: -u x.service\n" || err == nil { |
| + t.Fatalf("journal = %q, %v", out, err) |
| + } |
| + if _, err := Command(Program(99), "show").Output(context.Background()); err == nil { |
| + t.Fatal("an unknown program ran") |
| + } |
| +} |
| + |
| +func TestBoundPerVerb(t *testing.T) { |
| + cases := []struct { |
| + program Program |
| + args []string |
| + want time.Duration |
| + }{ |
| + {Systemctl, []string{"show", "-p", "MainPID", "--value", "u"}, QueryTimeout}, |
| + {Systemctl, []string{"--no-pager", "list-units", "--all", "carlos-*"}, QueryTimeout}, |
| + {Systemctl, []string{"is-active", "a", "b"}, QueryTimeout}, |
| + {Systemctl, []string{"is-enabled", "a"}, QueryTimeout}, |
| + {Systemctl, []string{"cat", "--no-pager", "u"}, QueryTimeout}, |
| + {SystemctlAbsolute, []string{"list-jobs", "--plain"}, QueryTimeout}, |
| + {Journalctl, []string{"-u", "u"}, QueryTimeout}, |
| + {Systemctl, []string{"restart", "u"}, 0}, |
| + {Systemctl, []string{"daemon-reload"}, 0}, |
| + } |
| + for _, c := range cases { |
| + if got := Command(c.program, c.args...).bound(); got != c.want { |
| + t.Errorf("%v: bound %s, want %s", c.args, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +func TestDescribe(t *testing.T) { |
| + cases := []struct { |
| + args []string |
| + verb string |
| + units []string |
| + }{ |
| + {[]string{"show", "-p", "Id,LoadState", "a.service", "b.service"}, "show", []string{"a.service", "b.service"}}, |
| + {[]string{"show", "--property=MainPID", "--value", "carlos-edge.service"}, "show", []string{"carlos-edge.service"}}, |
| + {[]string{"-p", "X", "show", "u"}, "show", []string{"u"}}, |
| + {[]string{"kill", "--kill-whom=all", "--signal=SIGKILL", "u"}, "kill", []string{"u"}}, |
| + {[]string{"daemon-reload"}, "daemon-reload", nil}, |
| + } |
| + for _, c := range cases { |
| + verb, units := describe(c.args) |
| + if verb != c.verb || !reflect.DeepEqual(units, c.units) { |
| + t.Errorf("%v: %q %q, want %q %q", c.args, verb, units, c.verb, c.units) |
| + } |
| + } |
| + if got := journalUnits([]string{"--no-pager", "--unit=a", "-u", "b", "-uc"}); !reflect.DeepEqual(got, []string{"a", "b", "c"}) { |
| + t.Errorf("journalUnits = %q", got) |
| + } |
| +} |
diff --git a/internal/systemd/guard_test.go b/internal/systemd/guard_test.go| new file mode 100644 |
| index 000000000..9d92bd6dc |
| --- /dev/null |
| +++ b/internal/systemd/guard_test.go |
| @@ -0,0 +1,435 @@ |
| +package systemd |
| + |
| +import ( |
| + "bytes" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// unboundedSystemctlAllowlist names root-graph files that may still run |
| +// systemctl or journalctl some other way, and why. Empty: every call goes |
| +// through this package. A file added here must say what bounds its call. |
| +var unboundedSystemctlAllowlist = map[string]string{} |
| + |
| +// remoteScripts names the root-graph files that build a systemctl command |
| +// line for ANOTHER box's shell, and the text that shows it. Neither rule |
| +// below matches them, because no local exec runs the string; the entry |
| +// keeps the exception named and narrow: the test checks the file still |
| +// holds that text and still has no hit. |
| +var remoteScripts = map[string]string{ |
| + // The edge-stop step of a group roll, sent to the member box over SSM |
| + // (NonInteractiveCommands) and bounded there by /usr/bin/timeout. |
| + "internal/grouproll/box.go": "/usr/bin/systemctl stop carlos-edge.service; ", |
| +} |
| + |
| +// TestSystemctlCallsAreBounded: no non-test Go file of a module package the |
| +// root binary links (linux, amd64 and arm64), outside this package, runs |
| +// systemctl or journalctl other than through Command. Two rules, over the |
| +// file's string constants with simple constant folding (literals, "+" |
| +// concatenation, const and string variables of the same package or |
| +// function, and fmt.Sprintf's format): |
| +// |
| +// - a program name: a string that is exactly "systemctl" or "journalctl" |
| +// or a path ending in /systemctl or /journalctl, wherever it appears |
| +// (exec.Command's name, a seam's first argument, a constant, |
| +// "system"+"ctl"); |
| +// - a local shell: a call anywhere in the file (a function, a method, a |
| +// function literal, a package var initializer, init) whose arguments |
| +// name a shell (sh, bash, dash, by name or path) followed by an |
| +// argument that holds systemctl or journalctl as a word ("sh", "-c", |
| +// "systemctl restart x"; the same string in a variable; |
| +// fmt.Sprintf("systemctl %s", u)). |
| +// |
| +// A sentence that only mentions a program ("run systemctl restart |
| +// carlos-edge" in a message) is neither and passes. What the folding |
| +// cannot see (a string built by another function, a constant from another |
| +// package handed to a shell) is outside the guard; review holds it. |
| +func TestSystemctlCallsAreBounded(t *testing.T) { |
| + if testing.Short() { |
| + t.Skip("lists the root binary's packages with go list") |
| + } |
| + root := moduleRoot(t) |
| + files := rootBinaryFiles(t, root) |
| + if len(files) < 100 { |
| + t.Fatalf("listed only %d root-binary files; the scan would prove nothing", len(files)) |
| + } |
| + byDir := map[string][]string{} |
| + for _, rel := range files { |
| + byDir[filepath.Dir(rel)] = append(byDir[filepath.Dir(rel)], rel) |
| + } |
| + var bad []string |
| + seen := map[string]bool{} |
| + scanned := map[string]bool{} |
| + for dir, rels := range byDir { |
| + if dir == "internal/systemd" { |
| + continue |
| + } |
| + paths := make([]string, len(rels)) |
| + for i, rel := range rels { |
| + paths[i] = filepath.Join(root, rel) |
| + } |
| + for i, hits := range unboundedRuns(t, paths) { |
| + rel := rels[i] |
| + scanned[rel] = true |
| + if _, ok := unboundedSystemctlAllowlist[rel]; ok { |
| + seen[rel] = len(hits) > 0 |
| + continue |
| + } |
| + for _, h := range hits { |
| + bad = append(bad, rel+":"+h) |
| + } |
| + } |
| + } |
| + sort.Strings(bad) |
| + for _, b := range bad { |
| + t.Errorf("%s: run it through internal/systemd.Command, which bounds it", b) |
| + } |
| + for rel := range unboundedSystemctlAllowlist { |
| + if !seen[rel] { |
| + t.Errorf("%s is allowlisted but runs neither program (or left the root binary): drop it from the allowlist", rel) |
| + } |
| + } |
| + for rel, text := range remoteScripts { |
| + body, err := os.ReadFile(filepath.Join(root, rel)) |
| + if !scanned[rel] || err != nil || !strings.Contains(string(body), strconv.Quote(text)) { |
| + t.Errorf("%s: its remote systemctl script %q is gone or left the root binary: drop it from remoteScripts", rel, text) |
| + } |
| + } |
| +} |
| + |
| +// The scan catches each shape a local run has taken or could take, and |
| +// lets messages and a remote script through. |
| +func TestUnboundedRunsScan(t *testing.T) { |
| + src := `package x |
| +import ( |
| + "context" |
| + "fmt" |
| + "log" |
| + "os/exec" |
| +) |
| +const bin = "/usr/bin/systemctl" |
| +const prog = "system" + "ctl" |
| +const restartEdge = "systemctl restart carlos-edge.service" |
| +var pkgScript = "journalctl -u carlos-edge.service" |
| +var run func(context.Context, ...string) (string, error) |
| +var query = func() error { return exec.Command("sh", "-c", "systemctl show carlos-edge.service").Run() } // 13 local shell in a package-level func literal |
| +var edgeRestart = "systemctl restart carlos-edge.service" |
| +var bounce = func() error { return exec.Command("bash", "-c", edgeRestart).Run() } // 14 local shell, package-level literal through a var |
| +var atInit = exec.Command("dash", "-c", "journalctl -u carlos-edge.service") // 15 local shell in a package var initializer |
| +func init() { exec.Command("sh", "-c", "systemctl daemon-reload") } // 16 local shell in init |
| +func f(ctx context.Context, unit string) { |
| + exec.Command("systemctl", "show") // 1 program name |
| + exec.CommandContext(ctx, "journalctl", "-u", "x") // 2 program name |
| + exec.Command(bin) // 3 at the const (line 8) |
| + run(ctx, "journalctl", "--no-pager") // 4 program name |
| + exec.Command("/bin/journalctl") // 5 program name |
| + exec.Command(prog) // 6 at the folded const (line 9) |
| + exec.Command("sh", "-c", "systemctl restart carlos-edge") // 7 local shell |
| + script := "systemctl stop " + unit |
| + exec.Command("/bin/bash", "-c", script) // 8 local shell via a variable |
| + exec.Command("sh", "-c", restartEdge) // 9 local shell via a const |
| + exec.Command("dash", "-c", fmt.Sprintf("systemctl %s", unit)) // 10 local shell via Sprintf |
| + run(ctx, "unshare", "-m", "sh", "-c", pkgScript) // 11 local shell via a package var |
| + exec.Command("sh", "-c", "echo "+"systemctl") // 12 local shell, folded |
| + |
| + _ = "run systemctl restart carlos-edge" |
| + _ = fmt.Errorf("systemctl show %s: failed", unit) |
| + log.Printf("systemctl %s: %v", unit, nil) |
| + exec.Command("sh", "-c", "echo hello") |
| + exec.Command("nft", "list", "ruleset") |
| + remote := "/usr/bin/systemctl stop carlos-edge.service; " |
| + send(remote) |
| + _ = "systemd-journald" |
| +} |
| +func send(string) {} |
| +` |
| + path := filepath.Join(t.TempDir(), "x.go") |
| + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := unboundedRuns(t, []string{path})[0] |
| + if len(got) != 16 { |
| + t.Fatalf("caught %d, want 16:\n%s", len(got), strings.Join(got, "\n")) |
| + } |
| +} |
| + |
| +var ( |
| + shells = map[string]bool{"sh": true, "bash": true, "dash": true} |
| + progWord = regexp.MustCompile(`(^|[^A-Za-z0-9_.@-])(systemctl|journalctl)($|[^A-Za-z0-9_.@-])`) |
| +) |
| + |
| +func programName(v string) bool { |
| + for _, p := range []string{"systemctl", "journalctl"} { |
| + if v == p || strings.HasSuffix(v, "/"+p) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func shellName(v string) bool { |
| + return shells[v] || shells[v[strings.LastIndex(v, "/")+1:]] && strings.HasPrefix(v, "/") |
| +} |
| + |
| +// unboundedRuns scans one package's files together (so package constants |
| +// and variables resolve across them) and reports, per file, each hit as |
| +// line: what. |
| +func unboundedRuns(t *testing.T, paths []string) [][]string { |
| + t.Helper() |
| + fset := token.NewFileSet() |
| + files := make([]*ast.File, len(paths)) |
| + pkgVals := map[string][]ast.Expr{} // package const and var initializers by name |
| + for i, path := range paths { |
| + f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatalf("parse %s: %v", path, err) |
| + } |
| + files[i] = f |
| + for _, d := range f.Decls { |
| + if g, ok := d.(*ast.GenDecl); ok && (g.Tok == token.CONST || g.Tok == token.VAR) { |
| + for _, spec := range g.Specs { |
| + vs := spec.(*ast.ValueSpec) |
| + for j, n := range vs.Names { |
| + if j < len(vs.Values) { |
| + pkgVals[n.Name] = append(pkgVals[n.Name], vs.Values[j]) |
| + } |
| + } |
| + } |
| + } |
| + } |
| + } |
| + out := make([][]string, len(files)) |
| + for i, f := range files { |
| + imports := map[*ast.BasicLit]bool{} |
| + for _, imp := range f.Imports { |
| + imports[imp.Path] = true |
| + } |
| + var hits []string |
| + hit := func(n ast.Node, what string) { |
| + hits = append(hits, fmt.Sprintf("%d: %s", fset.Position(n.Pos()).Line, what)) |
| + } |
| + // Program names: every literal, and every "+" whose operands fold |
| + // to constants (its own operands are then not checked again). |
| + folded := map[ast.Node]bool{} |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.BinaryExpr: |
| + if folded[n] || n.Op != token.ADD { |
| + return true |
| + } |
| + if v, ok := constString(n, pkgVals, 0); ok { |
| + markFolded(n, folded) |
| + if programName(v) { |
| + hit(n, strconv.Quote(v)) |
| + } |
| + return false |
| + } |
| + case *ast.BasicLit: |
| + if v, err := strconv.Unquote(n.Value); n.Kind == token.STRING && !imports[n] && err == nil && programName(v) { |
| + hit(n, strconv.Quote(v)) |
| + } |
| + } |
| + return true |
| + }) |
| + // Local shells, in one traversal of the whole file: every call, |
| + // wherever it is (a function, a method, a function literal, a |
| + // package var initializer, init), with every string binding the |
| + // file and its package make (const, var, := and =), joined without |
| + // regard to scope. A name bound in two places resolves to both, so |
| + // the union can only find more. |
| + vals := map[string][]ast.Expr{} |
| + for k, v := range pkgVals { |
| + vals[k] = v |
| + } |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.AssignStmt: |
| + if len(n.Lhs) == len(n.Rhs) { |
| + for j, l := range n.Lhs { |
| + if id, ok := l.(*ast.Ident); ok { |
| + vals[id.Name] = append(vals[id.Name], n.Rhs[j]) |
| + } |
| + } |
| + } |
| + case *ast.ValueSpec: |
| + // Package-level specs are in pkgVals already. |
| + for j, id := range n.Names { |
| + if j < len(n.Values) && !slices.Contains(pkgVals[id.Name], n.Values[j]) { |
| + vals[id.Name] = append(vals[id.Name], n.Values[j]) |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + shell := false |
| + for _, a := range call.Args { |
| + for _, v := range texts(a, vals, 0) { |
| + if shell && progWord.MatchString(v) { |
| + hit(a, "a local shell runs "+strconv.Quote(v)) |
| + return true |
| + } |
| + if shellName(v) { |
| + shell = true |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + out[i] = hits |
| + } |
| + return out |
| +} |
| + |
| +func markFolded(n ast.Node, folded map[ast.Node]bool) { |
| + ast.Inspect(n, func(m ast.Node) bool { |
| + if m != nil { |
| + folded[m] = true |
| + } |
| + return true |
| + }) |
| +} |
| + |
| +// constString folds e to one constant string: a literal, a parenthesis, a |
| +// "+" of constants, or a name whose only package-level value is one. |
| +func constString(e ast.Expr, pkg map[string][]ast.Expr, depth int) (string, bool) { |
| + if depth > 8 { |
| + return "", false |
| + } |
| + switch e := e.(type) { |
| + case *ast.BasicLit: |
| + if e.Kind != token.STRING { |
| + return "", false |
| + } |
| + v, err := strconv.Unquote(e.Value) |
| + return v, err == nil |
| + case *ast.ParenExpr: |
| + return constString(e.X, pkg, depth+1) |
| + case *ast.BinaryExpr: |
| + if e.Op != token.ADD { |
| + return "", false |
| + } |
| + a, ok := constString(e.X, pkg, depth+1) |
| + if !ok { |
| + return "", false |
| + } |
| + b, ok := constString(e.Y, pkg, depth+1) |
| + return a + b, ok |
| + case *ast.Ident: |
| + if vs := pkg[e.Name]; len(vs) == 1 { |
| + return constString(vs[0], pkg, depth+1) |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// texts is every string e may hold, as far as folding sees: the constant |
| +// parts of a "+" (each operand's texts, and their joins), every value a |
| +// name was given in the function or the package, and fmt.Sprintf's format. |
| +func texts(e ast.Expr, vals map[string][]ast.Expr, depth int) []string { |
| + if depth > 8 { |
| + return nil |
| + } |
| + switch e := e.(type) { |
| + case *ast.BasicLit: |
| + if v, err := strconv.Unquote(e.Value); e.Kind == token.STRING && err == nil { |
| + return []string{v} |
| + } |
| + case *ast.ParenExpr: |
| + return texts(e.X, vals, depth+1) |
| + case *ast.BinaryExpr: |
| + if e.Op == token.ADD { |
| + l, r := texts(e.X, vals, depth+1), texts(e.Y, vals, depth+1) |
| + out := append(append([]string{}, l...), r...) |
| + for _, a := range l { |
| + for _, b := range r { |
| + out = append(out, a+b) |
| + } |
| + } |
| + return out |
| + } |
| + case *ast.Ident: |
| + var out []string |
| + for _, v := range vals[e.Name] { |
| + out = append(out, texts(v, vals, depth+1)...) |
| + } |
| + return out |
| + case *ast.CallExpr: |
| + if s, ok := e.Fun.(*ast.SelectorExpr); ok && s.Sel.Name == "Sprintf" && len(e.Args) > 0 { |
| + if id, ok := s.X.(*ast.Ident); ok && id.Name == "fmt" { |
| + return texts(e.Args[0], vals, depth+1) |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func moduleRoot(t *testing.T) string { |
| + t.Helper() |
| + dir, err := os.Getwd() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for { |
| + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { |
| + return dir |
| + } |
| + parent := filepath.Dir(dir) |
| + if parent == dir { |
| + t.Fatal("no go.mod above the test") |
| + } |
| + dir = parent |
| + } |
| +} |
| + |
| +// rootBinaryFiles is every non-test Go file, relative to root, of every |
| +// module package the root binary links on linux/amd64 or linux/arm64 (as |
| +// internal/rootaws's guard lists them). |
| +func rootBinaryFiles(t *testing.T, root string) []string { |
| + t.Helper() |
| + set := map[string]bool{} |
| + for _, arch := range []string{"amd64", "arm64"} { |
| + cmd := exec.Command("go", "list", "-deps", "-f", `{{if not .Standard}}{{.Dir}}|{{join .GoFiles ","}}{{end}}`, ".") |
| + cmd.Dir = root |
| + cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0") |
| + var stderr bytes.Buffer |
| + cmd.Stderr = &stderr |
| + out, err := cmd.Output() |
| + if err != nil { |
| + t.Fatalf("go list (linux/%s): %v: %s", arch, err, stderr.String()) |
| + } |
| + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { |
| + dir, names, _ := strings.Cut(line, "|") |
| + rel, err := filepath.Rel(root, dir) |
| + if dir == "" || err != nil || strings.HasPrefix(rel, "..") { |
| + continue // the standard library and other modules |
| + } |
| + for _, n := range strings.Split(names, ",") { |
| + if n != "" { |
| + set[filepath.ToSlash(filepath.Join(rel, n))] = true |
| + } |
| + } |
| + } |
| + } |
| + files := make([]string, 0, len(set)) |
| + for f := range set { |
| + files = append(files, f) |
| + } |
| + sort.Strings(files) |
| + return files |
| +} |