carlos / platform Public

Merge remote-tracking branch 'origin/main' into billing-success

Paul Campbell pushed by claude agent, operated by paul@keymail.dev e3334892c01b8e6b2f26c6599c509bd53de592ad parent 71af483parent 11c6f19
32 files changed, +1,421 −125
  • docs/superpowers/notes/census-proposal-rootfs-check-volumes.md +23 −0
  • docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md +29 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md +17 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md +26 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md +18 −0
  • docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md +30 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md +11 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md +13 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md +33 −0
  • docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md +29 −0
  • internal/activator/logsink.go +26 −0
  • internal/activator/prepare.go +12 −7
  • internal/activator/rootfs_process_logs_test.go +112 −0
  • internal/activator/rootfsrelease.go +3 −7
  • internal/applog/record.go +5 −0
  • internal/applog/sink.go +15 −0
  • internal/applog/sink_test.go +26 −0
  • internal/console/apiinstances.go +47 −2
  • internal/console/fleethealth_test.go +124 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/rootfs_check_volumes_census_test.go +37 −0
  • internal/provision/rootfs_fleet_followups_census_test.go +38 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −0
  • internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv +8 −0
  • internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv +15 −0
  • logs_e2e_test.go +120 −59
  • main.go +4 −0
  • ship_check.go +114 −29
  • ship_check_prepare_test.go +210 −0
  • ship_check_probe.go +47 −0
  • ship_check_test.go +225 −20
  • ship_rootfs_unix_test.go +1 −0

CI failed — run details

diff --git a/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md b/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md
new file mode 100644
index 000000000..c23666568
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-rootfs-check-volumes.md
@@ -0,0 +1,23 @@
+# Census approval: rootfs-check-volumes
+
+Ruling `census-ruling-rootfs-check-volumes`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `ship_check.go` `rootfsCheck.runArgs` | body | unchanged (2) | R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. |
+
+Envelopes re-pinned: `.`.
+
+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:
+
+- `ship_check.go` `rootfsCheck.runArgs`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `ship_check_probe.go:prepareCheckDir`: reads +file:Lstat; written legacy, accepted-legacy, frozen
+
+Seal: `94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138` → `042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md b/docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md
new file mode 100644
index 000000000..ec62a9318
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md
@@ -0,0 +1,29 @@
+# Census approval: rootfs-fleet-followups
+
+Ruling `census-ruling-rootfs-fleet-followups`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/prepare.go` `ExecBackend.prepareKeyedAt` | body | unchanged (13) | names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved |
+| `internal/activator/prepare.go` `ExecBackend.prepareWorker` | body | unchanged (6) | passes the worker name (already checked by release.ValidWorkerName at the top) to logEmitter as the process; no read added or moved |
+| `internal/activator/prepare.go` `ExecBackend.logEmitter` | sites | -registry:App, -registry:Host | takes a process name and returns appLineEmitter(b.Logs, rt, process); the route account, app and host reads moved into appLineEmitter; no file read |
+| `internal/activator/rootfsrelease.go` `Service.releaseAppLog` | sites | -registry:App, -registry:Host | returns lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease)); the route reads moved into appLineEmitter; no file read |
+
+Envelopes re-pinned: `internal/activator`, `internal/applog`.
+
+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/activator/prepare.go` `ExecBackend.prepareKeyedAt`: 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 zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged
+- `internal/activator/prepare.go` `ExecBackend.prepareWorker`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: prepare for a worker: the instance's two directories and the worker log socket's, the worker's stale exit records cleared by its name prefix (another worker's and every generation's kept), its log listener bound where root's worker drop-in points StandardOutput=; reads no environment file; binds no control listener; asks no replica gate
+- `internal/activator/prepare.go` `ExecBackend.logEmitter`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route
+- `internal/activator/rootfsrelease.go` `Service.releaseAppLog`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.5]: new; the writer a release's output goes through: each line to the instance's own app log (a.Logs.App(account, app, host, line)); reads the route's account, app and host for the log's key; no file read
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/logsink.go:appLineEmitter`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen
+
+Seal: `042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6` → `78b7e7e30ad3ada44388a4ee16f3950ef888ae03e552477dcbfbb07c51ffb83e`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md
new file mode 100644
index 000000000..e2be49076
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md
@@ -0,0 +1,17 @@
+Reviewed `03e08f569cb2ecd07e0ecdc1ceba5d29f9b8cbad`, round 1/3.
+
+- **P1 — Helper container collides with a valid worker named `prepare`.** Verified in [ship_check.go:210](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:210): the helper requests `<prefix>-prepare`, remains until deferred cleanup, and `start` at line 300 assigns that same name to worker `prepare`. `ValidWorkerName` permits it (`internal/release/rootfs.go:70–85`). A healthy app with this worker fails its check when the runtime rejects the duplicate container name. **Fix:** give the helper a name outside the worker-name grammar and add a regression test whose fake rejects duplicate names. **Invariant:** internal helper names must not overlap valid process names.
+
+- **P2 — Tests do not pin the ownership transition or chmod-before-chown ordering.** [ship_check_prepare_test.go:20](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check_prepare_test.go:20) passes the directory’s existing UID/GID at line 39. Verified by inspection: deleting `Lchown`, or moving it before `Chmod`, would satisfy these assertions. Such regressions would prevent UID 65534 from writing, or make chmod fail without `CAP_FOWNER`. **Fix:** add a capability-constrained integration test that changes ownership from root to 65534 and confirms that user can write; verify both mutations fail. **Invariant:** preparation must establish writable ownership using only `CAP_CHOWN`.
+
+No P3 findings.
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–140. The `file:Lstat` read and `legacy / accepted-legacy` disposition match the container-only caller. It refuses a final symlink or non-directory, changes mode before ownership, and does not recurse.
+- **APPROVE — envelope `.`.** Read changed code in `main.go:21–51`, `ship_check.go:132–153,180–239,299–365`, and `ship_check_probe.go:108–140`; traced import, probe selection and cleanup. Import discards source execution metadata, the helper runs the selected probe with fixed arguments, and no box-root caller gains a new input path. The P1 collision is a functional defect.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The new dispatch writes no record; the `instances` and `sidecars` literals remain unchanged.
+
+Targeted check and census tests were attempted but stopped before compilation: Go could not create its work directory under read-only `$TMPDIR`. `GOCACHE` remained unset. No files changed; no full suites or mutation runs executed.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md
new file mode 100644
index 000000000..cad84514b
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R2.md
@@ -0,0 +1,26 @@
+- **R1 P1 — resolved.** The helper uses `<prefix>_prepare`, outside the worker-name grammar ([ship_check.go:215](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:215)). The fake rejects duplicate names, and the regression covers worker `prepare`.
+- **R1 P2 — resolved.** [ship_check_prepare_test.go:86](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check_prepare_test.go:86) asserts chmod 0700 before lchown 65534:65534, through both function and verb. Removing or reversing those calls breaks the assertion.
+
+Reviewed `d57b4bf04c4908f519fc17f6255e0e0dc2a3acc9`, round 2/3.
+
+**P1 — Docker volume population can undo preparation before the first app process starts.** Both the helper ([ship_check.go:220](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:220)) and app processes ([ship_check.go:286](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-check-volumes/ship_check.go:286)) mount the data volume without disabling image-content copying.
+
+Failure scenario: a valid image contains an empty `/data/instances/check` directory, mode 0755. Import normalizes its owner to 0:0. Preparation leaves the volume empty but changes its owner to 65534:65534. When Docker creates release—or web without release—it populates the still-empty volume again, restoring the image directory’s ownership and mode. UID 65534 then cannot create `CARLOS_DB`, so a healthy app fails its check.
+
+Verified by source inspection, not a runtime reproduction: Docker skips population only when the destination contains entries; its copy implementation restores directory metadata.
+
+[https://raw.githubusercontent.com/moby/moby/v27.5.1/container/container_unix.go](https://raw.githubusercontent.com/moby/moby/v27.5.1/container/container_unix.go), [https://raw.githubusercontent.com/containerd/continuity/main/fs/copy.go](https://raw.githubusercontent.com/containerd/continuity/main/fs/copy.go), [https://raw.githubusercontent.com/containerd/continuity/main/fs/copy_linux.go](https://raw.githubusercontent.com/containerd/continuity/main/fs/copy_linux.go)
+
+**Fix:** disable image-content copying on every data-volume mount, using syntax supported by each runtime. Add a regression with that empty directory present in the image, asserting UID 65534 can write after the next container starts. **Invariant/fault family:** prepared data-volume ownership must remain writable by the check user across container launches.
+
+No new P2 or P3 findings.
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–147. `file:Lstat` and `legacy / accepted-legacy` match the container-only caller. Final symlinks and non-directories are refused; chmod precedes lchown; neither recurses.
+- **APPROVE — envelope `.`.** Read `main.go:21–51`, `ship_check.go:132–243,303–369`, and `ship_check_probe.go:108–147`; traced import, probe selection and cleanup. No box-root caller gains an input path or weaker validation. The finding above concerns local-check functionality.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The added dispatch writes no record; the `instances` and `sidecars` literals remain unchanged.
+
+Targeted check and census tests stopped before compilation because `$TMPDIR` is read-only. GOCACHE remained unset. No full suites ran; no files changed.
+
+NOT READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md
new file mode 100644
index 000000000..65e77fbbb
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R3.md
@@ -0,0 +1,18 @@
+- **R1 P1 — resolved.** Helper name `<prefix>_prepare` cannot collide with worker names ([ship_check.go:215](ship_check.go:215)); the regression fake rejects duplicate names.
+- **R1 P2 — resolved.** Tests pin chmod 0700 before lchown 65534:65534, including the verb’s arguments ([ship_check_prepare_test.go:86](ship_check_prepare_test.go:86)).
+- **R2 P1 — resolved.** Every data/run volume mount uses `:nocopy`; the regression covers prepare, release, web and worker ([ship_check_test.go:695](ship_check_test.go:695)).
+
+Reviewed commit `05e4e6b23c28351d178580865545998173cec811`, round 3/3, including the R2 fix and whole branch against `1fa2a99b`.
+
+No new P1, P2 or P3 findings. Runtime syntax was cross-checked against the Moby parser and Podman documentation: [https://raw.githubusercontent.com/moby/moby/v27.5.1/volume/mounts/linux_parser.go](https://raw.githubusercontent.com/moby/moby/v27.5.1/volume/mounts/linux_parser.go), [https://docs.podman.io/en/v5.2.2/markdown/podman-run.1.html](https://docs.podman.io/en/v5.2.2/markdown/podman-run.1.html).
+
+Census verdicts:
+
+- **APPROVE — `ship_check_probe.go:prepareCheckDir`.** Read lines 108–147. `file:Lstat`, `legacy / accepted-legacy` remains appropriate for the container-only caller. Final symlinks and non-directories are refused; chmod precedes lchown; neither recurses.
+- **APPROVE — `ship_check.go:rootfsCheck.runArgs`.** Read lines 246–312. The body change adds `:nocopy` through `volumeMount`; paths, probe mount, privileges and command construction retain their checks. No file read or box-root authority is added; the existing disposition remains appropriate.
+- **APPROVE — envelope `.`.** Read `main.go:21–51`, `ship_check.go:108–382,526–544`, and `ship_check_probe.go:108–147,223–259`; traced import and normalization. The helper executes the selected probe with fixed arguments, cleanup records resources before creation, and release failure/timeout behavior is preserved. No box-root input path or weaker validation is introduced.
+- **APPROVE — record-write re-pin `main.go:main`.** Read the dispatch diff and `internal/provision/rootfs_check_volumes_census_test.go:16–37`. The new dispatch writes no record; the `instances` and `sidecars` literals are unchanged.
+
+Targeted check and census tests stopped before compilation because `$TMPDIR` is read-only. GOCACHE remained unset. Formatting and diff checks passed. No full suites ran; no files changed.
+
+READY
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md
new file mode 100644
index 000000000..f6b0b2039
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-rootfs-fleet-followups-R1.md
@@ -0,0 +1,30 @@
+No P1 findings.
+
+**P2 — Fleet HEALTH can describe an earlier instance lifetime.** At [apiinstances.go:498](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/console/apiinstances.go:498), `fleetHealth` accepts the rollout view without checking when its box report was generated. The platform-remote path explicitly rejects reports generated before `rec.CreatedAt` at [remoteinstances.go:344](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/console/remoteinstances.go:344).
+
+If an instance is deleted and recreated with the same host, account and app while its previous snapshot remains fresh, the new row inherits the old instance’s `Running`, `Asleep` or `Failed` word. It should remain unknown until a report covers the new record.
+
+**Fix:** retain the snapshot’s `GeneratedAt` in the rollout join and require it to be after `rec.CreatedAt` before deriving fleet health. Add an API witness with a report predating the record and a newer-report control.
+
+**Invariant / fault family:** health observations must belong to the current instance lifetime.
+
+No P3 findings.
+
+Census verdicts for `ff0605208c91c02b86beae5fdb12136e0d10ca88`:
+
+| Unit or envelope | Verdict and evidence |
+|---|---|
+| `ExecBackend.prepareKeyedAt` | **APPROVE**, existing legacy disposition. [prepare.go:179](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/prepare.go:179): adds process selection; launch gates and filesystem operations remain intact. |
+| `ExecBackend.prepareWorker` | **APPROVE**, existing legacy disposition. [prepare.go:209](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/prepare.go:209): validated worker name reaches the existing listener; no additional reads. |
+| `ExecBackend.logEmitter` | **APPROVE**, existing legacy disposition. [prepare.go:325](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/prepare.go:325): delegates route attribution to `appLineEmitter`. |
+| `Service.releaseAppLog` | **APPROVE**, existing legacy disposition. [rootfsrelease.go:353](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/rootfsrelease.go:353): same output destination, with the release process name. |
+| `appLineEmitter` | **APPROVE**, new `legacy / accepted-legacy` disposition. [logsink.go:47](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/activator/logsink.go:47): reads route identity and invokes an in-memory sink; grants no filesystem or execution authority. |
+| `internal/activator` envelope | **APPROVE**. Changed functions preserve existing capture destinations, validation and launch boundaries. |
+| `internal/applog` envelope | **APPROVE**. [sink.go:131](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/applog/sink.go:131): process attribution overrides parsed JSON; stream and binary-instance behavior remain intact. |
+| Record-write re-pin: `Server.handleAPIInstanceList` | **APPROVE**, unchanged `key-site / lit:instances` classification. [apiinstances.go:1230](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-fleet-followups/internal/console/apiinstances.go:1230): annotates health without changing record writes. |
+
+The five unit digests, legacy fingerprints, both envelope hashes and record-write re-pin match the source. Tenant checks remain enforced; neither change adds S3 calls per list or pass. Web generations, worker restarts and release retries reach the updated capture paths.
+
+Targeted tests and census tests could not start because the read-only sandbox prevented Go from creating its work directory. `GOCACHE` was unset. `git diff --check` passed; runtime and mutation results remain unverified.
+
+READY AFTER FIXES
\ No newline at end of file
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md
new file mode 100644
index 000000000..7a3233ada
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R2.md
@@ -0,0 +1,11 @@
+# Review brief: rootfs-check-volumes, round 2 of 3
+
+Same branch, authorities and "what to check" as docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md (read it). Review the diff 03e08f56..<this brief's parent> for the fixes, and the whole branch diff 1fa2a99b..HEAD for anything they broke.
+
+Earlier rounds: R1 (docs/superpowers/reviews/CODEX-FINDINGS-rootfs-check-volumes-R1.md): P1 helper container name collides with a worker named `prepare`; P2 tests do not pin chmod-before-chown or the 65534 owner. Fix commits 29e0c39a (helper `<prefix>_prepare`, outside ^[a-z][a-z0-9-]{0,15}$; fake rejects duplicate names; TestRootfsCheckWorkerNamedLikeTheHelper) and 500ec2ba (checkChmod/checkLchown package vars; TestPrepareCheckDirSetsModeThenOwner). Census re-proposed 2d5be53e (same unit and read; seal 4fb2a2ad; envelope . re-pinned).
+
+First give one line per R1 P1/P2: resolved, partly, or not. Then new findings. Then census verdicts again for every unit and envelope on the current card (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md) and the main.go main re-pin.
+
+Severity, output format and rules as in round 1. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md
new file mode 100644
index 000000000..02ec094ad
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes-R3.md
@@ -0,0 +1,13 @@
+# Review brief: rootfs-check-volumes, round 3 of 3 (LAST)
+
+Same branch, authorities and "what to check" as docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md. Review the fix diff from the R2 tip d57b4bf0 to <this brief's parent>, and the whole branch 1fa2a99b..HEAD for anything it broke.
+
+Earlier rounds: R1 (CODEX-FINDINGS-rootfs-check-volumes-R1.md) and R2 (CODEX-FINDINGS-rootfs-check-volumes-R2.md). R2's P1 (Docker/Podman copy-up of an empty named volume resets the prepared owner) is answered by d203093b: every data and run volume mount goes through rootfsCheck.volumeMount and ends in `:nocopy` (prepare helper, release, web, workers); TestRootfsCheckVolumesNeverCopyUp. Box witness on r10r (rootful podman): shop.tar and a variant image with an empty 0:0 755 /data/instances/check both pass; no leftovers. Docker was not available to run; the Docker side rests on Docker's documented -v nocopy option.
+
+First give one line per R1 and R2 P1/P2: resolved, partly, or not. Then new findings. Then census verdicts for every unit and envelope on the current card (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md: prepareCheckDir unchanged; rootfsCheck.runArgs body change, `:nocopy` only; envelope `.`) and the main.go main re-pin.
+
+This is round 3: a NOT READY must say whether its P1s share one cause, and whether refusing the case up front or cutting the feature would remove them.
+
+Severity, output and rules as in round 1. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md
new file mode 100644
index 000000000..70116c4c8
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-check-volumes.md
@@ -0,0 +1,33 @@
+# Review brief: rootfs-check-volumes (carlos ship --check keeps its data volume), round 1 of 3
+
+Repo carlos/platform, branch `rootfs-check-volumes`, review the diff `1fa2a99b..ece268bc7ae69b17307bbb97981189049462bee0` (this brief's commit follows it).
+Authorities on main: docs/superpowers/specs/2026-10-24-rootfs-apps-design.md (§5.8 the local check, §5.2 the launch contract), docs/superpowers/plans/2026-10-24-rootfs-apps-1-ship.md (Task 11, the check), AGENTS.md (census, copy, stopping rules).
+
+You are an independent reviewer. Read the diff, then the code it names, and check every claim against that code.
+
+## The bug
+`carlos ship --check` made the data volume a local-driver tmpfs volume. Docker and Podman unmount it when no container holds it, so what the `release` container wrote (migrations into CARLOS_DB) was gone before `web` started; examples/rails-shop failed with a 500. Box witness after the fix (r10r, podman): release 2.9 s, web 200 after 2.8 s, worker running after 5 s, passed, no leftovers.
+
+## Fixed: do not re-argue
+- Controller's design: data volume a plain local named volume; run volume stays tmpfs; a one-shot prepare container running the CLI's own linux binary (mounted at checkProbeMount) with hidden verb `__rootfs-check-prepare`, as root with only CAP_CHOWN, chmods then chowns that one directory. Report only mechanisms that fail it.
+
+## What to check
+1. The prepare container's privileges: `--user 0:0 --read-only --network none --cap-drop ALL --cap-add CHOWN --security-opt no-new-privileges`, mounts limited to the data volume and the probe. Can the image under check influence what runs as root (entrypoint, env, working dir, the volume's content, a symlink planted at the mount point, image metadata like USER/ENTRYPOINT/HEALTHCHECK, an ONBUILD)? The verb Lstats and refuses a symlink, no recursion, mode before owner (no CAP_FOWNER): correct?
+2. Docker and Podman both (rootful and rootless podman, Docker Desktop VM): does a plain local named volume persist between containers, and does chown to 65534 inside the prepare container give the check's user write access in each? macOS/Windows hosts: the probe binary is a linux build already required by the check.
+3. Cleanup on every path (success, prepare failure, Ctrl-C between steps): every container, volume and image the check made is removed; the persisted data volume does not survive the check.
+4. The refactor of start/runRelease into launch/waitExit: release behaviour unchanged (timeouts, failure lines, report wording).
+5. User-visible strings: the diff should add none needing copy review (a failed prepare reports through existing runtimeFailed wording). Flag any new human text.
+6. Census: card docs/superpowers/notes/census-proposal-rootfs-check-volumes.md (new unit ship_check_probe.go:prepareCheckDir, +file:Lstat; envelope `.` re-pinned) and internal/provision/rootfs_check_volumes_census_test.go (main.go main re-pinned). Give a verdict for every unit and envelope on the card per AGENTS.md "Getting a change approved". Note: this code runs in the user's CLI and inside a throwaway container, never as root on a box.
+7. Tests: do the new tests and mutations (listed in the commit) actually pin 1-3?
+
+## Severity
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+A P1 states its failure scenario and the evidence (file:line).
+
+## Output
+Findings ranked P1, P2, P3, each with the problem, evidence (file:line, verified), failure scenario, concrete fix and the invariant it breaks. Census verdicts per unit/envelope (APPROVE or REJECT with lines read). End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md
new file mode 100644
index 000000000..5d54cb7ae
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-REVIEW-BRIEF-rootfs-fleet-followups.md
@@ -0,0 +1,29 @@
+# Review brief: rootfs-fleet-followups (process names in carlos logs, fleet HEALTH), round 1 of 3
+
+Repo carlos/platform, branch `rootfs-fleet-followups`, review the diff `1fa2a99b..<this brief's parent>`.
+Authorities on main: docs/superpowers/specs/2026-10-24-rootfs-apps-design.md, docs/superpowers/plans/2026-10-24-rootfs-apps-4-console-and-docs.md (row RFS-4-C99: "carlos logs shows all three processes"), AGENTS.md (census, request budget, tenant isolation, production-wired witnesses, stopping rules).
+
+You are an independent reviewer. Read the diff, then the code it names, and check every claim against that code.
+
+## The changes
+1. a19a0c42: rootfs app log lines carry Fields["process"] = web | release | <worker name> (applog.Sink.AppProcess via an optional processSink interface; the platform's value wins over the app's JSON key; stream stays `app`; binary instances unchanged).
+2. 7545ef9a: `carlos instances list` HEALTH for fleet-placed records comes from the fleet box's rollout view via join.rollout(host, acct, app) (fleetHealth after instanceHealth in handleAPIInstanceList); Unavailable/Transient views stay unknown; "failed" on AttemptDown. The console's Running tab is deliberately NOT changed (its remote facts come only from cached platform box reports; fleet reports are an uncached per-request read).
+3. b0d928c0: census proposal (card docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md; record-write re-pin internal/provision/rootfs_fleet_followups_census_test.go).
+
+## What to check
+1. Tenant isolation for item 2: can a caller see HEALTH derived from another account's or app's fleet report, or from a box of a fleet its account does not own? (Task 9 / #155 tenant join rules; TestInstanceListWorkersStayInTheirTenant.)
+2. Item 2's health words: do they mirror the platform-remote branch exactly (always-on vs hibernating, crashed web, held build still serving)? Any row that now shows a misleading word?
+3. Item 1: can an app spoof another process's name, or inject a field that changes how the console or CLI filters or renders? Is every rootfs capture site covered (web generations including overlap swaps, workers including restarts, release including retries), and nothing else changed for binary instances?
+4. Request budget: do either change add S3 requests per list or per pass?
+5. Census: a verdict for every unit and envelope on the card and the re-pin, per AGENTS.md "Getting a change approved".
+6. Tests: production-wired, and do the stated mutations pin the behaviour?
+
+## Severity
+- **P1**: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review.
+- **P3**: clarity or polish. Follow-up list only.
+
+## Output
+Findings ranked P1, P2, P3 with evidence (file:line), failure scenario, fix, invariant. Census verdicts. End with exactly one verdict: READY, READY AFTER FIXES, or NOT READY.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of your own. Do not run the full test suites.
diff --git a/internal/activator/logsink.go b/internal/activator/logsink.go
index 431364dca..75944a932 100644
--- a/internal/activator/logsink.go
+++ b/internal/activator/logsink.go
@@ -12,6 +12,7 @@ import (
"regexp"
"strings"
+ "github.com/carlosframework/platform/internal/applog"
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -29,6 +30,31 @@ type EventSink interface {
Event(acct, app, host, level, msg string)
}
+// processSink is an EventSink that can name the process an app line came
+// from (applog.Sink.AppProcess). It is asked for by assertion, not added to
+// EventSink, so the package's EventSink fakes stay as they are; the
+// assertion below keeps the real sink holding it.
+type processSink interface {
+ AppProcess(acct, app, host, process, line string)
+}
+
+var _ processSink = (*applog.Sink)(nil)
+
+// appLineEmitter is the emit function for rt's app output, or nil when
+// sink is nil. A non-empty process (a rootfs instance's web, release or
+// worker name) is passed to a sink that can name it; otherwise the line
+// goes through App as before.
+func appLineEmitter(sink EventSink, rt registry.Route, process string) func(string) {
+ if sink == nil {
+ return nil
+ }
+ acct, app, host := release.RouteAccount(rt), rt.App, rt.Host
+ if ps, ok := sink.(processSink); ok && process != "" {
+ return func(line string) { ps.AppProcess(acct, app, host, process, line) }
+ }
+ return func(line string) { sink.App(acct, app, host, line) }
+}
+
// emitEvent publishes one platform event for rt's app, tolerating a nil
// sink. level is an applog.Level* value ("info"/"warn"/"error" — string
// here to keep the dependency one-way).
diff --git a/internal/activator/prepare.go b/internal/activator/prepare.go
index e921303f8..47c54aef9 100644
--- a/internal/activator/prepare.go
+++ b/internal/activator/prepare.go
@@ -179,7 +179,13 @@ func (b *ExecBackend) prepareKeyedAt(rt registry.Route, role instancectl.Role, s
var logs *logListener
if role != instancectl.RoleCmd {
var err error
- logs, err = listenLogs(b.logSocketFor(rt.Host, role, gen), b.logEmitter(rt))
+ // A rootfs row's run role is its web process; a binary row's
+ // lines name no process.
+ process := ""
+ if rt.Rootfs() && role == instancectl.RoleRun {
+ process = release.ProcessWeb
+ }
+ logs, err = listenLogs(b.logSocketFor(rt.Host, role, gen), b.logEmitter(rt, process))
if err != nil {
if ctl != nil {
ctl.Close()
@@ -222,7 +228,7 @@ func (b *ExecBackend) prepareWorker(rt registry.Route, name string) (instancePat
}
}
}
- logs, err := listenLogs(sock, b.logEmitter(rt))
+ logs, err := listenLogs(sock, b.logEmitter(rt, name))
if err != nil {
return p, nil, fmt.Errorf("log listener for %s worker %s: %w", rt.Host, name, err)
}
@@ -314,11 +320,10 @@ func (b *ExecBackend) logSocketNamed(host, name string) string {
}
// logEmitter is the same sink teeStd feeds, or nil when Logs is unset.
-func (b *ExecBackend) logEmitter(rt registry.Route) func(string) {
- if b.Logs == nil {
- return nil
- }
- return func(line string) { b.Logs.App(release.RouteAccount(rt), rt.App, rt.Host, line) }
+// process names the process the lines come from ("" for none):
+// appLineEmitter.
+func (b *ExecBackend) logEmitter(rt registry.Route, process string) func(string) {
+ return appLineEmitter(b.Logs, rt, process)
}
// writeLaunch is writeLaunchFor for the original templates.
diff --git a/internal/activator/rootfs_process_logs_test.go b/internal/activator/rootfs_process_logs_test.go
new file mode 100644
index 000000000..46695953a
--- /dev/null
+++ b/internal/activator/rootfs_process_logs_test.go
@@ -0,0 +1,112 @@
+package activator
+
+import (
+ "context"
+ "net"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// A rootfs instance's output reaches `carlos logs` naming the process that
+// wrote it (#366 Task 11 follow-up): web through the generation's log
+// listener, a worker through its own, the release through releaseAppLog.
+// Each line goes in at the socket or writer production hands the unit, and
+// comes out of a real applog.Sink, so the wiring at each capture site is
+// what is checked. A process key in the app's own JSON loses to the
+// platform's.
+func TestRootfsAppLinesNameTheirProcess(t *testing.T) {
+ t.Parallel()
+ b, ctl, rt, units := newWorkerBackend(t)
+ sink := applog.NewSink("box1", time.Now)
+ b.Logs = sink
+ web, g := startWorkerWeb(t, b, ctl, rt, units, "")
+ units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "inv1", true)
+ wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", g, web)
+ if err != nil {
+ t.Fatalf("LaunchRootfsWorker: %v", err)
+ }
+ t.Cleanup(func() { stopWorker(t, wp) })
+
+ writeUnitLine(t, b.logSocketFor(rt.Host, instancectl.RoleRun, g.N), `{"msg":"web line","process":"spoof"}`)
+ writeUnitLine(t, b.workerLogSocket(rt.Host, "jobs"), "worker line")
+ a := &Service{Logs: sink}
+ if _, err := a.releaseAppLog(rt).Write([]byte("release line")); err != nil {
+ t.Fatal(err)
+ }
+
+ got := map[string]string{}
+ for _, r := range drainAppLines(t, sink, 3) {
+ got[r.Msg] = r.Fields["process"]
+ if r.Stream != applog.StreamApp {
+ t.Errorf("%q is on stream %q, want app", r.Msg, r.Stream)
+ }
+ }
+ want := map[string]string{"web line": release.ProcessWeb, "worker line": "jobs", "release line": release.ProcessRelease}
+ for msg, p := range want {
+ if got[msg] != p {
+ t.Errorf("%q has process %q, want %q (all: %v)", msg, got[msg], p, got)
+ }
+ }
+}
+
+// A binary instance's nested run role is unchanged: its lines carry no
+// process field.
+func TestBinaryAppLinesNameNoProcess(t *testing.T) {
+ t.Parallel()
+ b, _ := newRootfsBackend(t)
+ rt := rootfsRoute(b)
+ rt.Runtime = ""
+ sink := applog.NewSink("box1", time.Now)
+ b.Logs = sink
+ _, ctl, logs, _, _, err := b.prepareKeyedAt(rt, instancectl.RoleRun, rt.Socket, 0, nil)
+ if err != nil {
+ t.Fatalf("prepareKeyedAt: %v", err)
+ }
+ if ctl != nil {
+ t.Cleanup(func() { ctl.Close() })
+ }
+ t.Cleanup(func() { logs.Close() })
+ writeUnitLine(t, b.logSocketFor(rt.Host, instancectl.RoleRun, 0), "binary line")
+ for _, r := range drainAppLines(t, sink, 1) {
+ if p, ok := r.Fields["process"]; ok {
+ t.Errorf("%q carries process %q, want none", r.Msg, p)
+ }
+ }
+}
+
+// writeUnitLine is a unit's stdout: one connection to its log socket, one
+// line, closed.
+func writeUnitLine(t *testing.T, sock, line string) {
+ t.Helper()
+ c, err := net.Dial("unix", sock)
+ if err != nil {
+ t.Fatalf("dial %s: %v", sock, err)
+ }
+ defer c.Close()
+ if _, err := c.Write([]byte(line + "\n")); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// drainAppLines drains sink until n app-stream records have arrived.
+func drainAppLines(t *testing.T, sink *applog.Sink, n int) []applog.Record {
+ t.Helper()
+ var out []applog.Record
+ for deadline := time.Now().Add(5 * time.Second); len(out) < n && time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
+ for _, recs := range sink.Drain() {
+ for _, r := range recs {
+ if r.Stream == applog.StreamApp {
+ out = append(out, r)
+ }
+ }
+ }
+ }
+ if len(out) != n {
+ t.Fatalf("%d app lines arrived, want %d: %+v", len(out), n, out)
+ }
+ return out
+}
diff --git a/internal/activator/rootfsrelease.go b/internal/activator/rootfsrelease.go
index ee6376dbe..6244ca4d5 100644
--- a/internal/activator/rootfsrelease.go
+++ b/internal/activator/rootfsrelease.go
@@ -348,14 +348,10 @@ func releaseLeaseGone(held leaseWatch) bool {
}
// releaseAppLog is the writer a release's output goes through to the app
-// log, a line a Write (StartRelease's line writer feeds it whole lines);
-// nil Logs discards.
+// log, a line a Write (StartRelease's line writer feeds it whole lines),
+// each naming the release process; nil Logs discards.
func (a *Service) releaseAppLog(rt registry.Route) io.Writer {
- if a.Logs == nil {
- return lineEmitter(nil)
- }
- sink := a.Logs
- return lineEmitter(func(line string) { sink.App(release.RouteAccount(rt), rt.App, rt.Host, line) })
+ return lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease))
}
// runRelease runs id's release process for rt, if one is due, under held
diff --git a/internal/applog/record.go b/internal/applog/record.go
index 92ae49d69..ea153fdd6 100644
--- a/internal/applog/record.go
+++ b/internal/applog/record.go
@@ -23,6 +23,11 @@ const (
StreamRelease = "release" // ship/promote history join (stage 3)
)
+// FieldProcess is the field an app line carries naming the process that
+// wrote it, when the platform knows (Sink.AppProcess): a rootfs instance's
+// web, release or worker. `carlos logs --field process=web` filters on it.
+const FieldProcess = "process"
+
// ValidStream reports whether s names a known stream — the CLI/API's
// vocabulary check, kept here so there is exactly one list.
func ValidStream(s string) bool {
diff --git a/internal/applog/sink.go b/internal/applog/sink.go
index 19a3db172..e40b8eed7 100644
--- a/internal/applog/sink.go
+++ b/internal/applog/sink.go
@@ -129,7 +129,22 @@ func (s *Sink) Known() []AppKey {
// JSON lines at the door (ParseAppLine) so the bucket holds fields and
// honored levels rather than opaque text. Subject to both budgets.
func (s *Sink) App(acct, app, host, line string) {
+ s.AppProcess(acct, app, host, "", line)
+}
+
+// AppProcess is App for a line the platform knows the process of (a rootfs
+// instance's web, release or a named worker): a non-empty process is set
+// as Fields["process"] after parsing, over any "process" key in the app's
+// own JSON, so the name a member filters on is always the platform's. The
+// stream stays StreamApp; StreamRelease is the ship/promote history.
+func (s *Sink) AppProcess(acct, app, host, process, line string) {
msg, level, fields := ParseAppLine(line)
+ if process != "" {
+ if fields == nil {
+ fields = make(map[string]string, 1)
+ }
+ fields[FieldProcess] = process
+ }
s.mu.Lock()
defer s.mu.Unlock()
b := s.buf(AppKey{acct, app})
diff --git a/internal/applog/sink_test.go b/internal/applog/sink_test.go
index fcdaa2ac0..17068a9fd 100644
--- a/internal/applog/sink_test.go
+++ b/internal/applog/sink_test.go
@@ -162,3 +162,29 @@ func TestIsDropNotice(t *testing.T) {
}
}
}
+
+// AppProcess is App with the platform naming the process that wrote the
+// line (a rootfs instance's web, release or a worker): the name rides in
+// Fields["process"], on a plain line and on a structured one alike, and
+// the platform's value wins over a "process" key in the app's own JSON.
+// The stream stays app: "release" is the ship/promote history's stream.
+func TestSinkAppProcessNamesTheProcess(t *testing.T) {
+ now, _ := testClock(time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC))
+ sk := NewSink("box1", now)
+ sk.AppProcess("bab", "shop", "shop.bab.oncarlos.com", "web", "listening")
+ sk.AppProcess("bab", "shop", "shop.bab.oncarlos.com", "jobs", `{"msg":"tick","process":"web","n":3}`)
+ sk.AppProcess("bab", "shop", "shop.bab.oncarlos.com", "release", "migrated")
+ sk.App("bab", "shop", "shop.bab.oncarlos.com", `{"msg":"own","process":"mine"}`)
+ recs := sk.Drain()[AppKey{"bab", "shop"}]
+ if len(recs) != 4 {
+ t.Fatalf("records: %d, want 4", len(recs))
+ }
+ for i, want := range []struct{ msg, process, n string }{
+ {"listening", "web", ""}, {"tick", "jobs", "3"}, {"migrated", "release", ""}, {"own", "mine", ""},
+ } {
+ r := recs[i]
+ if r.Stream != StreamApp || r.Msg != want.msg || r.Fields["process"] != want.process || r.Fields["n"] != want.n {
+ t.Errorf("record %d = %+v, want app stream, msg %q, process %q, n %q", i, r, want.msg, want.process, want.n)
+ }
+ }
+}
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index e4f71c70e..4a46e84de 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -476,6 +476,44 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma
return out
}
+// fleetHealth fills in, from join, the health of each record placed on a
+// customer fleet that instanceHealth left unknown: the platform's boxes do
+// not report fleet-placed hosts, but the fleet's own boxes' rollout reports
+// do, and join (loadRolloutJoin) reads them for the caller's own fleets
+// only. join.rollout keeps its tenant rule: a report is used only when it
+// names this account and app. A view whose box could not arm its scheduler
+// (Unavailable, which also covers a refused view with no tenant to check)
+// or whose host is starting or stopping (Transient) says nothing about the
+// host's state, and the word stays unknown, as it does for a view whose
+// box generated its snapshot no later than the record was created: that
+// report may be about an earlier lifetime of the same host, account and
+// app (appFacts.host's rule for a platform-remote record). Otherwise the
+// word is the platform-remote one (instanceHealth): awake is Running, a
+// host held down after a failed hold-mode build is Failed.
+func fleetHealth(health map[string]string, recs []provision.Record, join boxJoin, acct, app string) {
+ for _, rec := range recs {
+ if health[rec.Host] != healthUnknown {
+ continue
+ }
+ if _, fleetPlaced := registry.FleetPlacement(rec.Region); !fleetPlaced {
+ continue
+ }
+ v := join.rollout(rec.Host, acct, app)
+ if v == nil || v.Unavailable != "" || v.Transient || !v.at.After(rec.CreatedAt) {
+ continue
+ }
+ kind := rec.Kind
+ if kind == "" {
+ kind = "instance"
+ }
+ st := "ready"
+ if v.Attempt == status.AttemptDown {
+ st = "failed"
+ }
+ health[rec.Host] = healthWord(kind, st, rec.HibernateOrDefault(), v.Awake, true)
+ }
+}
+
// healthByHost is the metrics half of a health answer, shared by
// instanceHealth (records joined to routes) and handleAPIRoutes (routes
// directly, issue #64) so the two — and the Running tab, which uses the
@@ -716,6 +754,11 @@ type rolloutView struct {
// refused marks a view built from an Unavailable box, which has no
// account or app to check (hosts are unique; the caller filtered by app).
refused bool
+ // at is when the reporting box generated its snapshot (status.Box's
+ // GeneratedAt). Not shown: fleetHealth uses a view only when it is
+ // later than the record's creation, so a report about an earlier
+ // lifetime of the same host never describes this one.
+ at time.Time
}
// workerView is one worker of a rootfs instance as a member sees it
@@ -1044,12 +1087,12 @@ func (j *boxJoin) foldRollout(b status.Box, override bool) {
if _, held := ro.Hosts[host]; held {
continue
}
- put(host, rolloutView{Box: b.Label, Installed: v, Unavailable: ro.Unavailable, refused: true})
+ put(host, rolloutView{Box: b.Label, Installed: v, Unavailable: ro.Unavailable, refused: true, at: b.GeneratedAt})
}
for host, hr := range ro.Hosts {
put(host, rolloutView{Box: b.Label, Installed: hr.Installed, Good: hr.Good, Attempt: hr.Attempt, AttemptBuild: hr.AttemptBuild,
HeldBy: hr.HeldBy, Reason: hr.Reason, Unavailable: ro.Unavailable, Workers: workerViews(hr.Workers),
- account: hr.Account, app: hr.App, heldEpoch: hr.HeldEpoch, heldBook: hr.HeldBook, retryV: hr.RetryV})
+ account: hr.Account, app: hr.App, heldEpoch: hr.HeldEpoch, heldBook: hr.HeldBook, retryV: hr.RetryV, at: b.GeneratedAt})
}
return
}
@@ -1072,6 +1115,7 @@ func (j *boxJoin) foldRollout(b status.Box, override bool) {
ConfigPending: hr.ConfigPending, Transient: hr.Transient, SchedulerIdle: a.Queued == 0 && a.Running == 0 && a.Settling == 0,
Workers: workerViews(hr.Workers),
account: hr.Account, app: hr.App, heldEpoch: hr.HeldEpoch, heldBook: hr.HeldBook, retryV: hr.RetryV,
+ at: b.GeneratedAt,
})
}
}
@@ -1193,6 +1237,7 @@ func (s *Server) handleAPIInstanceList(w http.ResponseWriter, r *http.Request) {
}
}
health := s.instanceHealth(ctx, recs)
+ fleetHealth(health, recs, join, acct.Sqid, app)
counts := map[string]int{}
matched := make([]instanceListRecord, 0, len(recs))
home, names := s.regionHome(), s.regionNames()
diff --git a/internal/console/fleethealth_test.go b/internal/console/fleethealth_test.go
new file mode 100644
index 000000000..83c9a5405
--- /dev/null
+++ b/internal/console/fleethealth_test.go
@@ -0,0 +1,124 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// writeFleetRolloutBox registers fleet to owner and writes, under the
+// fleet's own prefix, a box named machine reporting ro (and versions as its
+// route versions, which an Unavailable report's hosts come from), generated
+// at at.
+func writeFleetRolloutBox(t *testing.T, fx *consoleFixture, fleet, owner, machine string, at time.Time, ro *status.RolloutReport, versions map[string]string) {
+ t.Helper()
+ reg, err := registry.Open(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reg.Close()
+ if err := reg.UpsertFleet(registry.Fleet{Name: fleet, Account: owner, Bucket: fleet + "-bucket"}); err != nil {
+ t.Fatal(err)
+ }
+ box := status.CollectBox(nil, status.Probes{MachineID: machine}, at)
+ box.Metrics = &status.BoxMetrics{Rollout: ro, RouteVersions: versions}
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/"+fleet+"/"), box); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// listHealth is the instance list's health word per host.
+func listHealth(t *testing.T, fx *consoleFixture, token, app string) map[string]string {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodGet, fx.ts.URL+"/api/cli/apps/"+fx.sqid+"/"+app+"/instances", token, "")
+ if code != http.StatusOK {
+ t.Fatalf("list = %d %s", code, out)
+ }
+ var list struct {
+ Instances []struct {
+ Host string `json:"host"`
+ Health string `json:"health"`
+ } `json:"instances"`
+ }
+ if err := json.Unmarshal([]byte(out), &list); err != nil {
+ t.Fatal(err)
+ }
+ got := map[string]string{}
+ for _, r := range list.Instances {
+ got[r.Host] = r.Health
+ }
+ return got
+}
+
+// #366 Task 11 follow-up: a record placed on the caller's own fleet takes
+// its health word from that fleet box's rollout report (the join the
+// list's rollout column reads), as a platform-remote record takes its word
+// from its box: awake is Running, a hibernating instance not awake is
+// Asleep, a host held down is Failed. Everything the join cannot vouch for
+// stays "Can't tell right now": a host starting or stopping, a report
+// naming another app, a box that could not arm its scheduler, a host no
+// box reports, another account's fleet box naming this app's host, and a
+// report generated before the record was created (an earlier lifetime of
+// the same host, account and app; the platform-remote rule, appFacts.host).
+// Every other report here is generated after the records, the control.
+func TestFleetPlacedHealthComesFromItsFleetBox(t *testing.T) {
+ fx := newConsoleFixture(t)
+ const app = "kass"
+ host := func(slug string) string { return slug + ".kass.carlosapp.dev" }
+ asleep := true
+ now := time.Now().UTC()
+ created := now.Add(-10 * time.Second)
+ for _, slug := range []string{"run", "nap", "down", "busy", "other", "gone", "stranger", "unavail", "reborn"} {
+ place := registry.PlacementTarget("pi")
+ if slug == "stranger" {
+ place = registry.PlacementTarget("stranger")
+ }
+ if err := provision.CreateRecord(context.Background(), fx.rel, provision.Record{
+ Schema: 1, Host: host(slug), Slug: slug, App: app, Account: fx.sqid, Region: place,
+ Channel: "stable", Hibernate: &asleep, CreatedAt: created, CreatedBy: "paul@keymail.dev",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ mine := func(hr status.HostRollout) status.HostRollout {
+ hr.Account, hr.App, hr.Installed = fx.sqid, app, "v1"
+ return hr
+ }
+ writeFleetRolloutBox(t, fx, "pi", fx.sqid, "pi-box", now, &status.RolloutReport{Hosts: map[string]status.HostRollout{
+ host("run"): mine(status.HostRollout{Awake: true}),
+ host("nap"): mine(status.HostRollout{}),
+ host("down"): mine(status.HostRollout{Attempt: status.AttemptDown, AttemptBuild: "v1"}),
+ host("busy"): mine(status.HostRollout{Transient: true}),
+ host("other"): {Account: fx.sqid, App: "other", Installed: "v1", Awake: true},
+ }}, nil)
+ writeFleetRolloutBox(t, fx, "pi", fx.sqid, "pi-box-2", now, &status.RolloutReport{Unavailable: "flag-off"},
+ map[string]string{host("unavail"): "v1"})
+ writeFleetRolloutBox(t, fx, "stranger", "zzz", "stranger-box", now, &status.RolloutReport{Hosts: map[string]status.HostRollout{
+ host("stranger"): mine(status.HostRollout{Awake: true}),
+ }}, nil)
+ // Fresh (well inside the staleness window) but from before the record.
+ writeFleetRolloutBox(t, fx, "pi", fx.sqid, "pi-box-old", created.Add(-10*time.Second), &status.RolloutReport{Hosts: map[string]status.HostRollout{
+ host("reborn"): mine(status.HostRollout{Awake: true}),
+ }}, nil)
+ token := cliToken(t, fx, "paul@keymail.dev", "code-fleet-health")
+
+ got := listHealth(t, fx, token, app)
+ want := map[string]string{
+ host("run"): "Running", host("nap"): "Asleep", host("down"): "Failed",
+ host("busy"): healthUnknown, host("other"): healthUnknown, host("gone"): healthUnknown,
+ host("stranger"): healthUnknown, host("unavail"): healthUnknown, host("reborn"): healthUnknown,
+ }
+ for h, w := range want {
+ if got[h] != w {
+ t.Errorf("%s health = %q, want %q", strings.SplitN(h, ".", 2)[0], got[h], w)
+ }
+ }
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 4527593f2..0098f6133 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 := fleetSecretsKeyWriteCensusInventory()
+ inventory := rootfsFleetFollowupsWriteCensusInventory()
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/rootfs_check_volumes_census_test.go b/internal/provision/rootfs_check_volumes_census_test.go
new file mode 100644
index 000000000..79496b2cb
--- /dev/null
+++ b/internal/provision/rootfs_check_volumes_census_test.go
@@ -0,0 +1,37 @@
+package provision
+
+// Record-write census entries for the ship --check data volume fix (#366,
+// branch rootfs-check-volumes), layered on fleetSecretsKeyWriteCensusInventory
+// (main's newest at the branch's base 1fa2a99b). Reviewed by the branch
+// author against the source; the census approval is recorded on #280 with
+// the root-read card
+// (docs/superpowers/notes/census-proposal-rootfs-check-volumes.md).
+//
+// One re-pin, no new unit:
+// - main.go main (key-site): dispatches __rootfs-check-prepare, the
+// carlos ship --check verb that makes the check's data volume its user's
+// inside a container on the person's machine, beside
+// __rootfs-check-probe and before the command switch; its instances and
+// sidecars literals are unchanged. It writes no record.
+func rootfsCheckVolumesWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), fleetSecretsKeyWriteCensusInventory()...)
+ repins := []censusEntry{
+ // rootfs-check-volumes: the __rootfs-check-prepare dispatch beside __rootfs-check-probe; the same literals.
+ {"main.go", "main", "key-site", "lit:instances,lit:sidecars", "9ce797683088785d55882487096e45cdbbd664fc692ccfe67c4eaea76c1be863"},
+ }
+ 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("rootfs-check-volumes re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("rootfs-check-volumes re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/rootfs_fleet_followups_census_test.go b/internal/provision/rootfs_fleet_followups_census_test.go
new file mode 100644
index 000000000..b8c263799
--- /dev/null
+++ b/internal/provision/rootfs_fleet_followups_census_test.go
@@ -0,0 +1,38 @@
+package provision
+
+// Record-write census entries for the rootfs fleet follow-ups (#366,
+// branch rootfs-fleet-followups), layered on
+// rootfsCheckVolumesWriteCensusInventory (main's newest at 43c8677a, merged
+// into the branch; it layers on fleetSecretsKeyWriteCensusInventory, the
+// newest at the branch's base 1fa2a99b). Reviewed by the branch author against the source; the census
+// approval is recorded on #280 with the root-read card
+// (docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md).
+//
+// One re-pin, no new unit:
+// - internal/console/apiinstances.go Server.handleAPIInstanceList
+// (key-site): after instanceHealth, fleetHealth fills the health word of
+// a fleet-placed record still unknown from the rollout join the handler
+// already loads (join.rollout, its tenant rule kept). The record listing
+// and its literal are unchanged; it writes no record.
+func rootfsFleetFollowupsWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), rootfsCheckVolumesWriteCensusInventory()...)
+ repins := []censusEntry{
+ // rootfs-fleet-followups: fleetHealth after instanceHealth; the same listing and literal.
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceList", "key-site", "lit:instances", "fc3da89d5a32eeed50e4a5c4811d2f90e0a2bce9a49bd2d71694844d5b1009d3"},
+ }
+ 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("rootfs-fleet-followups re-pin changes the class or kinds of " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("rootfs-fleet-followups re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 8d944141b..172d774b2 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -34,3 +34,5 @@ plan14-root-reads-static-dir-slash.tsv fb7cd756f7c3eb2dc019c8fd55fea5475e2df7ee3
plan14-root-reads-named-unit-delivery-114.tsv d92c9d40eb2a9e66c859e2fe6df3af10a1b9d3a83b1d717ec928cb432eebb1aa
plan14-root-reads-fleet-secrets-key.tsv 9df7f5aca9a502966c9643b7062829c1c25bfbd86fa20e92d764d66f676d2cd6
plan14-root-reads-static-headers.tsv 94b8ccf921f64be24a4773f72d55a8e24ceba3acfb40eefe3b56af6f5b008138
+plan14-root-reads-rootfs-check-volumes.tsv 042684bf5af6f61ce8b87f10b68a42b08d131ba4cb5bcab16320c7b032a724e6
+plan14-root-reads-rootfs-fleet-followups.tsv 78b7e7e30ad3ada44388a4ee16f3950ef888ae03e552477dcbfbb07c51ffb83e
diff --git a/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv b/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv
new file mode 100644
index 000000000..714a190c3
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-rootfs-check-volumes.tsv
@@ -0,0 +1,8 @@
+# Census overlay rootfs-check-volumes, written by census-propose (#369). census-ruling-rootfs-check-volumes, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rootfs-check-volumes.md.
+# 1 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 055963a9e0d8e690476664799c9ab21df3fcd3ab42960247a6abe38fbf2baa17 ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. file:Command@764,file:Command@848 a7bd986343e647262402a363cfb374c34bdd3ecf35cbb452d9e8816d88d4a02c
+@legacy b88e56ecd81527322832b883453084fda8bde581689e0e13fbe3a79170889c2e ship_check_probe.go prepareCheckDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-check-volumes;basis=new: __rootfs-check-prepare (carlos ship --check), run only inside the check's prepare container on the person's machine (as 0:0 with CAP_CHOWN alone, no network, read-only root), never by a box: Lstats the one directory it is given (the check's data volume at /data/instances/check), refuses a symlink or non-directory, then chmod 0700 and lchown to --uid:--uid; no recursion. Read added: file:Lstat of that path. R1 P2: the chmod and lchown go through package vars checkChmod/checkLchown (os.Chmod, os.Lchown; only tests change them) so a test pins the order; same calls, same arguments. main.go dispatches the verb before the command switch beside __rootfs-check-probe; no root unit calls it. file:Lstat@67 8633a0299cf2abee0b320ba4701137f31ada646c0d6c8310b6052054d5dad87f
+ship_check.go rootfsCheck.runArgs legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-1;basis=root-input (J4, as main's db.go units); the carlos CLI on a person's machine, as the person (no box unit): new (rootfs Plan 1), builds the docker or podman run argv for one check container; the scanner matches the word Command, here a field of release.Process (a process's argv), not os/exec; reads no file; decides nothing for root;rev3=census-ruling-rootfs-check-volumes;basis=R2 P1: the data and run volume mounts (-v) now carry :nocopy through rootfsCheck.volumeMount, so Docker and Podman never fill an empty check volume from the image directory at the mount point (which would reset the prepared owner and mode); same volumes, same paths, same probe mount, nothing else in the argv changed. Runs on the person's machine as the person; no box unit; no read added. file:Command@764,file:Command@848 a7bd986343e647262402a363cfb374c34bdd3ecf35cbb452d9e8816d88d4a02c
+ship_check_probe.go prepareCheckDir legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-check-volumes;basis=new: __rootfs-check-prepare (carlos ship --check), run only inside the check's prepare container on the person's machine (as 0:0 with CAP_CHOWN alone, no network, read-only root), never by a box: Lstats the one directory it is given (the check's data volume at /data/instances/check), refuses a symlink or non-directory, then chmod 0700 and lchown to --uid:--uid; no recursion. Read added: file:Lstat of that path. R1 P2: the chmod and lchown go through package vars checkChmod/checkLchown (os.Chmod, os.Lchown; only tests change them) so a test pins the order; same calls, same arguments. main.go dispatches the verb before the command switch beside __rootfs-check-probe; no root unit calls it. file:Lstat@67 8633a0299cf2abee0b320ba4701137f31ada646c0d6c8310b6052054d5dad87f
+@coverage . b86ad1c792b5fb3a92985bad439972463cdec87b3f066fe5e37f0beb32954d7d
diff --git a/internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv b/internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv
new file mode 100644
index 000000000..7fbb80339
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-rootfs-fleet-followups.tsv
@@ -0,0 +1,15 @@
+# Census overlay rootfs-fleet-followups, written by census-propose (#369). census-ruling-rootfs-fleet-followups, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rootfs-fleet-followups.md.
+# 2 body, 2 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy d82ca4f88546b2b29b8e9619c60118f3b3f1c492c071d39f7ae63f334d9ed6cb internal/activator/prepare.go ExecBackend.prepareKeyedAt 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 zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged;rev3=census-ruling-rootfs-fleet-followups;basis=names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved file:ReadDir@2929,registry:Host@1770,registry:Host@1982,registry:Host@5787,registry:Host@5985,registry:Host@612,whole:Route@1661,whole:Route@1872,whole:Route@2103,whole:Route@320,whole:Route@4642,whole:Route@5170,whole:Route@5821 0c049e8ff1256f466b0f6e770d65c9e0ba6943f03c377924481e0210c723da30
+@legacy 2467c84503328707bba08f52e54cc3498f611783447a44511b49a4df0b1ea58d internal/activator/prepare.go ExecBackend.prepareWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: prepare for a worker: the instance's two directories and the worker log socket's, the worker's stale exit records cleared by its name prefix (another worker's and every generation's kept), its log listener bound where root's worker drop-in points StandardOutput=; reads no environment file; binds no control listener; asks no replica gate;rev3=census-ruling-rootfs-fleet-followups;basis=passes the worker name (already checked by release.ValidWorkerName at the top) to logEmitter as the process; no read added or moved file:ReadDir@563,registry:Host@224,registry:Host@440,registry:Host@902,whole:Route@124,whole:Route@809 a22180a3d5c23b92e9c227a45e90e482fc5789baec5345f1151e37773b5941f8
+@legacy 5e26653fcccbee1e5f20286530b4789cd53e32d7984fabcbff14824667457077 internal/activator/logsink.go appLineEmitter legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-fleet-followups;basis=new: the app-line emit function for rt: nil for a nil sink; reads the route account (release.RouteAccount), app and host; a sink holding AppProcess (applog.Sink) gets the process name, otherwise App as before; in-memory log sink only, no file, path or env read registry:App@166,registry:Host@174,whole:Route@161 d3af8b263f021bcba5926116366bf4a4e853a21ef7c14bcaced53dbd75247324
+@legacy d765f7a7dd9ac5f10ac545c84454e8ae9046dc36142c9a3b88e6634613b5fa6b internal/activator/prepare.go ExecBackend.logEmitter legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-fleet-followups;basis=takes a process name and returns appLineEmitter(b.Logs, rt, process); the route account, app and host reads moved into appLineEmitter; no file read whole:Route@114 171f5bc4eca79f08dc335fccac8cd11385b72ce27bded922a71e639b8a8a6ce0
+@legacy 4ed1b4930a5a677b33ea8194fba90f4b9e9c56702129a055be0fb584e008e16d internal/activator/rootfsrelease.go Service.releaseAppLog legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.5]: new; the writer a release's output goes through: each line to the instance's own app log (a.Logs.App(account, app, host, line)); reads the route's account, app and host for the log's key; no file read;rev3=census-ruling-rootfs-fleet-followups;basis=returns lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease)); the route reads moved into appLineEmitter; no file read whole:Route@106 20871e7bd6d22cf8a1bf733fe8b8f34e9702b2b2f6d661d1ef8140963518ed70
+internal/activator/prepare.go ExecBackend.prepareKeyedAt 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 zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged;rev3=census-ruling-rootfs-fleet-followups;basis=names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved file:ReadDir@2929,registry:Host@1770,registry:Host@1982,registry:Host@5787,registry:Host@5985,registry:Host@612,whole:Route@1661,whole:Route@1872,whole:Route@2103,whole:Route@320,whole:Route@4642,whole:Route@5170,whole:Route@5821 0c049e8ff1256f466b0f6e770d65c9e0ba6943f03c377924481e0210c723da30
+internal/activator/prepare.go ExecBackend.prepareWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: prepare for a worker: the instance's two directories and the worker log socket's, the worker's stale exit records cleared by its name prefix (another worker's and every generation's kept), its log listener bound where root's worker drop-in points StandardOutput=; reads no environment file; binds no control listener; asks no replica gate;rev3=census-ruling-rootfs-fleet-followups;basis=passes the worker name (already checked by release.ValidWorkerName at the top) to logEmitter as the process; no read added or moved file:ReadDir@563,registry:Host@224,registry:Host@440,registry:Host@902,whole:Route@124,whole:Route@809 a22180a3d5c23b92e9c227a45e90e482fc5789baec5345f1151e37773b5941f8
+internal/activator/logsink.go appLineEmitter legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-fleet-followups;basis=new: the app-line emit function for rt: nil for a nil sink; reads the route account (release.RouteAccount), app and host; a sink holding AppProcess (applog.Sink) gets the process name, otherwise App as before; in-memory log sink only, no file, path or env read registry:App@166,registry:Host@174,whole:Route@161 d3af8b263f021bcba5926116366bf4a4e853a21ef7c14bcaced53dbd75247324
+internal/activator/prepare.go ExecBackend.logEmitter legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-fleet-followups;basis=takes a process name and returns appLineEmitter(b.Logs, rt, process); the route account, app and host reads moved into appLineEmitter; no file read whole:Route@114 171f5bc4eca79f08dc335fccac8cd11385b72ce27bded922a71e639b8a8a6ce0
+internal/activator/rootfsrelease.go Service.releaseAppLog legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.5]: new; the writer a release's output goes through: each line to the instance's own app log (a.Logs.App(account, app, host, line)); reads the route's account, app and host for the log's key; no file read;rev3=census-ruling-rootfs-fleet-followups;basis=returns lineEmitter(appLineEmitter(a.Logs, rt, release.ProcessRelease)); the route reads moved into appLineEmitter; no file read whole:Route@106 20871e7bd6d22cf8a1bf733fe8b8f34e9702b2b2f6d661d1ef8140963518ed70
+@coverage internal/activator 0debca01a10c2e37b744daed7b60c23788e9dca7d50086cb33eb0bf25e57ad75
+@coverage internal/applog 0f5d06983a3e8b949179ce74443aba0747cdc0a3d730e6189c9cfee4c808f59b
diff --git a/logs_e2e_test.go b/logs_e2e_test.go
index d0939784f..13d0b8352 100644
--- a/logs_e2e_test.go
+++ b/logs_e2e_test.go
@@ -20,65 +20,7 @@ import (
)
func TestE2ELogsThroughConsole(t *testing.T) {
- useTempCredentials(t)
- clearDeploymentEnv(t)
- checkNoRegistry := requireNoRegistryTouch(t)
-
- tmp := t.TempDir()
- relStore := release.NewDirStore(filepath.Join(tmp, "store"))
- seed, pubB64, err := release.GenerateKey()
- if err != nil {
- t.Fatal(err)
- }
- priv, err := release.ParseSigningKey(seed, "e2e")
- if err != nil {
- t.Fatal(err)
- }
- pub, err := release.ParsePublicKey(pubB64, "e2e")
- if err != nil {
- t.Fatal(err)
- }
- cst, err := console.Open(filepath.Join(tmp, "console.db"))
- if err != nil {
- t.Fatal(err)
- }
- t.Cleanup(func() { cst.Close() })
-
- var srv *console.Server
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- srv.ServeHTTP(w, r)
- }))
- t.Cleanup(ts.Close)
- srv, err = console.NewServer(console.Config{
- Origin: ts.URL,
- Keymail: "http://keymail.invalid", // never dialled — see e2eDeviceLogin
- Registry: filepath.Join(tmp, "registry.db"),
- Releases: relStore,
- ReleasePub: pub,
- Key: priv,
- AppScheme: "http",
- AppsDomain: "oncarlos.test",
- }, cst)
- if err != nil {
- t.Fatal(err)
- }
-
- const addr = "paul@keymail.dev"
- if err := cst.AddMember(console.OpsAccountID, addr, console.RoleOwner, time.Now()); err != nil {
- t.Fatal(err)
- }
- if _, err := cst.CreateAppIn(console.OpsAccountID, "titogo", addr, time.Now()); err != nil {
- t.Fatal(err)
- }
- token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, addr, "e2e@laptop")
- credFile, err := loadCredentials()
- if err != nil {
- t.Fatal(err)
- }
- credFile.put(credential{Console: ts.URL, Address: addr, Token: token, ExpiresAt: expiresAt})
- if err := credFile.save(); err != nil {
- t.Fatal(err)
- }
+ checkNoRegistry, relStore := startLogsE2E(t)
// A box shipped two chunks: routine output, then a wake failure — the
// #131 case, as the shipping loop would have written it.
@@ -160,3 +102,122 @@ func TestE2ELogsThroughConsole(t *testing.T) {
// a local registry.
checkNoRegistry()
}
+
+// startLogsE2E is a real console.Server over a DirStore, an ops app
+// titogo and a device-flow login for its owner. It returns the
+// no-registry check and the store boxes ship chunks into.
+func startLogsE2E(t *testing.T) (checkNoRegistry func(), relStore *release.DirStore) {
+ t.Helper()
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ checkNoRegistry = requireNoRegistryTouch(t)
+
+ tmp := t.TempDir()
+ relStore = release.NewDirStore(filepath.Join(tmp, "store"))
+ seed, pubB64, err := release.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := release.ParseSigningKey(seed, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ pub, err := release.ParsePublicKey(pubB64, "e2e")
+ if err != nil {
+ t.Fatal(err)
+ }
+ cst, err := console.Open(filepath.Join(tmp, "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { cst.Close() })
+
+ var srv *console.Server
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ srv.ServeHTTP(w, r)
+ }))
+ t.Cleanup(ts.Close)
+ srv, err = console.NewServer(console.Config{
+ Origin: ts.URL,
+ Keymail: "http://keymail.invalid", // never dialled — see e2eDeviceLogin
+ Registry: filepath.Join(tmp, "registry.db"),
+ Releases: relStore,
+ ReleasePub: pub,
+ Key: priv,
+ AppScheme: "http",
+ AppsDomain: "oncarlos.test",
+ }, cst)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ const addr = "paul@keymail.dev"
+ if err := cst.AddMember(console.OpsAccountID, addr, console.RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := cst.CreateAppIn(console.OpsAccountID, "titogo", addr, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, addr, "e2e@laptop")
+ credFile, err := loadCredentials()
+ if err != nil {
+ t.Fatal(err)
+ }
+ credFile.put(credential{Console: ts.URL, Address: addr, Token: token, ExpiresAt: expiresAt})
+ if err := credFile.save(); err != nil {
+ t.Fatal(err)
+ }
+
+ return checkNoRegistry, relStore
+}
+
+// A rootfs instance's lines name their process end to end (#366 Task 11
+// follow-up): a real applog.Sink tags them as the activator's capture
+// sites do, the drain is shipped as the agent's logshipFlush writes a
+// chunk, and the member reads them through the console with the real
+// runLogs. --field process=<name> narrows to one process; every line stays
+// on the app stream, never "release" (the ship/promote history's).
+func TestE2ELogsNameTheProcess(t *testing.T) {
+ checkNoRegistry, relStore := startLogsE2E(t)
+
+ const host = "titogo.bab.oncarlos.test"
+ sink := applog.NewSink("box1", time.Now)
+ sink.AppProcess(release.OpsAccount, "titogo", host, release.ProcessWeb, `{"msg":"web says hi","process":"spoof"}`)
+ sink.AppProcess(release.OpsAccount, "titogo", host, "jobs", "worker tick")
+ sink.AppProcess(release.OpsAccount, "titogo", host, release.ProcessRelease, "migrations ran")
+ for k, recs := range sink.Drain() {
+ body, err := applog.EncodeChunk(recs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key, err := applog.ChunkKey(k.Acct, k.App, recs[0].Box, applog.HourOf(recs[0].TS), recs[0].Seq, len(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := relStore.Put(context.Background(), key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ buf := captureStdout(t)
+ runLogs([]string{"-app", "titogo", "-account", "ops"})
+ out := buf.String()
+ for _, want := range []string{"web says hi process=web", "worker tick process=jobs", "migrations ran process=release"} {
+ if !strings.Contains(out, want) {
+ t.Errorf("logs stdout missing %q:\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "spoof") || strings.Contains(out, "[release]") || strings.Count(out, "[app]") != 3 {
+ t.Errorf("want three [app] lines and the platform's process names only:\n%s", out)
+ }
+
+ for _, c := range []struct{ process, want string }{{"web", "web says hi"}, {"jobs", "worker tick"}, {"release", "migrations ran"}} {
+ buf.Reset()
+ runLogs([]string{"-app", "titogo", "-account", "ops", "-field", "process=" + c.process})
+ out := buf.String()
+ if !strings.Contains(out, c.want) || strings.Count(out, "[app]") != 1 {
+ t.Errorf("--field process=%s: want %q alone:\n%s", c.process, c.want, out)
+ }
+ }
+ checkNoRegistry()
+}
diff --git a/main.go b/main.go
index cd4d1ecaf..62f138eb2 100644
--- a/main.go
+++ b/main.go
@@ -45,6 +45,10 @@ func main() {
if cmd == "__rootfs-check-probe" {
os.Exit(runRootfsCheckProbe(args))
}
+ // And the container that makes the check's data volume its user's.
+ if cmd == "__rootfs-check-prepare" {
+ os.Exit(runRootfsCheckPrepare(args))
+ }
switch cmd {
// Asking for help is not an error: it prints on stdout and exits 0, so
// `carlos help | less` works. A bare `carlos` still fails (stderr, 2).
diff --git a/ship_check.go b/ship_check.go
index 0cec4f41f..2e3abe4fb 100644
--- a/ship_check.go
+++ b/ship_check.go
@@ -29,6 +29,9 @@ const (
checkHost = "shop.example.com"
workerSettle = 5 * time.Second
checkLogLines = 20
+ // checkPrepareTimeout bounds the prepare container, which changes one
+ // directory's owner and mode, even under emulation.
+ checkPrepareTimeout = 60 * time.Second
)
// The instance's paths in every check container, as a box lays them out.
@@ -95,8 +98,8 @@ type checkProbeResult struct {
Ports []int `json:"ports"`
}
-// runRootfsCheck runs b's image with rt: release, if declared, to its end;
-// then web, probed with the binary at probe; then each worker, after a
+// runRootfsCheck runs b's image with rt: a container that makes the data
+// volume the check user's; release, if declared, to its end; then web, probed with the binary at probe; then each worker, after a
// healthy web. console is never started (spec §5.10). It writes each line
// of its report to out as it goes. Every container, volume and image it
// made is removed before it returns, on every path, and a removal that
@@ -137,7 +140,7 @@ func (c *rootfsCheck) check(ctx context.Context) {
c.say(fmt.Sprintf("the %s process runs %s, which needs a JIT, and this release does not declare one. it passes here but stops at start on a box. ship it with --jit", name, prog))
}
}
- if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) {
+ if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) || !c.prepareData(ctx) {
return
}
if _, ok := c.b.procs[release.ProcessRelease]; ok && !c.runRelease(ctx) {
@@ -166,25 +169,92 @@ func (c *rootfsCheck) checkArch(ctx context.Context) bool {
}
// makeImageAndVolumes imports the tree and makes the instance's two
-// directories, each a tmpfs volume owned by the check's user. Each name is
-// recorded before the runtime is asked, so a call cut short is cleaned up.
+// directories as volumes. The data volume is a plain local volume, so what
+// release writes there (a migrated CARLOS_DB) is still there for web and
+// the workers, as on a box's disk: Docker and Podman unmount a tmpfs
+// volume, and so empty it, whenever no container holds it. It starts out
+// root's; prepareData gives it to the check's user. The run volume holds
+// only the socket, which web makes afresh, so it stays a tmpfs volume
+// owned by the check's user. Each name is recorded before the runtime is
+// asked, so a call cut short is cleaned up.
func (c *rootfsCheck) makeImageAndVolumes(ctx context.Context) bool {
c.image = c.prefix + ":latest"
if err := c.rt.importTree(ctx, c.b.tree, c.image); err != nil {
return c.runtimeFailed(ctx, "import", err)
}
- for _, v := range []string{c.prefix + "-data", c.prefix + "-run"} {
- c.volumes = append(c.volumes, v)
- _, err := c.rt.run(ctx, nil, "volume", "create", "--label", "carlos-check="+c.id, "--driver", "local",
- "--opt", "type=tmpfs", "--opt", "device=tmpfs",
- "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID), v)
- if err != nil {
+ for _, v := range []struct {
+ name string
+ opts []string
+ }{
+ {c.prefix + "-data", nil},
+ {c.prefix + "-run", []string{"--opt", "type=tmpfs", "--opt", "device=tmpfs",
+ "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID)}},
+ } {
+ c.volumes = append(c.volumes, v.name)
+ args := append([]string{"volume", "create", "--label", "carlos-check=" + c.id, "--driver", "local"}, v.opts...)
+ if _, err := c.rt.run(ctx, nil, append(args, v.name)...); err != nil {
return c.runtimeFailed(ctx, "volume create", err)
}
}
return true
}
+// prepareData makes the data volume's root the check user's, mode 0700, as
+// a box makes an instance's directory, before any process runs. A
+// container of its own runs the probe binary's __rootfs-check-prepare as
+// root with CAP_CHOWN alone, no new privileges, no network, a read-only
+// root, and nothing mounted but the data volume and the probe; the check
+// waits for it to exit 0. It is recorded like every container, so the
+// cleanup removes it.
+func (c *rootfsCheck) prepareData(ctx context.Context) bool {
+ // A process's container is <prefix>-<name>, and a worker may be named
+ // prepare (release.ValidWorkerName). The helper's "_" is outside that
+ // grammar, and inside the runtimes' container names
+ // ([a-zA-Z0-9][a-zA-Z0-9_.-]*), so the two never meet. Volumes and the
+ // image are named in namespaces of their own.
+ ctr := c.prefix + "_prepare"
+ args := []string{"run", "-d", "--name", ctr,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", c.volumeMount(0, checkDataDir),
+ "-v", c.probe + ":" + checkProbeMount + ":ro",
+ "--entrypoint", checkProbeMount,
+ "--label", "carlos-check=" + c.id,
+ c.image,
+ "__rootfs-check-prepare", "--dir", checkDataDir, "--uid", strconv.Itoa(checkUID),
+ }
+ if !c.launch(ctx, ctr, args) {
+ return false
+ }
+ code, _, err := c.waitExit(ctx, ctr, checkPrepareTimeout)
+ if err != nil {
+ return c.runtimeFailed(ctx, "wait", err)
+ }
+ if code == 0 {
+ return true
+ }
+ logs := c.logs(ctx, ctr)
+ if execFormatError(logs...) {
+ return c.fail(checkNoEmulation)
+ }
+ c.runtimeFailed(ctx, "run", fmt.Errorf("__rootfs-check-prepare exited with status %d", code))
+ c.sayLogs(logs)
+ return false
+}
+
+// volumeMount is the -v value that mounts the check's volume i at path,
+// with nocopy, which Docker and Podman both take for a named volume.
+// Without it both fill an empty volume from the image's directory at path
+// each time a container starts, the directory's owner and mode included:
+// an image holding an empty /data/instances/check would hand the prepared
+// data volume back to root when release or web started, and the run
+// volume, a tmpfs volume emptied whenever no container holds it, would be
+// re-owned the same way at every start. Every mount of either says nocopy.
+func (c *rootfsCheck) volumeMount(i int, path string) string {
+ return c.volumes[i] + ":" + path + ":nocopy"
+}
+
// processVars is process name's environment in the check: its own env,
// then --env's values, then the instance's CARLOS_* values (validation keeps CARLOS_ names out of
// a process's env). There is no CARLOS_CONTROL_SOCKET or CARLOS_PURGE:
@@ -225,8 +295,8 @@ func (c *rootfsCheck) runArgs(ctr, name string) []string {
"--memory", mem, "--memory-swap", mem,
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--platform", "linux/arm64", "--user", user,
- "-v", c.volumes[0] + ":" + checkDataDir,
- "-v", c.volumes[1] + ":" + checkRunDir,
+ "-v", c.volumeMount(0, checkDataDir),
+ "-v", c.volumeMount(1, checkRunDir),
"-v", c.probe + ":" + checkProbeMount + ":ro",
}
vars := c.processVars(name)
@@ -242,19 +312,41 @@ func (c *rootfsCheck) runArgs(ctr, name string) []string {
return append(args, p.Command[1:]...)
}
-// start runs process name detached and answers its container. A run the
-// runtime refused is reported: an arm64 program this machine cannot run is
-// RFS-1-C62.
+// start runs process name detached and answers its container.
func (c *rootfsCheck) start(ctx context.Context, name string) (string, bool) {
ctr := c.prefix + "-" + name
+ return ctr, c.launch(ctx, ctr, c.runArgs(ctr, name))
+}
+
+// launch records container ctr, then asks the runtime to run args, which
+// name it. A run the runtime refused is reported: an arm64 program this
+// machine cannot run is RFS-1-C62.
+func (c *rootfsCheck) launch(ctx context.Context, ctr string, args []string) bool {
c.containers = append(c.containers, ctr)
- if _, err := c.rt.run(ctx, nil, c.runArgs(ctr, name)...); err != nil {
+ if _, err := c.rt.run(ctx, nil, args...); err != nil {
if ctx.Err() == nil && execFormatError(err.Error()) {
- return ctr, c.fail(checkNoEmulation)
+ return c.fail(checkNoEmulation)
}
- return ctr, c.runtimeFailed(ctx, "run", err)
+ return c.runtimeFailed(ctx, "run", err)
+ }
+ return true
+}
+
+// waitExit waits up to timeout for ctr to exit and answers its status.
+// timedOut says the wait ran out of time rather than ctx ending.
+func (c *rootfsCheck) waitExit(ctx context.Context, ctr string, timeout time.Duration) (code int, timedOut bool, err error) {
+ wctx, cancel := context.WithTimeout(ctx, timeout)
+ out, err := c.rt.run(wctx, nil, "wait", ctr)
+ timedOut = wctx.Err() != nil && ctx.Err() == nil
+ cancel()
+ if err != nil {
+ return 0, timedOut, err
+ }
+ code, err = strconv.Atoi(lastLine(string(out)))
+ if err != nil {
+ return 0, false, fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out)))
}
- return ctr, true
+ return code, false, nil
}
// runRelease runs release to its end, under its timeout. A failure stops
@@ -269,20 +361,13 @@ func (c *rootfsCheck) runRelease(ctx context.Context) bool {
if s := c.b.procs[release.ProcessRelease].TimeoutSec; s > 0 {
timeout = time.Duration(s) * time.Second
}
- wctx, cancel := context.WithTimeout(ctx, timeout)
- out, err := c.rt.run(wctx, nil, "wait", ctr)
- timedOut := wctx.Err() != nil
- cancel()
+ code, timedOut, err := c.waitExit(ctx, ctr, timeout)
if err != nil {
- if ctx.Err() == nil && timedOut {
+ if timedOut {
return c.fail(fmt.Sprintf("release did not finish within %s", checkDuration(timeout)))
}
return c.runtimeFailed(ctx, "wait", err)
}
- code, err := strconv.Atoi(lastLine(string(out)))
- if err != nil {
- return c.runtimeFailed(ctx, "wait", fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out))))
- }
if code == 0 {
c.say(fmt.Sprintf("release finished in %s", checkDuration(time.Since(began))))
return true
diff --git a/ship_check_prepare_test.go b/ship_check_prepare_test.go
new file mode 100644
index 000000000..d0cbc331f
--- /dev/null
+++ b/ship_check_prepare_test.go
@@ -0,0 +1,210 @@
+//go:build unix
+
+package main
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+// __rootfs-check-prepare makes one directory the given user's, mode 0700:
+// that directory alone, never what is in it, and never through a symlink.
+// The test chowns to its own user and group, which needs no privilege.
+func TestPrepareCheckDir(t *testing.T) {
+ uid, gid := os.Getuid(), os.Getgid()
+ owner := func(t *testing.T, p string) (os.FileMode, int, int) {
+ t.Helper()
+ fi, err := os.Lstat(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := fi.Sys().(*syscall.Stat_t)
+ return fi.Mode().Perm(), int(st.Uid), int(st.Gid)
+ }
+
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ inside := filepath.Join(dir, "shop.db")
+ if err := os.WriteFile(inside, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(dir, uid, gid); err != nil {
+ t.Fatalf("prepareCheckDir: %v", err)
+ }
+ if mode, u, g := owner(t, dir); mode != 0o700 || u != uid || g != gid {
+ t.Errorf("dir is %v %d:%d, want 0700 %d:%d", mode, u, g, uid, gid)
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a file inside became %v: prepare recursed", mode)
+ }
+
+ // A symlink is refused, and its target is left as it was.
+ target := filepath.Join(t.TempDir(), "elsewhere")
+ if err := os.Mkdir(target, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "check")
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(link, uid, gid); err == nil {
+ t.Error("prepareCheckDir followed a symlink")
+ }
+ if mode, _, _ := owner(t, target); mode != 0o755 {
+ t.Errorf("the symlink's target became %v", mode)
+ }
+
+ // A file, and a path that is not there, are refused.
+ if err := prepareCheckDir(inside, uid, gid); err == nil {
+ t.Error("prepareCheckDir took a file")
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a refused file became %v", mode)
+ }
+ if err := prepareCheckDir(filepath.Join(dir, "missing"), uid, gid); err == nil {
+ t.Error("prepareCheckDir took a missing path")
+ }
+}
+
+// prepareCheckDir sets the mode, then the owner, with exactly the
+// arguments the check needs. The order is the property: in the prepare
+// container root holds CAP_CHOWN alone, so once the directory is 65534's it
+// could no longer chmod it (that needs CAP_FOWNER). CI has no root to give
+// a directory away, so this pins the calls through the checkChmod and
+// checkLchown seams; the capabilities themselves are witnessed by the
+// rootful Podman run on a dev box (rootfs Plan 4 Task 11, 2026-10-29).
+func TestPrepareCheckDirSetsModeThenOwner(t *testing.T) {
+ var calls []string
+ oldChmod, oldLchown := checkChmod, checkLchown
+ t.Cleanup(func() { checkChmod, checkLchown = oldChmod, oldLchown })
+ checkChmod = func(name string, mode os.FileMode) error {
+ calls = append(calls, fmt.Sprintf("chmod %s %#o", name, mode))
+ return nil
+ }
+ checkLchown = func(name string, uid, gid int) error {
+ calls = append(calls, fmt.Sprintf("lchown %s %d:%d", name, uid, gid))
+ return nil
+ }
+
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(dir, 65534, 65534); err != nil {
+ t.Fatalf("prepareCheckDir: %v", err)
+ }
+ want := []string{"chmod " + dir + " 0700", "lchown " + dir + " 65534:65534"}
+ if !slices.Equal(calls, want) {
+ t.Errorf("calls %q, want %q", calls, want)
+ }
+
+ // The verb gives --uid as the group too.
+ calls = nil
+ if got := runRootfsCheckPrepare([]string{"--dir", dir, "--uid", "65534"}); got != 0 || !slices.Equal(calls, want) {
+ t.Errorf("the verb: exit %d, calls %q, want 0 and %q", got, calls, want)
+ }
+
+ // A refused path is never changed; a chmod that fails stops the chown.
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ calls = nil
+ if err := prepareCheckDir(link, 65534, 65534); err == nil || len(calls) != 0 {
+ t.Errorf("a symlink: %v, calls %q", err, calls)
+ }
+ checkChmod = func(string, os.FileMode) error { return errors.New("operation not permitted") }
+ calls = nil
+ if err := prepareCheckDir(dir, 65534, 65534); err == nil || len(calls) != 0 {
+ t.Errorf("a failed chmod: %v, calls %q", err, calls)
+ }
+}
+
+// The verb's exit statuses: 0 done, 1 refused, 2 a flag error.
+func TestRunRootfsCheckPrepareExits(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ // The verb gives --uid as both user and group, so run it with the group
+ // it would set only when this user's group has the same number.
+ if os.Getuid() == os.Getgid() {
+ if got := runRootfsCheckPrepare([]string{"--dir", dir, "--uid", strconv.Itoa(os.Getuid())}); got != 0 {
+ t.Errorf("a directory: exit %d, want 0", got)
+ }
+ }
+ if got := runRootfsCheckPrepare([]string{"--dir", link, "--uid", strconv.Itoa(os.Getuid())}); got != 1 {
+ t.Errorf("a symlink: exit %d, want 1", got)
+ }
+ for _, args := range [][]string{
+ nil,
+ {"--uid", "65534"},
+ {"--dir", dir},
+ {"--dir", dir, "--uid", "-1"},
+ {"--dir", dir, "--uid", "x"},
+ {"--dir", dir, "--uid", "65534", "extra"},
+ {"--nope"},
+ } {
+ if got := runRootfsCheckPrepare(args); got != 2 {
+ t.Errorf("%q: exit %d, want 2", args, got)
+ }
+ }
+}
+
+// The binary dispatches the verb before its command switch, as it does
+// __rootfs-check-probe: the prepare container runs it by that name.
+func TestRootfsCheckPrepareThroughTheBinary(t *testing.T) {
+ if testing.Short() {
+ t.Skip("runs the carlos binary")
+ }
+ if os.Getuid() != os.Getgid() {
+ t.Skip("the verb sets --uid as the group too, which this user may not")
+ }
+ bin := buildCarlos(t)
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ run := func(args ...string) (int, string) {
+ cmd := exec.Command(bin, append([]string{"__rootfs-check-prepare"}, args...)...)
+ cmd.Env = carlosTestEnv(t)
+ cmd.Dir = t.TempDir()
+ out, err := cmd.CombinedOutput()
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ return ee.ExitCode(), string(out)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return 0, string(out)
+ }
+ uid := strconv.Itoa(os.Getuid())
+ if code, out := run("--dir", link, "--uid", uid); code != 1 || !strings.Contains(out, "is not a directory") {
+ t.Errorf("a symlink: exit %d, %q; want 1 and the reason", code, out)
+ }
+ if code, out := run("--dir", dir, "--uid", uid); code != 0 {
+ t.Fatalf("a directory: exit %d, %q", code, out)
+ }
+ if fi, err := os.Lstat(dir); err != nil || fi.Mode().Perm() != 0o700 {
+ t.Errorf("after the verb the directory is %v (%v), want 0700", fi.Mode().Perm(), err)
+ }
+}
diff --git a/ship_check_probe.go b/ship_check_probe.go
index 0be29f778..96184ff4c 100644
--- a/ship_check_probe.go
+++ b/ship_check_probe.go
@@ -100,6 +100,53 @@ func runRootfsCheckProbe(args []string) int {
}
}
+// runRootfsCheckPrepare is __rootfs-check-prepare, run in the check's
+// prepare container as root with CAP_CHOWN alone: it makes the directory at
+// --dir mode 0700 and owned by --uid, as user and group (prepareCheckDir).
+// Exit 0 when done, 1 when refused or failed (the reason on stderr, which
+// the check shows as the container's last lines), 2 on a flag error.
+func runRootfsCheckPrepare(args []string) int {
+ fs := flag.NewFlagSet("__rootfs-check-prepare", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ dir := fs.String("dir", "", "the directory to prepare")
+ uid := fs.Int("uid", -1, "its owner, as user and group")
+ if err := fs.Parse(args); err != nil || *dir == "" || *uid < 0 || fs.NArg() > 0 {
+ return 2
+ }
+ if err := prepareCheckDir(*dir, *uid, *uid); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return 1
+ }
+ return 0
+}
+
+// checkChmod and checkLchown are prepareCheckDir's two changes. Vars so a
+// test can pin their order and arguments: CI has no root to give a
+// directory away. Production never changes them.
+var (
+ checkChmod = os.Chmod
+ checkLchown = os.Lchown
+)
+
+// prepareCheckDir makes dir mode 0700 and owned by uid:gid: dir alone,
+// never what is in it, and never through a symlink, which Lstat refuses
+// with anything else that is not a directory. The mode goes first: once
+// the directory is another user's, root without CAP_FOWNER could no longer
+// change it.
+func prepareCheckDir(dir string, uid, gid int) error {
+ fi, err := os.Lstat(dir)
+ if err != nil {
+ return err
+ }
+ if !fi.IsDir() {
+ return fmt.Errorf("%s is not a directory", dir)
+ }
+ if err := checkChmod(dir, 0o700); err != nil {
+ return err
+ }
+ return checkLchown(dir, uid, gid)
+}
+
// checkProbeGet asks GET / once, for the check's host, and answers the
// status.
func checkProbeGet(ctx context.Context, client *http.Client) (int, error) {
diff --git a/ship_check_test.go b/ship_check_test.go
index 95cf367a0..cd59958b2 100644
--- a/ship_check_test.go
+++ b/ship_check_test.go
@@ -27,7 +27,9 @@ import (
// objects the check made, which must end empty.
// checkName is the shape of every name the check gives the runtime.
-var checkName = regexp.MustCompile(`^carlos-check-[0-9a-f]{8}(-[a-z][a-z0-9-]*|:latest)$`)
+// A process's container is <prefix>-<process>; the check's own helper is
+// <prefix>_<helper>, a form no process name can take.
+var checkName = regexp.MustCompile(`^carlos-check-[0-9a-f]{8}(-[a-z][a-z0-9-]*|_[a-z]+|:latest)$`)
type fakeCheck struct {
t *testing.T
@@ -39,8 +41,9 @@ type fakeCheck struct {
cleaning bool
arch string
- waitOut string
- waitHang bool
+ waitOut string // every wait's answer, unless waitBy has the process
+ waitBy map[string]string // wait's answer, by process
+ waitHang string // the process whose wait never returns
probeOut string
probeErr error
runErr map[string]error // by process
@@ -60,6 +63,7 @@ func newFakeCheck(t *testing.T) *fakeCheck {
t: t, made: map[string]bool{}, live: map[string]bool{},
arch: "aarch64", waitOut: "0\n", probeOut: `{"status":200,"after_ms":42}` + "\n",
runErr: map[string]error{}, state: map[string]string{}, logs: map[string]string{},
+ waitBy: map[string]string{},
failAt: -1, cancelAt: -1, out: &bytes.Buffer{},
removeErr: map[string]error{},
}
@@ -67,9 +71,10 @@ func newFakeCheck(t *testing.T) *fakeCheck {
func (f *fakeCheck) rt() containerRuntime { return containerRuntime{name: "docker", run: f.run} }
-// procOf is the process a container is named for.
+// procOf is the process a container is named for, or "_" and the helper's
+// name for one of the check's own (<prefix>_prepare is "_prepare").
func procOf(ctr string) string {
- return strings.TrimPrefix(ctr, ctr[:len("carlos-check-")+9])
+ return strings.TrimPrefix(ctr[len("carlos-check-")+8:], "-")
}
func flagValue(args []string, flag string) string {
@@ -129,9 +134,14 @@ func (f *fakeCheck) run(ctx context.Context, stdin io.Reader, args ...string) ([
makes = "container:" + ctr
}
if makes != "" {
- if name := makes[strings.IndexByte(makes, ':')+1:]; !checkName.MatchString(name) {
+ name := makes[strings.IndexByte(makes, ':')+1:]
+ if !checkName.MatchString(name) {
f.t.Errorf("%v names %q", args, name)
}
+ // Docker and Podman refuse a second container by a name in use.
+ if args[0] == "run" && f.made[makes] {
+ return nil, fmt.Errorf(`Error: creating container storage: the container name %q is already in use`, name)
+ }
f.made[makes] = true
}
if args[0] == "import" {
@@ -160,10 +170,14 @@ func (f *fakeCheck) run(ctx context.Context, stdin io.Reader, args ...string) ([
case "run":
return []byte("0123abcd\n"), f.runErr[procOf(flagValue(args, "--name"))]
case "wait":
- if f.waitHang {
+ proc := procOf(last)
+ if f.waitHang == proc {
<-ctx.Done()
return nil, ctx.Err()
}
+ if out, ok := f.waitBy[proc]; ok {
+ return []byte(out), nil
+ }
return []byte(f.waitOut), nil
case "exec":
return []byte(f.probeOut), f.probeErr
@@ -295,8 +309,9 @@ func TestRootfsCheckHappyPath(t *testing.T) {
want := []string{
"info", "import", "volume create data", "volume create run",
+ "run _prepare", "wait _prepare",
"run release", "wait release", "run web", "exec web", "run jobs", "inspect jobs",
- "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
+ "rm -f _prepare", "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
}
if got := f.summary(); !slices.Equal(got, want) {
t.Errorf("calls:\n got %q\nwant %q", got, want)
@@ -401,8 +416,8 @@ func TestRootfsCheckRunArgs(t *testing.T) {
}
}
wantMounts := []string{
- prefix + "-data:/data/instances/check",
- prefix + "-run:/run/carlos/instances/check",
+ prefix + "-data:/data/instances/check:nocopy",
+ prefix + "-run:/run/carlos/instances/check:nocopy",
"/probe/carlos:/opt/carlos/carlos:ro",
}
if !slices.Equal(mounts, wantMounts) {
@@ -457,12 +472,30 @@ func TestRootfsCheckRunArgs(t *testing.T) {
if want := []string{"exec", name, "/opt/carlos/carlos", "__rootfs-check-probe", "--socket", "/run/carlos/instances/check/app.sock", "--timeout", "120s"}; !slices.Equal(exec, want) {
t.Errorf("exec = %q, want %q", exec, want)
}
- // Volumes are tmpfs, owned by the check's user.
- if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-data"}; !slices.Equal(f.calls[2], want) {
- t.Errorf("volume create = %q, want %q", f.calls[2], want)
+ // The data volume is a plain local volume, so what release writes is
+ // still there for web, as on a box's disk: a tmpfs volume is emptied
+ // whenever no container holds it. The run volume, the socket's, is
+ // tmpfs, owned by the check's user.
+ creates := map[string][]string{}
+ for _, c := range f.calls {
+ if c[0] == "volume" && c[1] == "create" {
+ creates[procOf(c[len(c)-1])] = c
+ }
+ }
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", prefix + "-data"}; !slices.Equal(creates["data"], want) {
+ t.Errorf("data volume create = %q, want %q", creates["data"], want)
}
- if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(f.calls[9], want) {
- t.Errorf("inspect = %q, want %q", f.calls[9], want)
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-run"}; !slices.Equal(creates["run"], want) {
+ t.Errorf("run volume create = %q, want %q", creates["run"], want)
+ }
+ var inspect []string
+ for _, c := range f.calls {
+ if c[0] == "inspect" {
+ inspect = c
+ }
+ }
+ if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(inspect, want) {
+ t.Errorf("inspect = %q, want %q", inspect, want)
}
}
@@ -535,7 +568,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
noSettle(t)
t.Run("an exit", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitOut = "3\n"
+ f.waitBy["release"] = "3\n"
f.logs["release"] = "migrating\nno such table: orders\n"
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
want := []string{"release exited with status 3. its last lines:", " migrating", " no such table: orders", checkC75}
@@ -549,7 +582,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
t.Run("a timeout", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitHang = true
+ f.waitHang = release.ProcessRelease
procs := shopProcs()
procs[release.ProcessRelease] = release.Process{Command: []string{"/srv/migrate"}, TimeoutSec: 1}
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, procs), "/probe/carlos", f.out)
@@ -564,6 +597,175 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
}
+// The data volume is a new local volume, so root's: before any process
+// runs, one container of its own makes it the check user's, mode 0700, as
+// root with CAP_CHOWN alone, no network, and only that volume and the
+// probe binary mounted.
+func TestRootfsCheckPreparesTheDataVolume(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ procs map[string]release.Process
+ first string // the first process after prepare
+ }{
+ {"with release", shopProcs(), "run release"},
+ {"web alone", map[string]release.Process{release.ProcessWeb: shopProcs()[release.ProcessWeb]}, "run web"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, c.procs), "/probe/carlos", f.out)
+ if r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ sum := f.summary()
+ at := slices.Index(sum, "run _prepare")
+ if at < 0 || at+2 >= len(sum) || sum[at+1] != "wait _prepare" || sum[at+2] != c.first {
+ t.Fatalf("calls %q: want run _prepare, wait _prepare, then %s", sum, c.first)
+ }
+ if create := slices.Index(sum, "volume create data"); create < 0 || create > at {
+ t.Errorf("calls %q: prepare before the data volume exists", sum)
+ }
+ prep := f.runOf("_prepare")
+ name := flagValue(prep, "--name")
+ prefix := strings.TrimSuffix(name, "_prepare")
+ id := strings.TrimPrefix(prefix, "carlos-check-")
+ want := []string{"run", "-d", "--name", name,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", prefix + "-data:/data/instances/check:nocopy",
+ "-v", "/probe/carlos:/opt/carlos/carlos:ro",
+ "--entrypoint", "/opt/carlos/carlos",
+ "--label", "carlos-check=" + id,
+ prefix + ":latest",
+ "__rootfs-check-prepare", "--dir", "/data/instances/check", "--uid", "65534",
+ }
+ if !slices.Equal(prep, want) {
+ t.Errorf("prepare's argv\n got %q\nwant %q", prep, want)
+ }
+ var caps []string
+ for i, a := range prep {
+ if a == "--cap-add" {
+ caps = append(caps, prep[i+1])
+ }
+ }
+ if !slices.Equal(caps, []string{"CHOWN"}) {
+ t.Errorf("prepare adds %q, want CHOWN alone", caps)
+ }
+ if !slices.Contains(sum, "rm -f _prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", sum)
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
+// The helper's container is named outside the process names' grammar, so a
+// release may declare a worker named prepare, and it runs as any worker.
+func TestRootfsCheckWorkerNamedLikeTheHelper(t *testing.T) {
+ noSettle(t)
+ if !release.ValidWorkerName("prepare") {
+ t.Fatal("prepare is no longer a valid worker name; pick another of the helper's names")
+ }
+ f := newFakeCheck(t)
+ procs := shopProcs()
+ procs["prepare"] = release.Process{Command: []string{"/srv/jobs", "prepare"}}
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, procs), "/probe/carlos", f.out)
+ if r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ if !slices.Contains(r.lines, "prepare is still running after 5.0 s") {
+ t.Errorf("report = %q, want the prepare worker running", r.lines)
+ }
+ if w := f.runOf("prepare"); w == nil || flagValue(w, "--entrypoint") != "/srv/jobs" {
+ t.Errorf("the prepare worker ran as %q", w)
+ }
+ if h := f.runOf("_prepare"); h == nil || flagValue(h, "--entrypoint") != "/opt/carlos/carlos" {
+ t.Errorf("the helper ran as %q", h)
+ }
+ f.checkLeftNothing(t)
+}
+
+// Docker and Podman fill an empty named volume from the image's directory
+// at the mount point each time a container starts, owner and mode
+// included. The data volume stays empty after prepare, so an image with an
+// empty /data/instances/check would hand it back to root at release's or
+// web's start; the run volume, tmpfs, is empty at every start. So every
+// mount of either volume, in every container the check runs, says nocopy.
+func TestRootfsCheckVolumesNeverCopyUp(t *testing.T) {
+ noSettle(t)
+ f := newFakeCheck(t)
+ if r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out); r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ runs := 0
+ for _, c := range f.calls {
+ if c[0] != "run" {
+ continue
+ }
+ runs++
+ name := flagValue(c, "--name")
+ prefix := name[:len("carlos-check-")+8]
+ var vols []string
+ for i, a := range c {
+ if a == "-v" && strings.HasPrefix(c[i+1], prefix+"-") {
+ vols = append(vols, c[i+1])
+ }
+ }
+ want := []string{prefix + "-data:/data/instances/check:nocopy", prefix + "-run:/run/carlos/instances/check:nocopy"}
+ if procOf(name) == "_prepare" {
+ want = want[:1]
+ }
+ if !slices.Equal(vols, want) {
+ t.Errorf("%s mounts %q, want %q", procOf(name), vols, want)
+ }
+ }
+ if runs != 4 {
+ t.Errorf("%d runs, want prepare, release, web and jobs", runs)
+ }
+}
+
+// A prepare that does not exit 0 fails the check before any process runs,
+// and the check still removes everything it made.
+func TestRootfsCheckPrepareFailureStopsTheCheck(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ setup func(f *fakeCheck)
+ want []string
+ }{
+ {"an exit", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "1\n"
+ f.logs["_prepare"] = "chown /data/instances/check: operation not permitted\n"
+ }, []string{"docker run: __rootfs-check-prepare exited with status 1", " chown /data/instances/check: operation not permitted", checkC75}},
+ {"an amd64 probe", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "255\n"
+ f.logs["_prepare"] = `exec /opt/carlos/carlos: exec format error` + "\n"
+ }, []string{checkNoEmulation, checkC75}},
+ {"not an exit status", func(f *fakeCheck) {
+ f.waitBy["_prepare"] = "gone\n"
+ }, []string{`docker wait: "gone" is not an exit status`, checkC75}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ c.setup(f)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
+ if !r.failed || !slices.Equal(r.lines[1:], c.want) {
+ t.Errorf("report = %q (failed %v), want C60 then %q", r.lines, r.failed, c.want)
+ }
+ for _, s := range f.summary() {
+ if s == "run release" || s == "run web" || s == "run jobs" {
+ t.Errorf("%q after prepare failed", s)
+ }
+ }
+ if !slices.Contains(f.summary(), "rm -f _prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", f.summary())
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
func TestRootfsCheckWorkerThatExits(t *testing.T) {
noSettle(t)
f := newFakeCheck(t)
@@ -787,6 +989,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
done
find "$TMPDIR" -name '*.env' >> "$log" ;;
exec) echo "$FAKE_PROBE"; exit "$FAKE_PROBE_EXIT" ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
@@ -833,7 +1036,8 @@ exit 0
}
log, _ := os.ReadFile(logPath)
for _, want := range []string{"rm -f carlos-check-", "volume rm carlos-check-", "rmi carlos-check-",
- " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 "} {
+ " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 ",
+ " --cap-add CHOWN ", " __rootfs-check-prepare --dir /data/instances/check --uid 65534\n"} {
if !strings.Contains(string(log), want) {
t.Errorf("the runtime never saw %q:\n%s", want, log)
}
@@ -947,8 +1151,8 @@ func TestShipCheckWithoutEnvUnchanged(t *testing.T) {
"--memory", "1073741824", "--memory-swap", "1073741824",
"--cap-drop", "ALL", "--security-opt", "no-new-privileges",
"--platform", "linux/arm64", "--user", "65534:65534",
- "-v", prefix + "-data:/data/instances/check",
- "-v", prefix + "-run:/run/carlos/instances/check",
+ "-v", prefix + "-data:/data/instances/check:nocopy",
+ "-v", prefix + "-run:/run/carlos/instances/check:nocopy",
"-v", "/probe/carlos:/opt/carlos/carlos:ro",
"-e", "A_FIRST=1",
"-e", "CARLOS_DB=/data/instances/check/shop.example.com.db",
@@ -1148,6 +1352,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
prev=$a
done ;;
exec) echo '{"status":200,"after_ms":7}' ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
diff --git a/ship_rootfs_unix_test.go b/ship_rootfs_unix_test.go
index f85f9197b..18d1ad00a 100644
--- a/ship_rootfs_unix_test.go
+++ b/ship_rootfs_unix_test.go
@@ -111,6 +111,7 @@ func TestShipRootfsCheckCleansUpOnInterrupt(t *testing.T) {
case "$1" in
info) echo aarch64 ;;
import) cat > /dev/null ;;
+wait) echo 0 ;;
exec) : > "$FAKE_READY"; exec sleep 60 ;;
esac
exit 0