agent: the box's interactive session worker (rootfs plan 6)
The box's half of interactive sessions (rootfs plan 6 task 12): for a reconcile-noted session marker on a row this box owns (and, for a region-HA row, holds awake: Service.HoldsAwake, PF-15), the worker checks the id, reads and verifies the signed grant, dials the console's box door, reads the Open, refuses over the connection (incarnation, off, import, the activator's claim/flat/wake/busy) or starts the tty unit through RunCmd and relays frames to the pty until the command exits, idles, reaches its limit, the console hangs up, the connection goes or a newer session replaces it. One grant GET and one config.json GET per session on the owning box; none elsewhere; no writes. Armed beside the runs worker with the box judge; logs RFS-6-C48 to C57. Census overlay rootfs-apps-6 re-proposed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
approved_rootfs_copy_test.go+3 −0docs/superpowers/notes/census-proposal-rootfs-apps-6.md+16 −3docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md+10 −10internal/activator/activator.go+11 −0internal/activator/cmd_test.go+67 −0internal/host/agent.go+8 −0internal/host/changeindex.go+2 −0internal/host/interactive.go+928 −0internal/host/interactive_e2e_linux_test.go+234 −0internal/host/interactive_test.go+1,723 −0internal/host/lifetime_gating_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv+28 −4
Intent
<task-notification> <task-id>a32fb75664237bf8f</task-id> <tool-use-id>toolu_01YBwEeDsdwXheu6uVc7W3XP</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a32fb75664237bf8f.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 11: box door, splice, sweep" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE **Commit:** 5906ae16 (fix round 2), on top of 6bf1161d. Not pushed. Git printed the usual `packed-refs.lock` warning, but the commit landed. **Tests:** the session and sweep tests pass under `-race -count=2`, including three new tests that were RED before the fix; the sweep, cutover, job and census tests pass, the census card is unchanged (`admitSession` re-pinned), the three cross-builds succeed, and all 5 fix-round mutations are killed.</result> <usage><subagent_tokens>466835</subagent_tokens><tool_uses>12</tool_uses><duration_ms>826983</duration_ms></usage> </task-notification>
<cross-session-message from="uds:/run/user/1001/cc-socks/342481.sock" from-name="platform-f6" from-mode="bypass"> Release request from Paul (relayed by the devbox session): he wants a release cut from current main eab053ae and rolled dev first, then flagship. Flagship picks up v0.32.1 (#471) plus the console Protection tab (66c324fd, eab053ae), devbox mode 2c66e563 and your 62e19e36. Devbox mode is inert on fleet boxes: only `carlos devbox serve` uses it, and the one shared-path change bounds the _headers and _redirects reads in static serving. Are you able to cut and roll it as v0.32.2? If you're busy or mid-something, say so and I'll run it from your v0.32.1 brief instead. Please reply either way. I'm also getting the devbox install on DOCS-T1 ready, which needs that release's binary. </cross-session-message>
How are we doing overall in our rootfs plans? Are we spinning? Is the destination in sight?
<cross-session-message from="uds:/run/user/1001/cc-socks/342481.sock" from-name="platform-f6" from-mode="bypass"> Dev is on v0.32.2 (cut from main eab053ae, published 10:51Z). Every dev box was current by 11:07Z, and box-1 reconnected at 11:06:54Z. The dev console has been on the v0.32.2 build 0ea29db3 since 11:09:15Z. Your midnight #471 recheck runs against v0.32.2. Paul gave the flagship go, so the flagship roll is starting now. </cross-session-message>
Attributed to this commit: 20.4 g CO₂e (2,520,433 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on rootfs-apps-6-interactive, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go| index 7d5aca54a..bcd626046 100644 |
| --- a/approved_rootfs_copy_test.go |
| +++ b/approved_rootfs_copy_test.go |
| @@ -262,6 +262,9 @@ var rootfsCopyBuilt = []string{ |
| // Plan 6 Task 10: the console's session door |
| // (internal/console/apiinteractive.go) |
| "RFS-6-C27", "RFS-6-C32", "RFS-6-C33", "RFS-6-C34", "RFS-6-C35", "RFS-6-C36", "RFS-6-C37", |
| + // Plan 6 Task 12: the box's session lines in carlos logs |
| + // (internal/host/interactive.go) |
| + "RFS-6-C48", "RFS-6-C49", "RFS-6-C50", "RFS-6-C51", "RFS-6-C52", "RFS-6-C53", "RFS-6-C54", "RFS-6-C55", "RFS-6-C56", "RFS-6-C57", |
| } |
| func mustParseRootfsRecord(t *testing.T) []copyRow { |
diff --git a/docs/superpowers/notes/census-proposal-rootfs-apps-6.md b/docs/superpowers/notes/census-proposal-rootfs-apps-6.md| index 50b4641a1..db2c868a2 100644 |
| --- a/docs/superpowers/notes/census-proposal-rootfs-apps-6.md |
| +++ b/docs/superpowers/notes/census-proposal-rootfs-apps-6.md |
| @@ -1,6 +1,6 @@ |
| # Census approval: rootfs-apps-6 |
| -Ruling `census-ruling-rootfs-apps-6`. The independent reviewer approves or rejects every change below, 17 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| +Ruling `census-ruling-rootfs-apps-6`. The independent reviewer approves or rejects every change below, 28 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| @@ -14,6 +14,7 @@ Ruling `census-ruling-rootfs-apps-6`. The independent reviewer approves or rejec |
| | `internal/activator/rootfs_service.go` `Service.residentLeaseLost` | body | unchanged (2) | rootfs Plan 6 Task 7a (Call A1): residentLeaseLostLocked also returns one kill func per one-shot unit that may run; each runs off a.mu in the same WaitGroup as stopRootfsWorkersAtLoss and killResidentGens, which still run only for a resident (gens non-nil); the kills go to root's existing /stop through KillOneShot; no read added | |
| | `internal/activator/rootfsrelease.go` `Service.releaseAdmitLocked` | body | unchanged (3) | rootfs Plan 6 Task 9 (PF-17): the busy check is holdBusyLocked(e, RoleCmd) where it was cmdBusyLocked(e): only established cmd-unit holds and cmd-unit lease stops refuse a release command, never a started session, whose tty unit is its own; cmdStartInFlightLocked now also counts a session's start in flight (merge ruling M2), so a release is refused during either role's start window, short and bounded, as swap admission is (fix round 2 ruling: a refusal at admission is not executed and takes the ordinary retry); no read added, read sites unchanged | |
| | `internal/activator/rootfsrelease.go` `Service.runRelease` | body | unchanged (12) | rootfs Plan 6 Task 9: newCmdHold takes the hold's role; a release command's hold is instancectl.RoleCmd, the unit it runs in; nothing else changed, no read added | |
| +| `internal/host/agent.go` `runAgent` | body | unchanged (6) | rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites | |
| | `internal/host/runexec.go` `runsWorker.execute` | body | unchanged (2) | rootfs Plan 6 Task 7a (INV-2): sets CmdSpec.AfterSettled to remove the run's directory (runs.RemoveRunDir under the instance's own directory, as cleanUp did) once the activator has proven no unit of the run runs; finish and cleanUp take removeDir, true only on the incarnation refusal before RunCmd; the directory goes later or at the same point, never earlier; no read added | |
| | `internal/host/units/carlos-instance-cmd@.service` `external` | body | unchanged (1) | rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else | |
| | `internal/host/units/carlos-instance-gen@.service` `external` | body | unchanged (1) | rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else | |
| @@ -34,7 +35,7 @@ Ruling `census-ruling-rootfs-apps-6`. The independent reviewer approves or rejec |
| | `internal/activator/cmdunit.go` `cmdUnit.Poll` | sites | +registry:Host ×4, +registry:Runtime, +whole:Route ×5 | rootfs Plan 6 Task 8 (PF-7): role-aware: a cmd unit polls as before (CmdStatusRootfs on a rootfs row, CmdStatus on a binary one); a tty unit polls through TTYControl, TTYStatusRootfs on a rootfs row and TTYStatus on a binary one, or ErrNoTTY without the session verbs; any other role is refused; all status reads over the control socket, no decision; the new sites are the error text (rt.Host), the tty arm runtime check (rt.Runtime) and the route passed | |
| | `internal/activator/rootfs_service.go` `Service.rootfsTick` | sites | +whole:Route | rootfs Plan 6 Task 7a: the no-signal fallback also covers a hibernating rootfs entry with a one-shot unit that may run (oneShotHoldsLocked); it latches ownerKilled and runs each one-shot kill func (KillOneShot to root's existing /stop) with go off a.mu, beside a resident's killResidentGens and stopRootfsWorkersAtLoss as before; new site +whole:Route is e.route.Rootfs(); stops more, starts nothing | |
| -Envelopes re-pinned: `.`, `internal/activator`, `internal/appconfig`, `internal/host`, `internal/host/units`, `internal/instancectl`, `internal/instanceexec`, `internal/layout`, `internal/provision`. |
| +Envelopes re-pinned: `.`, `internal/activator`, `internal/appconfig`, `internal/host`, `internal/host/units`, `internal/instancectl`, `internal/instanceexec`, `internal/interactive`, `internal/layout`, `internal/provision`. |
| Removed units: the scan finds neither the declaration nor any of its sites. |
| @@ -58,6 +59,7 @@ Recorded dispositions, which each change must still satisfy: |
| - `internal/activator/rootfs_service.go` `Service.residentLeaseLost`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8 (C7): a resident's lost lease marks it and then kills its generations off a.mu (killResidentGens);rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1.10: a resident's lost lease stops its workers (stopRootfsWorkersAtLoss, proven gone) in parallel with killResidentGens; rt is taken under the lock and passed to killResidentGens in place of e.route (the same route); site +whole:Route (that local rt); no file read |
| - `internal/activator/rootfsrelease.go` `Service.releaseAdmitLocked`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.10]: new; the owner's half of a release's admission under a.mu: refuses while a run holds the cmd unit, and for an awake owner mirrors Swap's exclusions (worker or non-instance kind, a layout other than flat or nested through the existing swapLayout, members, a raised parent, a resize, a cmd start in flight); in-memory only; refusals only |
| - `internal/activator/rootfsrelease.go` `Service.runRelease`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1: new; the one place a release command runs. Refuses while any record of the host is open; skips the row's good build (releaseRan); reads the declared processes (declaredProcesses: the existing staged-manifest read) and refuses on a read error, never treating it as no release; runs only when releaseDue; needs a lease watch and a ReleaseBackend; its gate is the caller's plus the lease's Err and its safety deadline more than releaseStopLead (cmdStopBound, 2 min) away; creates the record under a.mu after releaseAdmitLocked; publishes the generations file and the build state (recordBuild) before anything runs; times out at the manifest's timeout_sec (default, capped at runs.MaxTimeout); ReleaseEnv; a supervisor stops the unit ahead of the lease's safety deadline; StartRelease under the exec gate; polls the unit (root's existing cmd status); stops and settles it (the existing cmd hold's stop, cmdStopBound); only a non-zero exit, a signal or the timeout with the unit proven gone is the build's failure (*ReleaseError); registry:Host sites are the record key and log lines |
| +- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added |
| - `internal/host/runexec.go` `runsWorker.execute`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): runs one picked run to its result in the bucket; every root action goes through instance control;rev3=PROPOSED-325;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=emits the run's start and end as member log events through the agent's EventSink; reads unchanged |
| - `internal/host/units/carlos-instance-cmd@.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=the cmd unit template (applied by PID 1 as root; its process runs as carlos): extends the J4 seed pattern to the run role. The template equals the seed template outside named lines, and the template-equality test pins that. Root lays out a staged executable validated by the same refuseStagedExe the seed and generation paths use, then starts this unit, which runs as carlos with the instance's own reach. No new trust of registry, /data or agent-asserted content beyond the seed path |
| - `internal/host/units/carlos-instance-gen@.service` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| @@ -92,12 +94,23 @@ New dispositions, which census-propose wrote and the reviewer checks against the |
| - new `internal/activator/rootfs_service.go:Service.residentLeaseLostLocked`: reads +whole:Route ×2; written legacy, accepted-legacy, frozen |
| - new `internal/activator/rootfs_service.go:Service.residentLeaseShort`: reads +whole:Route ×2; written legacy, accepted-legacy, frozen |
| - new `internal/activator/rootfsenv.go:ExecBackend.rootfsTTYVars`: reads +registry:Socket, +whole:Route; written legacy, accepted-legacy, frozen |
| +- new `internal/host/interactive.go:interactiveWorker.consider`: reads +registry:HA, +whole:Route ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/host/interactive.go:interactiveWorker.owned`: reads +registry:Account, +registry:App, +registry:Provisioned, +whole:Route ×3; written legacy, accepted-legacy, frozen |
| +- new `internal/host/interactive.go:sessionRun.bridge`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/host/interactive.go:sessionRun.receiveOpen`: reads +file:Open ×6; written legacy, accepted-legacy, frozen |
| +- new `internal/host/interactive.go:sessionRun.serve`: reads +file:Open, +whole:Route; written legacy, accepted-legacy, frozen |
| - new `internal/host/units/carlos-instance-rootfs-tty@.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/host/units/carlos-instance-tty@.service:external`: reads +file:external; written legacy, accepted-legacy, frozen |
| - new `internal/instancectl/cmd.go:Server.oneShotStatus`: reads +file:Query ×3; written legacy, accepted-legacy, frozen |
| - new `internal/instanceexec/tty_linux.go:receivePTY`: reads +file:Fstat; written legacy, accepted-legacy, frozen |
| +- new `internal/interactive/frames.go:Receive`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/interactive/frames.go:handshakeRecorder.Read`: reads +file:Read ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/interactive/grant.go:MintToken`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- new `internal/interactive/interactive.go:Open.Check`: reads +file:Open; written legacy, accepted-legacy, frozen |
| +- new `internal/interactive/interactive.go:Open.Normalized`: reads +file:Open ×2; written legacy, accepted-legacy, frozen |
| +- new `internal/interactive/interactive.go:type Open`: reads +file:Open; written legacy, accepted-legacy, frozen |
| - reads `internal/activator/cmdunit.go:cmdUnit.StopAndSettle`: +registry:Host, +whole:Route; keeps legacy, task accepted-legacy |
| -Seal: `1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7` → `f02fd204e9316044a993e8c66318a8429555366b3e1a7b5a0388ed4376d334ad`. |
| +Seal: `1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7` → `75b5bf971620474d35c8cd06aab78f0c4edfc24d925729daa3567bcf369ca644`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md| index afe8bea1a..87f2f2f45 100644 |
| --- a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md |
| +++ b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md |
| @@ -518,16 +518,16 @@ From the plan: Every string is human text the plan introduces. Existing approved |
| | RFS-6-C45 | apps_swap.go | %s: interactive sessions are off | approved | |
| | RFS-6-C46 | apps_swap.go | apps set: the change did not stick (the console stored interactive %s). run it again | approved | |
| | RFS-6-C47 | apps_swap.go (appsSetNothing, replacing today's IP1-57 `apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow or --size`, also held by the zero-downtime record zdd.apps-set.nothing and the instance-policy record IP1-57, which change with it; revised 2026-10-30 by the Plan 6 preflight, PF-10, to keep --egress-allow and --size; the first draft read `apps set: nothing to set. Pass --swap, --swap-concurrency, --interactive or one of the update settings`) | apps set: nothing to set. Pass --swap, --swap-concurrency, --egress-allow, --size or --interactive | approved | |
| -| RFS-6-C48 | carlos logs | interactive session %s opened by %s | approved | |
| -| RFS-6-C49 | carlos logs | interactive session %s ended with exit %d after %s | approved | |
| -| RFS-6-C50 | carlos logs | interactive session %s ended after %s: %s | approved | |
| -| RFS-6-C51 | `carlos logs` reason | 30 minutes passed without a keystroke | approved | |
| -| RFS-6-C52 | `carlos logs` reason | it reached its 6 hour limit | approved | |
| -| RFS-6-C53 | `carlos logs` reason | the person's connection closed | approved | |
| -| RFS-6-C54 | `carlos logs` reason | the box lost its connection to the console | approved | |
| -| RFS-6-C55 | carlos logs | interactive session %s did not start: %s | approved | |
| -| RFS-6-C56 | `carlos logs` refusal | interactive sessions are off for this app | approved | |
| -| RFS-6-C57 | `carlos logs` refusal | the box was still closing the last session | approved | |
| +| RFS-6-C48 | internal/host/interactive.go (`carlos logs`, sessionStartedLine, built by Plan 6 Task 12) | interactive session %s opened by %s | approved | |
| +| RFS-6-C49 | internal/host/interactive.go (`carlos logs`, sessionEndedLine, built by Plan 6 Task 12) | interactive session %s ended with exit %d after %s | approved | |
| +| RFS-6-C50 | internal/host/interactive.go (`carlos logs`, sessionEndedLine, built by Plan 6 Task 12) | interactive session %s ended after %s: %s | approved | |
| +| RFS-6-C51 | internal/host/interactive.go (`carlos logs` reason, sessionEndWords, built by Plan 6 Task 12) | 30 minutes passed without a keystroke | approved | |
| +| RFS-6-C52 | internal/host/interactive.go (`carlos logs` reason, sessionEndWords, built by Plan 6 Task 12) | it reached its 6 hour limit | approved | |
| +| RFS-6-C53 | internal/host/interactive.go (`carlos logs` reason, sessionEndWords, built by Plan 6 Task 12) | the person's connection closed | approved | |
| +| RFS-6-C54 | internal/host/interactive.go (`carlos logs` reason, sessionEndWords, built by Plan 6 Task 12) | the box lost its connection to the console | approved | |
| +| RFS-6-C55 | internal/host/interactive.go (`carlos logs`, sessionEndedLine, built by Plan 6 Task 12) | interactive session %s did not start: %s | approved | |
| +| RFS-6-C56 | internal/host/interactive.go (`carlos logs` refusal, sessionRefusedWords, built by Plan 6 Task 12) | interactive sessions are off for this app | approved | |
| +| RFS-6-C57 | internal/host/interactive.go (`carlos logs` refusal, sessionRefusedWords, built by Plan 6 Task 12) | the box was still closing the last session | approved | |
| | RFS-6-C58 | `cli.md`, `### carlos run` | With -it, the command runs in a terminal session instead: what you type goes to it and its screen comes back, so a REPL or a shell works. The app must allow it first, with carlos apps set <app> --interactive on, which only an owner can do. A session ends when the command exits, after 30 minutes without a keystroke, after 6 hours, or soon after your connection drops. A deploy, a restart or a move of the instance ends it too. Ctrl-C and Ctrl-D go to the command. One session at a time per instance, beside any run. Who opened it, where, when it ended and how are in the audit log. What you type and what it prints are not kept. | approved | |
| | RFS-6-C59 | `cli.md`, `### carlos console` | Opens the console process your app's manifest declares, in a terminal session, as carlos run -it would. carlos ship fills one in for Rails, Laravel and Django apps when the manifest has none. An app without one is refused, and the message says how to name a command instead. | approved | |
| | RFS-6-C60 | `cli.md`, `carlos apps set` | --interactive on lets any member open a terminal session on the app's instances with carlos run -it or carlos console. A session can read and change everything the instance can, so it is off until an owner turns it on. Any member can turn it off. | approved | |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 36e0310a2..354cc1043 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -3176,6 +3176,17 @@ func (a *Service) Owns(host string) bool { |
| return a.entries[host] != nil |
| } |
| +// HoldsAwake reports whether host's entry is this box's, awake, and holds |
| +// its lease, with no fence and no shutdown: the gate's ownership check |
| +// (ownedLocked(e, false) == nil). The box's session worker asks it for a |
| +// region-HA route (rootfs apps Plan 6 Task 12, PF-15), where every region |
| +// peer owns the row and only the holder may take the session. Read only. |
| +func (a *Service) HoldsAwake(host string) bool { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return a.ownedLocked(a.entries[host], false) == nil |
| +} |
| + |
| // IdleWindow is cfg.Idle, for the box-side reporters that must tell a member |
| // whether their schedule is tight enough to hold the instance resident. Read |
| // only; the window is fixed at construction from CARLOS_HIBERNATE_IDLE. |
diff --git a/internal/activator/cmd_test.go b/internal/activator/cmd_test.go| index 9f954038a..17e26ab4f 100644 |
| --- a/internal/activator/cmd_test.go |
| +++ b/internal/activator/cmd_test.go |
| @@ -1389,3 +1389,70 @@ func TestTheSweepRetriesAnAttachedSessionsFailedSettle(t *testing.T) { |
| } |
| ses.Release() |
| } |
| + |
| +// HoldsAwake is the region-HA rule's predicate for the box's session worker |
| +// (rootfs apps Plan 6 Task 12, PF-15): the host's entry is this box's, |
| +// awake, holding its lease, with no fence and no shutdown |
| +// (ownedLocked(e, false) == nil). Anything else, and no entry at all, is |
| +// false. |
| +func TestHoldsAwake(t *testing.T) { |
| + a, cb, _ := testCmdActivator(t, Config{}) |
| + rt := testRoute("c.example.com") |
| + if a.HoldsAwake(rt.Host) { |
| + t.Fatal("no entry: held") |
| + } |
| + h, err := a.RunCmd(context.Background(), rt, sessionSpec("tty_a")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Release() |
| + if !a.HoldsAwake(rt.Host) { |
| + t.Fatal("an awake owned entry is not held") |
| + } |
| + if a.HoldsAwake("other.example.com") { |
| + t.Fatal("another host is held") |
| + } |
| + set := func(f func(e *actEntry)) { |
| + a.mu.Lock() |
| + f(a.entries[rt.Host]) |
| + a.mu.Unlock() |
| + } |
| + for _, c := range []struct { |
| + name string |
| + break_, fix func(e *actEntry) |
| + }{ |
| + {"waking", func(e *actEntry) { e.state = actWaking }, func(e *actEntry) { e.state = actAwake }}, |
| + {"stopping", func(e *actEntry) { e.state = actStopping }, func(e *actEntry) { e.state = actAwake }}, |
| + {"fenced", func(e *actEntry) { |
| + if a.fences == nil { |
| + a.fences = map[string]uint64{} |
| + } |
| + a.fences[e.host] = 1 |
| + }, func(e *actEntry) { delete(a.fences, e.host) }}, |
| + {"shutting down", func(*actEntry) { a.shuttingDown = true }, func(*actEntry) { a.shuttingDown = false }}, |
| + } { |
| + set(c.break_) |
| + if a.HoldsAwake(rt.Host) { |
| + t.Errorf("%s: held", c.name) |
| + } |
| + set(c.fix) |
| + if !a.HoldsAwake(rt.Host) { |
| + t.Fatalf("%s: the control is not held", c.name) |
| + } |
| + } |
| + cb.lastRep().setErr(errors.New("lease lost")) |
| + if a.HoldsAwake(rt.Host) { |
| + t.Error("a lost lease: held") |
| + } |
| + cb.lastRep().setErr(nil) |
| + a.mu.Lock() |
| + e := a.entries[rt.Host] |
| + delete(a.entries, rt.Host) |
| + a.mu.Unlock() |
| + if a.HoldsAwake(rt.Host) { |
| + t.Error("asleep (no entry): held") |
| + } |
| + a.mu.Lock() |
| + a.entries[rt.Host] = e |
| + a.mu.Unlock() |
| +} |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 8d2a63fb4..d343144b3 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -693,6 +693,10 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| // stopped a previous agent's leftover units, the cmd units |
| // among them. |
| armRunsPass(svc, reg, dd, rolloutSink, boxJudge) |
| + // Interactive sessions' worker (rootfs apps Plan 6 Task 12), |
| + // beside the runs worker and for the same reasons: its |
| + // passes ride the same loops, after the startup latch. |
| + armInteractivePass(svc, reg, rolloutSink, boxJudge) |
| // The db-reads loop (db region forward spec §7.1): armed |
| // only on a box that can serve; it takes nothing until a |
| // console asks. |
| @@ -1873,6 +1877,9 @@ func reconcileSerializedAuth(ctx context.Context, s release.Store, reg *registry |
| // Runs ride this pass's record reads (run spec §5.2): the worker notes |
| // every in-scope record with a run, and acts after the pass. |
| cfg = withRunsHook(cfg) |
| + // Sessions ride them too (rootfs apps Plan 6 Task 12): the worker notes |
| + // every in-scope record with a session marker. |
| + cfg = withInteractiveHook(cfg) |
| var rep provision.ReconcileReport |
| instances := cfg |
| instances.Report = &rep |
| @@ -3907,6 +3914,7 @@ func instancesLoop(reg *registry.Registry, writes hostwrite.Config, bs *buildSta |
| plansPass(ctx, store, reg, os.Getenv) |
| runMovesPass(ctx, store) |
| runRunsPass(ctx) |
| + runInteractivePass(ctx) |
| if err := aliasPassReporting(ctx, store, reg, &aliasClaimCache, boxAssetAuthority, cfg.Region); err != nil { |
| log.Printf("agent: instances alias pass: %v", err) |
| } |
diff --git a/internal/host/changeindex.go b/internal/host/changeindex.go| index f3c92fa8b..94a8a5b30 100644 |
| --- a/internal/host/changeindex.go |
| +++ b/internal/host/changeindex.go |
| @@ -311,6 +311,8 @@ func (l *passLegs) run(ctx context.Context, what string, keep func(registry.Rout |
| mark("moves") |
| runRunsPass(ctx) |
| mark("runs") |
| + runInteractivePass(ctx) |
| + mark("interactive") |
| // A serial move may be a forwarded db read: list the queue now. The |
| // scoped pass nudges too: a request written through an indexed store |
| // may move only the index. The nudge is a non-blocking channel send. |
diff --git a/internal/host/interactive.go b/internal/host/interactive.go| new file mode 100644 |
| index 000000000..caab53a2e |
| --- /dev/null |
| +++ b/internal/host/interactive.go |
| @@ -0,0 +1,928 @@ |
| +package host |
| + |
| +// The box's session worker (rootfs apps spec §5.10/C9, Plan 6 Task 12). The |
| +// console admits a session by writing a marker on the instance's record and |
| +// a signed grant under the app's subtree (Task 10). Reconcile hands this |
| +// worker every in-scope record that carries a marker (InteractiveSeen, the |
| +// same trigger as the runs worker: the change index and the reconcile pass |
| +// the box already runs, nothing polled of its own). For a marker on a row |
| +// this box owns, the worker reads and verifies the grant, dials the |
| +// console's box door (Task 11), reads the session's Open, starts the tty |
| +// unit through the activator (RunCmd with spec.TTY, Tasks 8 and 9) and |
| +// relays frames between the door and the pty until the session ends. |
| +// |
| +// REQUESTS: one grant GET and one config.json GET (the app's setting) per |
| +// session on the owning box, and nothing on any other box: it ignores the |
| +// marker before reading anything. The worker reads no record of its own |
| +// (the marker reached it on reconcile's judged read) and never writes the |
| +// bucket: the console clears the marker and deletes the grant. |
| +// |
| +// REFUSALS start nothing and dial nothing: a row this box does not own; for |
| +// an HA route, a host this box does not hold awake (PF-15: every region |
| +// peer owns a born-HA row, and only the holder may take the session); a |
| +// malformed id; a grant that is missing, forged, expired, or names another |
| +// session, account, app or host. After the dial, a door refusal starts |
| +// nothing; another incarnation, the setting off, an uncommitted import and |
| +// the activator's refusals are an End refused over the connection. |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "golang.org/x/net/websocket" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/interactive" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/runs" |
| +) |
| + |
| +const ( |
| + // sessionReadMax bounds one read of the pty master, so one Data frame. |
| + sessionReadMax = 32 << 10 |
| + // sessionDrain is how long a session whose command is done waits for |
| + // the master's EIO, which comes once its last output has been read, |
| + // before the unit is stopped and the master closed. A unit that never |
| + // took its terminal leaves the agent's copy of the slave open, so no |
| + // EIO comes before the stop. |
| + sessionDrain = 2 * time.Second |
| + // sessionInputQueue is how many Data and Resize frames wait for the |
| + // terminal while the unit starts; past it the reader waits too. |
| + sessionInputQueue = 64 |
| +) |
| + |
| +// errSessionReplaced is the cause a newer session for the same host ends |
| +// an older one with. |
| +var errSessionReplaced = errors.New("host: a newer session replaced this one") |
| + |
| +// interactiveWorker is the box's half of interactive sessions. |
| +type interactiveWorker struct { |
| + store release.Store |
| + routes func(host string) (*registry.Route, error) |
| + launch runLauncher |
| + pub ed25519.PublicKey |
| + box string |
| + // fleet is the box's fleet credential, the tunnel's name and token, |
| + // when both are set (fleetCredential): the box door wants it for an |
| + // instance placed on a fleet. |
| + fleet func() (name, token string, ok bool) |
| + allowed func(ctx context.Context, acct, app string) (bool, error) |
| + dial func(ctx context.Context, url, origin string, h http.Header) (*websocket.Conn, error) |
| + // events is where a session's lines reach `carlos logs`; nil on a box |
| + // with no log store. |
| + events activator.EventSink |
| + now func() time.Time |
| + // idle, max and grace are interactive.IdleTimeout, MaxDuration and |
| + // HangupGrace; alive, lost and openWait are KeepaliveEvery, |
| + // KeepaliveLost and OpenWait; drain is sessionDrain. Tests shorten them. |
| + idle, max, grace time.Duration |
| + alive, lost, openWait time.Duration |
| + drain time.Duration |
| + // holds is svc.HoldsAwake, consulted only for an HA route (PF-15). |
| + holds func(host string) bool |
| + // judge is the box's lifetime judge (newBoxJudge): every pass runs |
| + // under provision.WithLifetimes of it. The worker reads no record |
| + // itself; the records it acts on come from reconcile's judged read. |
| + // Nil on a claims-on box. |
| + judge *provision.LifetimeJudge |
| + // startFailed is activator.TTYStartFailed: a unit that ended without |
| + // ever taking its terminal. A test replaces it. |
| + startFailed func(activator.Terminal, instancectl.CmdStatus) bool |
| + // start runs a session on its own goroutine. |
| + start func(func()) |
| + |
| + mu sync.Mutex |
| + noted map[string]provision.Record // host -> the record reconcile read |
| + seen map[string]time.Time // session id -> when it may be forgotten |
| + logged map[string]bool // ids whose grant read failed, logged once |
| + active map[string]*sessionRun // host -> the session this worker runs |
| +} |
| + |
| +func newInteractiveWorker(store release.Store, routes func(string) (*registry.Route, error), launch runLauncher, pub ed25519.PublicKey, box string) *interactiveWorker { |
| + return &interactiveWorker{store: store, routes: routes, launch: launch, pub: pub, box: box, |
| + fleet: func() (string, string, bool) { return "", "", false }, |
| + allowed: func(ctx context.Context, acct, app string) (bool, error) { |
| + // The default bundle's setting (carried from Task 4). |
| + return appconfig.GetInteractive(ctx, store, acct, app) |
| + }, |
| + dial: interactive.Dial, |
| + now: time.Now, |
| + idle: interactive.IdleTimeout, max: interactive.MaxDuration, grace: interactive.HangupGrace, |
| + alive: interactive.KeepaliveEvery, lost: interactive.KeepaliveLost, openWait: interactive.OpenWait, |
| + drain: sessionDrain, startFailed: activator.TTYStartFailed, |
| + start: func(f func()) { go f() }, |
| + noted: map[string]provision.Record{}, seen: map[string]time.Time{}, logged: map[string]bool{}, |
| + active: map[string]*sessionRun{}} |
| +} |
| + |
| +// fleetCredential is the box's fleet credential from its environment: |
| +// CARLOS_TUNNEL_NAME and CARLOS_TUNNEL_TOKEN, both set. |
| +func fleetCredential(getenv func(string) string) func() (string, string, bool) { |
| + return func() (string, string, bool) { |
| + name, token := strings.TrimSpace(getenv("CARLOS_TUNNEL_NAME")), strings.TrimSpace(getenv("CARLOS_TUNNEL_TOKEN")) |
| + return name, token, name != "" && token != "" |
| + } |
| +} |
| + |
| +// armedInteractive is the worker the agent armed; nil until then. |
| +var armedInteractive atomic.Pointer[interactiveWorker] |
| + |
| +// note is ReconcileConfig.InteractiveSeen: remember, never act, never block. |
| +func (w *interactiveWorker) note(rec provision.Record) { |
| + w.mu.Lock() |
| + w.noted[rec.Host] = rec |
| + w.mu.Unlock() |
| +} |
| + |
| +// pass acts on every record noted since the last pass. |
| +func (w *interactiveWorker) pass(ctx context.Context) { |
| + ctx = provision.WithLifetimes(ctx, w.judge) |
| + now := w.now() |
| + w.mu.Lock() |
| + noted := w.noted |
| + w.noted = map[string]provision.Record{} |
| + for id, until := range w.seen { |
| + if now.After(until) { |
| + delete(w.seen, id) |
| + delete(w.logged, id) |
| + } |
| + } |
| + w.mu.Unlock() |
| + for _, rec := range noted { |
| + w.consider(ctx, rec) |
| + } |
| +} |
| + |
| +// seenFor is how long an id stays seen after its pickup: past it, a grant |
| +// would be refused as expired anyway (VerifyGrant allows MaxGrantSkew). |
| +const seenFor = 2 * interactive.MaxGrantSkew |
| + |
| +func (w *interactiveWorker) isSeen(id string) bool { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + _, ok := w.seen[id] |
| + return ok |
| +} |
| + |
| +// markSeen records id as handled: it is never read or dialed again while |
| +// remembered. |
| +func (w *interactiveWorker) markSeen(id string, pickupBy time.Time) { |
| + w.mu.Lock() |
| + w.seen[id] = pickupBy.Add(seenFor) |
| + w.mu.Unlock() |
| +} |
| + |
| +// firstLog reports whether this is the first failure logged for id. |
| +func (w *interactiveWorker) firstLog(id string) bool { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + if w.logged[id] { |
| + return false |
| + } |
| + w.logged[id] = true |
| + return true |
| +} |
| + |
| +// owned is the row this box runs the record's instance from, by the runs |
| +// worker's rule: provisioned for the record's account and app, and one the |
| +// activator manages. |
| +func (w *interactiveWorker) owned(rec provision.Record) (registry.Route, bool) { |
| + rt, err := w.routes(rec.Host) |
| + if err != nil || rt == nil || !rt.Provisioned || rt.Account != rec.Account || rt.App != rec.App || !activator.ActivatorManaged(*rt) { |
| + return registry.Route{}, false |
| + } |
| + return *rt, true |
| +} |
| + |
| +// consider decides one record's session, in order: owned (and for an HA |
| +// route, held awake), not seen, a well-formed id, a grant that verifies and |
| +// names this record's session before its pickup. Then the session runs on |
| +// its own goroutine. |
| +func (w *interactiveWorker) consider(ctx context.Context, rec provision.Record) { |
| + m := rec.Interactive |
| + if m == nil { |
| + return |
| + } |
| + rt, ok := w.owned(rec) |
| + if !ok { |
| + return |
| + } |
| + if rt.HA && (w.holds == nil || !w.holds(rec.Host)) { |
| + // A region peer that does not hold the host: not this box's |
| + // session. No request, no dial, no log line. |
| + return |
| + } |
| + id := m.ID |
| + if w.isSeen(id) { |
| + return |
| + } |
| + if !interactive.ValidID(id) { |
| + // Never a store key (carried from Task 3). |
| + w.markSeen(id, m.PickupBy) |
| + log.Printf("agent: interactive: %s: the record names a malformed session id %q; ignored", rec.Host, id) |
| + return |
| + } |
| + if !w.now().Before(m.PickupBy) { |
| + return |
| + } |
| + rctx, cancel := context.WithTimeout(ctx, runReadBound) |
| + wire, _, err := w.store.Get(rctx, interactive.GrantKey(rec.Account, rec.App, id)) |
| + cancel() |
| + if err != nil { |
| + if errors.Is(err, os.ErrNotExist) { |
| + w.markSeen(id, m.PickupBy) |
| + log.Printf("agent: interactive: %s %s: no grant; ignored", rec.Host, id) |
| + } else if w.firstLog(id) { |
| + // A read that failed is tried again on a later pass. |
| + log.Printf("agent: interactive: %s %s: read the grant: %v", rec.Host, id, err) |
| + } |
| + return |
| + } |
| + g, err := interactive.VerifyGrant(w.pub, wire, w.now()) |
| + if err != nil { |
| + w.markSeen(id, m.PickupBy) |
| + log.Printf("agent: interactive: %s %s: the grant did not verify (%v); ignored", rec.Host, id, err) |
| + return |
| + } |
| + if g.ID != id || g.Account != rec.Account || g.App != rec.App || g.Host != rec.Host || !w.now().Before(g.PickupBy) { |
| + w.markSeen(id, m.PickupBy) |
| + log.Printf("agent: interactive: %s %s: the grant names %s/%s/%s %s, not this record's session; ignored", rec.Host, id, g.Account, g.App, g.Host, g.ID) |
| + return |
| + } |
| + w.markSeen(id, g.PickupBy) |
| + s := &sessionRun{w: w, rec: rec, rt: rt, g: g, done: make(chan struct{}), |
| + activity: make(chan struct{}, 1), in: make(chan sessionInput, sessionInputQueue), |
| + readDone: make(chan struct{}), over: make(chan struct{})} |
| + s.ctx, s.cancel = context.WithCancelCause(context.Background()) |
| + w.mu.Lock() |
| + old := w.active[rec.Host] |
| + w.active[rec.Host] = s |
| + w.mu.Unlock() |
| + w.start(func() { s.run(old) }) |
| +} |
| + |
| +// forget drops s from the active set, unless a newer session took its host. |
| +func (w *interactiveWorker) forget(s *sessionRun) { |
| + w.mu.Lock() |
| + if w.active[s.rec.Host] == s { |
| + delete(w.active, s.rec.Host) |
| + } |
| + w.mu.Unlock() |
| +} |
| + |
| +// event publishes one of a session's lines against the record's instance. |
| +func (w *interactiveWorker) event(rec provision.Record, line string) { |
| + if w.events == nil { |
| + return |
| + } |
| + w.events.Event(rec.Account, rec.App, rec.Host, runEventLevel, line) |
| +} |
| + |
| +// sessionInput is one frame for the terminal: data, or a resize. |
| +type sessionInput struct { |
| + data []byte |
| + resize bool |
| + cols, rows uint16 |
| +} |
| + |
| +// sessionRun is one session on this box, from the dial to its End. |
| +type sessionRun struct { |
| + w *interactiveWorker |
| + rec provision.Record |
| + rt registry.Route |
| + g interactive.Grant |
| + // ctx is cancelled, with errSessionReplaced, by a newer session for |
| + // the host. |
| + ctx context.Context |
| + cancel context.CancelCauseFunc |
| + done chan struct{} |
| + |
| + ws *websocket.Conn |
| + sendMu sync.Mutex |
| + |
| + // The reader's outputs. activity is a keystroke (idle reset); in is |
| + // the terminal's input; readDone closes when the reader stops, with |
| + // peerEnd set first if the console sent an End. over closes when the |
| + // session is ending, so a reader waiting on in gives up. |
| + activity chan struct{} |
| + in chan sessionInput |
| + readDone chan struct{} |
| + peerEnd *interactive.End |
| + over chan struct{} |
| +} |
| + |
| +// run is the session's life. old, the session this worker still ran for |
| +// the host, is ended first, as replaced. |
| +func (s *sessionRun) run(old *sessionRun) { |
| + w := s.w |
| + defer close(s.done) |
| + defer w.forget(s) |
| + if old != nil { |
| + old.cancel(errSessionReplaced) |
| + <-old.done |
| + } |
| + if s.ctx.Err() != nil { |
| + return |
| + } |
| + ws, err := s.dial() |
| + if err != nil { |
| + log.Printf("agent: interactive: %s %s: the console did not take the session: %v", s.rec.Host, s.g.ID, err) |
| + return |
| + } |
| + s.ws = ws |
| + open, err := s.receiveOpen() |
| + if err != nil { |
| + ws.Close() |
| + log.Printf("agent: interactive: %s %s: no session to open: %v", s.rec.Host, s.g.ID, err) |
| + return |
| + } |
| + go s.read() |
| + end, started := interactive.End{Reason: interactive.EndReplaced}, false |
| + if s.ctx.Err() == nil { |
| + // Not replaced while it waited for the Open. |
| + end, started = s.serve(open) |
| + } |
| + end.Box = w.box |
| + if end.Ended.IsZero() { |
| + end.Ended = w.now().UTC() |
| + } |
| + _ = s.sendJSON(interactive.KindEnd, end) |
| + // The End is the last frame: the connection closes, and with it the |
| + // reader. |
| + ws.Close() |
| + <-s.readDone |
| + w.event(s.rec, sessionEndedLine(s.g.ID, end)) |
| + log.Printf("agent: interactive: %s: session %s ended: %s (started %v)", s.rec.Host, s.g.ID, end.Reason, started) |
| +} |
| + |
| +// dial opens the box door the grant names, with the session's token, the |
| +// box's label and, on a fleet box, the fleet credential. |
| +func (s *sessionRun) dial() (*websocket.Conn, error) { |
| + w := s.w |
| + u, err := url.Parse(s.g.Attach) |
| + if err != nil { |
| + return nil, err |
| + } |
| + wsURL, err := interactive.WebSocketURL(s.g.Attach) |
| + if err != nil { |
| + return nil, err |
| + } |
| + h := http.Header{} |
| + h.Set(interactive.HeaderToken, s.g.Token) |
| + h.Set("X-Carlos-Box", w.box) |
| + if name, token, ok := w.fleet(); ok { |
| + h.Set("Authorization", "Bearer "+token) |
| + h.Set("Carlos-Tunnel-Name", name) |
| + } |
| + ctx, cancel := context.WithTimeout(s.ctx, w.openWait) |
| + defer cancel() |
| + return w.dial(ctx, wsURL, u.Scheme+"://"+u.Host, h) |
| +} |
| + |
| +// receiveOpen reads the console's first frame within OpenWait: the |
| +// session's Open, normalized and checked. |
| +func (s *sessionRun) receiveOpen() (interactive.Open, error) { |
| + _ = s.ws.SetReadDeadline(time.Now().Add(s.w.openWait)) |
| + kind, payload, err := interactive.Receive(s.ws) |
| + if err != nil { |
| + return interactive.Open{}, err |
| + } |
| + if kind != interactive.KindOpen { |
| + return interactive.Open{}, fmt.Errorf("first frame %q, not an open", kind) |
| + } |
| + var o interactive.Open |
| + if err := json.Unmarshal(payload, &o); err != nil { |
| + return interactive.Open{}, err |
| + } |
| + o = o.Normalized() |
| + if err := o.Check(); err != nil { |
| + return interactive.Open{}, err |
| + } |
| + return o, nil |
| +} |
| + |
| +// read is the connection's only reader (carried from Task 2) for the rest |
| +// of the session: Data and Resize go to in, a keystroke to activity, a |
| +// keepalive only refreshes the deadline, and an End from the console is |
| +// kept in peerEnd. Any error ends the connection. |
| +func (s *sessionRun) read() { |
| + defer close(s.readDone) |
| + for { |
| + _ = s.ws.SetReadDeadline(time.Now().Add(s.w.lost)) |
| + kind, payload, err := interactive.Receive(s.ws) |
| + if err != nil { |
| + s.ws.Close() |
| + return |
| + } |
| + var in sessionInput |
| + switch kind { |
| + case interactive.KindData: |
| + select { |
| + case s.activity <- struct{}{}: |
| + default: |
| + } |
| + in = sessionInput{data: payload} |
| + case interactive.KindResize: |
| + cols, rows, ok := interactive.ParseResize(payload) |
| + if !ok { |
| + continue |
| + } |
| + in = sessionInput{resize: true, cols: cols, rows: rows} |
| + case interactive.KindEnd: |
| + var e interactive.End |
| + if json.Unmarshal(payload, &e) != nil || e.Reason == "" { |
| + e = interactive.End{Reason: interactive.EndHangup} |
| + } |
| + s.peerEnd = &e |
| + return |
| + default: |
| + continue |
| + } |
| + select { |
| + case s.in <- in: |
| + case <-s.over: |
| + return |
| + } |
| + } |
| +} |
| + |
| +// send writes one frame, one writer at a time, bounded by KeepaliveLost. A |
| +// failed write ends the connection, so the reader stops too. |
| +func (s *sessionRun) send(kind byte, payload []byte) error { |
| + s.sendMu.Lock() |
| + defer s.sendMu.Unlock() |
| + _ = s.ws.SetWriteDeadline(time.Now().Add(s.w.lost)) |
| + err := interactive.Send(s.ws, kind, payload) |
| + if err != nil { |
| + s.ws.Close() |
| + } |
| + return err |
| +} |
| + |
| +func (s *sessionRun) sendJSON(kind byte, v any) error { |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + return err |
| + } |
| + return s.send(kind, b) |
| +} |
| + |
| +// keepalive sends KindAlive every KeepaliveEvery until stop closes. |
| +func (s *sessionRun) keepalive(stop <-chan struct{}, done chan<- struct{}) { |
| + defer close(done) |
| + t := time.NewTicker(s.w.alive) |
| + defer t.Stop() |
| + for { |
| + select { |
| + case <-stop: |
| + return |
| + case <-t.C: |
| + if s.send(interactive.KindAlive, nil) != nil { |
| + return |
| + } |
| + } |
| + } |
| +} |
| + |
| +// peerGone is the End for a session whose console side went: the |
| +// console's own End if it sent one, else lost. A newer session's |
| +// replacement comes first. |
| +func (s *sessionRun) peerGone() interactive.End { |
| + if errors.Is(context.Cause(s.ctx), errSessionReplaced) { |
| + return interactive.End{Reason: interactive.EndReplaced} |
| + } |
| + select { |
| + case <-s.readDone: |
| + if e := s.peerEnd; e != nil { |
| + return interactive.End{Reason: e.Reason} |
| + } |
| + default: |
| + } |
| + return interactive.End{Reason: interactive.EndLost} |
| +} |
| + |
| +func refusedEnd(code, detail string) interactive.End { |
| + return interactive.End{Reason: interactive.EndRefused, Refused: code, Detail: detail} |
| +} |
| + |
| +// launchEnd maps RunCmd's refusals to the session's End: claim, flat, wake |
| +// (with its member-safe reason), busy; a stop that beat the start is an |
| +// interruption with its reason; anything else is the box failing to start |
| +// the command. |
| +func launchEnd(err error) interactive.End { |
| + var we *activator.CmdWakeError |
| + var se *activator.CmdStoppedError |
| + switch { |
| + case errors.Is(err, activator.ErrCmdClaim): |
| + return refusedEnd(runs.RefusedClaim, "") |
| + case errors.Is(err, activator.ErrCmdNotNested), errors.Is(err, activator.ErrCmdNotInstance): |
| + return refusedEnd(runs.RefusedFlat, "") |
| + case errors.As(err, &we): |
| + return refusedEnd(runs.RefusedWake, we.Reason) |
| + case errors.Is(err, activator.ErrTTYBusy): |
| + return refusedEnd(interactive.RefusedBusy, "") |
| + case errors.As(err, &se): |
| + return interactive.End{Reason: interactive.EndInterrupted, Detail: se.Reason} |
| + } |
| + return interactive.End{Reason: interactive.EndInterrupted, Detail: runs.InterruptedStartFailed} |
| +} |
| + |
| +// serve is the session after its Open: the refusals, the start, the bridge |
| +// and the ending. It returns the End to send and whether the command |
| +// started. Every frame it sends is sent before it returns, so the End |
| +// follows the last output. |
| +func (s *sessionRun) serve(open interactive.Open) (interactive.End, bool) { |
| + w := s.w |
| + defer close(s.over) |
| + stopAlive, aliveDone := make(chan struct{}), make(chan struct{}) |
| + go s.keepalive(stopAlive, aliveDone) |
| + defer func() { |
| + close(stopAlive) |
| + <-aliveDone |
| + }() |
| + |
| + if s.g.Incarnation != recordIncarnation(s.rec) { |
| + return refusedEnd(runs.RefusedIncarnation, ""), false |
| + } |
| + actx, cancel := context.WithTimeout(s.ctx, runReadBound) |
| + on, err := w.allowed(actx, s.rec.Account, s.rec.App) |
| + cancel() |
| + if err != nil { |
| + if s.ctx.Err() != nil { |
| + return s.peerGone(), false |
| + } |
| + log.Printf("agent: interactive: %s %s: read the setting: %v", s.rec.Host, s.g.ID, err) |
| + return interactive.End{Reason: interactive.EndInterrupted, Detail: runs.InterruptedStartFailed}, false |
| + } |
| + if !on { |
| + return refusedEnd(interactive.RefusedOff, ""), false |
| + } |
| + if s.rec.ImportUncommitted() { |
| + return refusedEnd(runs.RefusedImport, ""), false |
| + } |
| + if s.sendJSON(interactive.KindStatus, interactive.Status{State: interactive.StateStarting}) != nil { |
| + return s.peerGone(), false |
| + } |
| + |
| + // The start ends early if the console hangs up, the connection goes or |
| + // a newer session replaces this one. |
| + lctx, lcancel := context.WithCancel(s.ctx) |
| + launched := make(chan struct{}) |
| + go func() { |
| + select { |
| + case <-s.readDone: |
| + lcancel() |
| + case <-launched: |
| + } |
| + }() |
| + spec := activator.CmdSpec{RunID: s.g.ID, Process: open.Process, Args: open.Argv, |
| + TTY: &activator.TTYSpec{Term: open.Term, Cols: uint16(open.Cols), Rows: uint16(open.Rows)}} |
| + handle, err := w.launch.RunCmd(lctx, s.rt, spec) |
| + close(launched) |
| + ended := lctx.Err() != nil |
| + lcancel() |
| + if err != nil { |
| + if ended { |
| + return s.peerGone(), false |
| + } |
| + if e := launchEnd(err); e.Detail == runs.InterruptedStartFailed { |
| + log.Printf("agent: interactive: %s %s: start: %v", s.rec.Host, s.g.ID, err) |
| + } |
| + return launchEnd(err), false |
| + } |
| + started := w.now().UTC() |
| + log.Printf("agent: interactive: %s: session %s started (%s)", s.rec.Host, s.g.ID, handle.Invocation()) |
| + w.event(s.rec, sessionStartedLine(s.g.ID, s.g.By)) |
| + _ = s.sendJSON(interactive.KindStatus, interactive.Status{State: interactive.StateStarted}) |
| + end := s.bridge(handle) |
| + end.Started = started |
| + return end, true |
| +} |
| + |
| +// bridge relays between the connection and the session's terminal until |
| +// the session ends, then stops the unit and releases it. |
| +func (s *sessionRun) bridge(handle activator.CmdHandle) interactive.End { |
| + w := s.w |
| + term := handle.Terminal() |
| + // The pump: master to Data frames. It ends at the master's EIO, or |
| + // once the master is closed. |
| + pumpDone := make(chan struct{}) |
| + go func() { |
| + defer close(pumpDone) |
| + if term == nil { |
| + return |
| + } |
| + buf := make([]byte, sessionReadMax) |
| + failed := false |
| + for { |
| + n, err := term.Read(buf) |
| + if n > 0 && !failed && s.send(interactive.KindData, buf[:n]) != nil { |
| + // The connection is gone; keep draining so the tenant's |
| + // command is not blocked on a full pty. |
| + failed = true |
| + } |
| + if err != nil { |
| + return |
| + } |
| + } |
| + }() |
| + // The feed: Data and Resize frames to the terminal. |
| + stopFeed, feedDone := make(chan struct{}), make(chan struct{}) |
| + go func() { |
| + defer close(feedDone) |
| + for { |
| + select { |
| + case <-stopFeed: |
| + return |
| + case in := <-s.in: |
| + if term == nil { |
| + continue |
| + } |
| + if in.resize { |
| + _ = term.Resize(in.cols, in.rows) |
| + } else if _, err := term.Write(in.data); err != nil { |
| + return |
| + } |
| + } |
| + } |
| + }() |
| + |
| + type polled struct { |
| + st instancectl.CmdStatus |
| + at time.Time |
| + } |
| + pctx, stopPolling := context.WithCancel(context.Background()) |
| + defer stopPolling() |
| + statuses := make(chan polled, 1) |
| + go func() { |
| + for { |
| + st, err := handle.Poll(pctx) |
| + if pctx.Err() != nil { |
| + return |
| + } |
| + if err != nil { |
| + select { |
| + case <-pctx.Done(): |
| + return |
| + case <-time.After(runPollRetry): |
| + } |
| + continue |
| + } |
| + if st.State != instancectl.CmdRunning { |
| + statuses <- polled{st, w.now()} |
| + return |
| + } |
| + } |
| + }() |
| + |
| + sctx, cancel := context.WithTimeout(context.Background(), runStopBound) |
| + defer cancel() |
| + stopped := false |
| + stop := func() { |
| + if stopped { |
| + return |
| + } |
| + stopped = true |
| + if err := handle.Stop(sctx); err != nil { |
| + log.Printf("agent: interactive: %s %s: stop: %v", s.rec.Host, s.g.ID, err) |
| + } |
| + } |
| + // finish stops the unit, closes the terminal and joins the pump and the |
| + // feed, so no frame follows the End and the handoff is settled. |
| + finish := func() { |
| + stop() |
| + if term != nil { |
| + _ = term.Hangup() |
| + } |
| + close(stopFeed) |
| + <-pumpDone |
| + <-feedDone |
| + } |
| + defer handle.Release() |
| + |
| + idle := time.NewTimer(w.idle) |
| + defer idle.Stop() |
| + limit := time.NewTimer(w.max) |
| + defer limit.Stop() |
| + interrupts := time.NewTicker(runInterruptEvery) |
| + defer interrupts.Stop() |
| + |
| + var hangup *interactive.End |
| + var done *polled |
| +wait: |
| + for { |
| + select { |
| + case <-s.activity: |
| + if !idle.Stop() { |
| + select { |
| + case <-idle.C: |
| + default: |
| + } |
| + } |
| + idle.Reset(w.idle) |
| + case p := <-statuses: |
| + done = &p |
| + break wait |
| + case <-idle.C: |
| + hangup = &interactive.End{Reason: interactive.EndIdle} |
| + break wait |
| + case <-limit.C: |
| + hangup = &interactive.End{Reason: interactive.EndLimit} |
| + break wait |
| + case <-s.readDone: |
| + e := s.peerGone() |
| + hangup = &e |
| + break wait |
| + case <-s.ctx.Done(): |
| + e := s.peerGone() |
| + hangup = &e |
| + break wait |
| + case <-interrupts.C: |
| + // An interruption: the activator is stopping the unit. Its done |
| + // status, if it comes within the grace, still decides. |
| + if reason, _ := handle.Interrupted(); reason != "" { |
| + grace := time.NewTimer(runInterruptGrace) |
| + select { |
| + case p := <-statuses: |
| + done = &p |
| + case <-grace.C: |
| + } |
| + grace.Stop() |
| + break wait |
| + } |
| + } |
| + } |
| + |
| + if hangup != nil { |
| + // Hang up: SIGHUP to the tenant's session. A unit not done within |
| + // the grace is stopped. |
| + if term != nil { |
| + _ = term.Hangup() |
| + } |
| + grace := time.NewTimer(w.grace) |
| + select { |
| + case <-statuses: |
| + case <-grace.C: |
| + stop() |
| + } |
| + grace.Stop() |
| + finish() |
| + return *hangup |
| + } |
| + |
| + if done != nil { |
| + // The command is done: its output drains to the master's EIO, then |
| + // the unit is stopped. |
| + drain := time.NewTimer(w.drain) |
| + select { |
| + case <-pumpDone: |
| + case <-drain.C: |
| + } |
| + drain.Stop() |
| + } |
| + finish() |
| + // The settle has joined the handoff (Stop closes it), so whether the |
| + // unit ever took its terminal is final. |
| + reason, askedAt := handle.Interrupted() |
| + if reason != "" && done != nil && done.st.State == instancectl.CmdDone && askedAt.After(done.at) { |
| + // Asked for after the command had finished: the exit stands. |
| + reason = "" |
| + } |
| + switch { |
| + case reason != "": |
| + return interactive.End{Reason: interactive.EndInterrupted, Detail: reason} |
| + case done == nil: |
| + return interactive.End{Reason: interactive.EndInterrupted, Detail: runs.InterruptedGone} |
| + case w.startFailed(term, done.st): |
| + return interactive.End{Reason: interactive.EndInterrupted, Detail: runs.InterruptedStartFailed} |
| + case done.st.State == instancectl.CmdGone: |
| + return interactive.End{Reason: interactive.EndInterrupted, Detail: runs.InterruptedGone} |
| + } |
| + exit, signal := exitOf(done.st) |
| + if signal != "" { |
| + // A command ended by a signal exits as a shell reports it. |
| + var n int |
| + fmt.Sscanf(signal, "%d", &n) |
| + exit = 128 + n |
| + } |
| + return interactive.End{Reason: interactive.EndExited, Exit: exit} |
| +} |
| + |
| +// The session's lines in `carlos logs` (RFS-6-C48 to C57), info like a |
| +// run's: who opened it, then how it ended. What was typed and printed is |
| +// never written. |
| + |
| +// sessionStartedLine is RFS-6-C48. |
| +func sessionStartedLine(id, by string) string { |
| + return fmt.Sprintf("interactive session %s opened by %s", id, by) |
| +} |
| + |
| +// sessionEndedLine is how the session ended: RFS-6-C49 for an exit, C50 |
| +// with C51 to C54 or the interruption's reason for an ending after the |
| +// start, and C55 with C56, C57 or the run refusal's words for a session |
| +// that did not start. An unknown reason renders as itself, as the CLI's |
| +// does. |
| +func sessionEndedLine(id string, e interactive.End) string { |
| + took := e.Ended.Sub(e.Started).Round(time.Second) |
| + switch { |
| + case e.Reason == interactive.EndRefused: |
| + return fmt.Sprintf("interactive session %s did not start: %s", id, sessionRefusedWords(e)) |
| + case e.Reason == interactive.EndInterrupted && e.Started.IsZero(): |
| + return fmt.Sprintf("interactive session %s did not start: %s", id, e.Detail) |
| + case e.Reason == interactive.EndExited: |
| + return fmt.Sprintf("interactive session %s ended with exit %d after %s", id, e.Exit, took) |
| + } |
| + if e.Started.IsZero() { |
| + took = 0 |
| + } |
| + return fmt.Sprintf("interactive session %s ended after %s: %s", id, took, sessionEndWords(e)) |
| +} |
| + |
| +// sessionEndWords is why a started session ended (RFS-6-C51 to C54). |
| +func sessionEndWords(e interactive.End) string { |
| + switch e.Reason { |
| + case interactive.EndIdle: |
| + return "30 minutes passed without a keystroke" |
| + case interactive.EndLimit: |
| + return "it reached its 6 hour limit" |
| + case interactive.EndHangup: |
| + return "the person's connection closed" |
| + case interactive.EndLost: |
| + return "the box lost its connection to the console" |
| + case interactive.EndInterrupted: |
| + return e.Detail |
| + } |
| + return e.Reason |
| +} |
| + |
| +// sessionRefusedWords is why the box did not start the session (RFS-6-C56, |
| +// C57, and the run refusals' words). |
| +func sessionRefusedWords(e interactive.End) string { |
| + switch e.Refused { |
| + case interactive.RefusedOff: |
| + return "interactive sessions are off for this app" |
| + case interactive.RefusedBusy: |
| + return "the box was still closing the last session" |
| + } |
| + return runRefusedWords(runs.Result{Refused: e.Refused, Detail: e.Detail}) |
| +} |
| + |
| +// armInteractivePass arms the session worker on a box with an activator, a |
| +// registry, a store and a parseable CARLOS_RELEASE_PUBKEY, beside the runs |
| +// worker; otherwise it says why, once. events must be a genuinely nil |
| +// interface when there is no log store, never a nil *applog.Sink. judge is |
| +// the box's (newBoxJudge); nil on a claims-on box. |
| +func armInteractivePass(svc *activator.Service, reg *registry.Registry, events activator.EventSink, judge *provision.LifetimeJudge) { |
| + disabled := func(why any) { log.Printf("agent: interactive sessions disabled: %v", why) } |
| + if svc == nil || reg == nil { |
| + disabled("no activator or no registry") |
| + return |
| + } |
| + store, err := openDeployStore(context.Background()) |
| + if err != nil { |
| + disabled(err) |
| + return |
| + } |
| + pub, err := release.ParsePublicKey(os.Getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY") |
| + if err != nil { |
| + disabled(err) |
| + return |
| + } |
| + w := newInteractiveWorker(store, reg.Get, svc, pub, BoxLabel()) |
| + w.holds = svc.HoldsAwake |
| + w.fleet = fleetCredential(os.Getenv) |
| + w.events = events |
| + w.judge = judge |
| + armedInteractive.Store(w) |
| + log.Printf("agent: interactive sessions armed (box %s)", w.box) |
| +} |
| + |
| +// withInteractiveHook gives reconcile the worker's note. |
| +func withInteractiveHook(cfg provision.ReconcileConfig) provision.ReconcileConfig { |
| + if w := armedInteractive.Load(); w != nil && cfg.InteractiveSeen == nil { |
| + cfg.InteractiveSeen = w.note |
| + } |
| + return cfg |
| +} |
| + |
| +// runInteractivePass acts on what the last reconcile pass noted. |
| +func runInteractivePass(ctx context.Context) { |
| + if w := armedInteractive.Load(); w != nil { |
| + w.pass(ctx) |
| + } |
| +} |
diff --git a/internal/host/interactive_e2e_linux_test.go b/internal/host/interactive_e2e_linux_test.go| new file mode 100644 |
| index 000000000..0b188207c |
| --- /dev/null |
| +++ b/internal/host/interactive_e2e_linux_test.go |
| @@ -0,0 +1,234 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/interactive" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// e2ePTY is a real pty: the master is the session's Terminal, as the |
| +// activator's ptyTerminal is. |
| +type e2ePTY struct { |
| + master *os.File |
| + slavePath string |
| + closeOnce sync.Once |
| +} |
| + |
| +func openE2EPTY(t *testing.T) (*e2ePTY, *os.File) { |
| + t.Helper() |
| + const flags = unix.O_RDWR | unix.O_NOCTTY | unix.O_CLOEXEC |
| + mfd, err := unix.Open("/dev/ptmx", flags, 0) |
| + if err != nil { |
| + t.Skipf("no pty here: %v", err) |
| + } |
| + if err := unix.IoctlSetPointerInt(mfd, unix.TIOCSPTLCK, 0); err != nil { |
| + t.Fatal(err) |
| + } |
| + n, err := unix.IoctlGetInt(mfd, unix.TIOCGPTN) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + path := fmt.Sprintf("/dev/pts/%d", n) |
| + sfd, err := unix.Open(path, flags, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := unix.IoctlSetWinsize(mfd, unix.TIOCSWINSZ, &unix.Winsize{Col: 80, Row: 24}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := unix.SetNonblock(mfd, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := &e2ePTY{master: os.NewFile(uintptr(mfd), "/dev/ptmx"), slavePath: path} |
| + t.Cleanup(func() { p.Hangup() }) |
| + return p, os.NewFile(uintptr(sfd), path) |
| +} |
| + |
| +func (p *e2ePTY) Read(b []byte) (int, error) { return p.master.Read(b) } |
| +func (p *e2ePTY) Write(b []byte) (int, error) { return p.master.Write(b) } |
| +func (p *e2ePTY) Resize(cols, rows uint16) error { |
| + conn, err := p.master.SyscallConn() |
| + if err != nil { |
| + return err |
| + } |
| + var ioctlErr error |
| + if err := conn.Control(func(fd uintptr) { |
| + ioctlErr = unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, &unix.Winsize{Col: cols, Row: rows}) |
| + }); err != nil { |
| + return err |
| + } |
| + return ioctlErr |
| +} |
| +func (p *e2ePTY) Hangup() error { |
| + var err error |
| + p.closeOnce.Do(func() { err = p.master.Close() }) |
| + return err |
| +} |
| + |
| +// slaveSize is the window size the slave's TIOCGWINSZ reads. |
| +func (p *e2ePTY) slaveSize() (cols, rows uint16, err error) { |
| + fd, err := unix.Open(p.slavePath, unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return 0, 0, err |
| + } |
| + defer unix.Close(fd) |
| + ws, err := unix.IoctlGetWinsize(fd, unix.TIOCGWINSZ) |
| + if err != nil { |
| + return 0, 0, err |
| + } |
| + return ws.Col, ws.Row, nil |
| +} |
| + |
| +// e2eCat is the session's unit: /bin/cat on the pty's slave, in its own |
| +// session with the slave as its controlling terminal, as the tty unit's |
| +// command is. |
| +type e2eCat struct { |
| + term *e2ePTY |
| + cmd *exec.Cmd |
| + done chan struct{} |
| + status instancectl.CmdStatus |
| + mu sync.Mutex |
| + stopped bool |
| +} |
| + |
| +func (c *e2eCat) Invocation() string { return "inv-e2e" } |
| +func (c *e2eCat) Poll(ctx context.Context) (instancectl.CmdStatus, error) { |
| + select { |
| + case <-c.done: |
| + return c.status, nil |
| + case <-ctx.Done(): |
| + return instancectl.CmdStatus{}, ctx.Err() |
| + case <-time.After(time.Second): |
| + return instancectl.CmdStatus{State: instancectl.CmdRunning}, nil |
| + } |
| +} |
| +func (c *e2eCat) Interrupted() (string, time.Time) { return "", time.Time{} } |
| +func (c *e2eCat) Stop(context.Context) error { |
| + c.mu.Lock() |
| + c.stopped = true |
| + c.mu.Unlock() |
| + _ = c.cmd.Process.Kill() |
| + <-c.done |
| + return c.term.Hangup() |
| +} |
| +func (c *e2eCat) Release() {} |
| +func (c *e2eCat) Terminal() activator.Terminal { return c.term } |
| + |
| +// e2eLaunch starts /bin/cat on a fresh pty for the session it is handed. |
| +type e2eLaunch struct { |
| + t *testing.T |
| + mu sync.Mutex |
| + cat *e2eCat |
| + spec activator.CmdSpec |
| +} |
| + |
| +func (l *e2eLaunch) RunCmd(ctx context.Context, rt registry.Route, spec activator.CmdSpec) (activator.CmdHandle, error) { |
| + term, slave := openE2EPTY(l.t) |
| + defer slave.Close() |
| + cmd := exec.Command("/bin/cat") |
| + cmd.Stdin, cmd.Stdout, cmd.Stderr = slave, slave, slave |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true, Ctty: 0} |
| + if err := cmd.Start(); err != nil { |
| + return nil, err |
| + } |
| + c := &e2eCat{term: term, cmd: cmd, done: make(chan struct{})} |
| + go func() { |
| + err := cmd.Wait() |
| + code := 0 |
| + var ee *exec.ExitError |
| + if errors.As(err, &ee) { |
| + code = ee.ExitCode() |
| + } |
| + c.status = instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: fmt.Sprint(code)} |
| + close(c.done) |
| + }() |
| + l.mu.Lock() |
| + l.cat, l.spec = c, spec |
| + l.mu.Unlock() |
| + return c, nil |
| +} |
| + |
| +func TestInteractiveSessionEndToEnd(t *testing.T) { |
| + if _, err := os.Stat("/bin/cat"); err != nil { |
| + t.Skip("no /bin/cat") |
| + } |
| + c := newIxConsole(t) |
| + cli := c.open(t, interactive.Open{Schema: 1, Argv: []string{"cat"}, Term: "xterm-256color", Cols: 80, Rows: 24}) |
| + rec := c.record(t) |
| + if rec.Interactive == nil { |
| + t.Fatal("the console wrote no marker") |
| + } |
| + launch := &e2eLaunch{t: t} |
| + events := &eventLog{} |
| + w := newInteractiveWorker(c.store, ixRoutes(ixRoute(ixHost)), launch, c.pub, "box-a") |
| + w.events = events |
| + w.note(rec) |
| + w.pass(context.Background()) |
| + if st := cliStatus(t, cli); st != interactive.StateStarting { |
| + t.Fatalf("status %q", st) |
| + } |
| + if st := cliStatus(t, cli); st != interactive.StateStarted { |
| + t.Fatalf("status %q", st) |
| + } |
| + if launch.spec.RunID != rec.Interactive.ID || fmt.Sprint(launch.spec.Args) != "[cat]" || launch.spec.TTY == nil { |
| + t.Fatalf("spec %+v", launch.spec) |
| + } |
| + |
| + if err := interactive.Send(cli, interactive.KindData, []byte("hello\r")); err != nil { |
| + t.Fatal(err) |
| + } |
| + var out strings.Builder |
| + for !strings.Contains(out.String(), "hello\r\nhello") { |
| + kind, p := cliNext(t, cli) |
| + if kind != interactive.KindData { |
| + t.Fatalf("frame %q %s while waiting for the echo; output so far %q", kind, p, out.String()) |
| + } |
| + out.Write(p) |
| + } |
| + |
| + if err := interactive.Send(cli, interactive.KindResize, interactive.ResizePayload(132, 43)); err != nil { |
| + t.Fatal(err) |
| + } |
| + waitFor(t, "the slave to read the new size", func() bool { |
| + cols, rows, err := launch.cat.term.slaveSize() |
| + return err == nil && cols == 132 && rows == 43 |
| + }) |
| + |
| + if err := interactive.Send(cli, interactive.KindData, []byte{0x04}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e := cliEnd(t, cli) |
| + if e.Reason != interactive.EndExited || e.Exit != 0 { |
| + t.Fatalf("end %+v, want exited 0", e) |
| + } |
| + waitFor(t, "the console's end writes", func() bool { |
| + r := c.record(t) |
| + got := strings.Join(c.audit(t), ",") |
| + return r.Interactive == nil && strings.Contains(got, "interactive-start") && strings.Contains(got, "interactive-end") |
| + }) |
| + waitFor(t, "the worker's session to end", func() bool { w.mu.Lock(); defer w.mu.Unlock(); return len(w.active) == 0 }) |
| + if launch.cat.stopped != true { |
| + t.Fatal("the unit was not stopped after the exit") |
| + } |
| + msgs := events.all() |
| + if len(msgs) != 2 || msgs[0].msg != "interactive session "+rec.Interactive.ID+" opened by paul@keymail.dev" || |
| + !strings.HasPrefix(msgs[1].msg, "interactive session "+rec.Interactive.ID+" ended with exit 0 after ") { |
| + t.Fatalf("events %+v", msgs) |
| + } |
| +} |
diff --git a/internal/host/interactive_test.go b/internal/host/interactive_test.go| new file mode 100644 |
| index 000000000..ee4c845b0 |
| --- /dev/null |
| +++ b/internal/host/interactive_test.go |
| @@ -0,0 +1,1723 @@ |
| +package host |
| + |
| +// The box's session worker (rootfs apps Plan 6 Task 12): which records it |
| +// acts on, the grant, the dial, the refusals over the connection, the |
| +// bridge and every ending. The console's box door is a fake here (ixDoor) |
| +// except in TestARestartedWorkerCannotRelaunchAnEndedSession and the linux |
| +// end-to-end test, which run a real console.Server. Account bah, app shop. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "io" |
| + "log" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/net/websocket" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/interactive" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/runs" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +const ixHost = "shop.example.com" |
| + |
| +var ixAcct = domains.Sqid(7) // bah |
| + |
| +// ixRecord is bah's shop instance with a session marker for id. |
| +func ixRecord(id string, pickupBy time.Time) provision.Record { |
| + return provision.Record{Schema: 1, Host: ixHost, Slug: "shop", App: "shop", Account: ixAcct, Region: "uk", Channel: "stable", |
| + CreatedAt: time.Date(2026, 10, 20, 9, 0, 0, 0, time.UTC), |
| + Interactive: &provision.InteractiveState{ID: id, By: "alice@keymail.dev", Console: "boot-1", PickupBy: pickupBy.UTC()}} |
| +} |
| + |
| +func ixRoute(host string) *registry.Route { |
| + return ®istry.Route{Host: host, Kind: "instance", Hibernate: true, Socket: "/run/x.sock", Provisioned: true, App: "shop", Account: ixAcct} |
| +} |
| + |
| +func ixRoutes(rt *registry.Route) func(string) (*registry.Route, error) { |
| + return func(h string) (*registry.Route, error) { |
| + if rt == nil || h != rt.Host { |
| + return nil, nil |
| + } |
| + c := *rt |
| + return &c, nil |
| + } |
| +} |
| + |
| +func ixID(t *testing.T) string { |
| + t.Helper() |
| + id, err := interactive.MintID() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +// ixStore counts every request the worker makes, by verb, and can refuse |
| +// every write. |
| +type ixStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + gets, puts int |
| + deletes int |
| + lists int |
| + keys []string |
| + failWrites bool |
| +} |
| + |
| +func (s *ixStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + s.mu.Lock() |
| + s.gets++ |
| + s.keys = append(s.keys, key) |
| + s.mu.Unlock() |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +func (s *ixStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + s.mu.Lock() |
| + s.puts++ |
| + fail := s.failWrites |
| + s.mu.Unlock() |
| + if fail { |
| + return "", errors.New("ixStore: writes refused") |
| + } |
| + return s.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +func (s *ixStore) Delete(ctx context.Context, key string) error { |
| + s.mu.Lock() |
| + s.deletes++ |
| + fail := s.failWrites |
| + s.mu.Unlock() |
| + if fail { |
| + return errors.New("ixStore: writes refused") |
| + } |
| + return s.Store.Delete(ctx, key) |
| +} |
| + |
| +func (s *ixStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + s.mu.Lock() |
| + s.lists++ |
| + s.mu.Unlock() |
| + return s.Store.List(ctx, prefix) |
| +} |
| + |
| +func (s *ixStore) ListDirs(ctx context.Context, prefix string) ([]string, error) { |
| + s.mu.Lock() |
| + s.lists++ |
| + s.mu.Unlock() |
| + return s.Store.ListDirs(ctx, prefix) |
| +} |
| + |
| +func (s *ixStore) counts() (gets, writes, lists int) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.gets, s.puts + s.deletes, s.lists |
| +} |
| + |
| +func (s *ixStore) reset() { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.gets, s.puts, s.deletes, s.lists, s.keys = 0, 0, 0, 0, nil |
| +} |
| + |
| +// ixTerm is a session's terminal: out is what the tenant's command prints |
| +// (the test writes it), in is what reaches the command. |
| +type ixTerm struct { |
| + outR *io.PipeReader |
| + outW *io.PipeWriter |
| + mu sync.Mutex |
| + in bytes.Buffer |
| + resizes [][2]uint16 |
| + hangups int |
| + closed bool |
| +} |
| + |
| +func newIxTerm() *ixTerm { |
| + r, w := io.Pipe() |
| + return &ixTerm{outR: r, outW: w} |
| +} |
| + |
| +func (t *ixTerm) Read(p []byte) (int, error) { return t.outR.Read(p) } |
| +func (t *ixTerm) Write(p []byte) (int, error) { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + if t.closed { |
| + return 0, io.ErrClosedPipe |
| + } |
| + return t.in.Write(p) |
| +} |
| +func (t *ixTerm) Resize(c, r uint16) error { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + t.resizes = append(t.resizes, [2]uint16{c, r}) |
| + return nil |
| +} |
| +func (t *ixTerm) Hangup() error { |
| + t.mu.Lock() |
| + t.hangups++ |
| + t.mu.Unlock() |
| + t.close() |
| + return nil |
| +} |
| +func (t *ixTerm) close() { |
| + t.mu.Lock() |
| + t.closed = true |
| + t.mu.Unlock() |
| + t.outR.CloseWithError(io.EOF) |
| +} |
| +func (t *ixTerm) input() string { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + return t.in.String() |
| +} |
| +func (t *ixTerm) hungUp() int { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + return t.hangups |
| +} |
| + |
| +// ixHandle is a started session. Poll answers once done is closed. Stop |
| +// closes the terminal and, unless stopLeavesRunning, ends the unit (killed). |
| +type ixHandle struct { |
| + term activator.Terminal |
| + done chan struct{} |
| + doneOnce sync.Once |
| + mu sync.Mutex |
| + status instancectl.CmdStatus |
| + reason string |
| + askedAt time.Time |
| + stops []time.Time |
| + releases int |
| + // events is the order of Stop and Release against the session's other |
| + // calls, for the tests that check it. |
| + events []string |
| +} |
| + |
| +func newIxHandle(term activator.Terminal) *ixHandle { |
| + return &ixHandle{term: term, done: make(chan struct{})} |
| +} |
| + |
| +func (h *ixHandle) finish(st instancectl.CmdStatus) { |
| + h.doneOnce.Do(func() { |
| + h.mu.Lock() |
| + h.status = st |
| + h.mu.Unlock() |
| + close(h.done) |
| + }) |
| +} |
| + |
| +func (h *ixHandle) note(e string) { h.mu.Lock(); h.events = append(h.events, e); h.mu.Unlock() } |
| + |
| +func (h *ixHandle) Invocation() string { return "inv-tty" } |
| +func (h *ixHandle) Poll(ctx context.Context) (instancectl.CmdStatus, error) { |
| + select { |
| + case <-h.done: |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return h.status, nil |
| + case <-ctx.Done(): |
| + return instancectl.CmdStatus{}, ctx.Err() |
| + case <-time.After(200 * time.Millisecond): |
| + return instancectl.CmdStatus{State: instancectl.CmdRunning}, nil |
| + } |
| +} |
| +func (h *ixHandle) Interrupted() (string, time.Time) { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return h.reason, h.askedAt |
| +} |
| +func (h *ixHandle) interrupt(reason string, at time.Time) { |
| + h.mu.Lock() |
| + h.reason, h.askedAt = reason, at |
| + h.mu.Unlock() |
| +} |
| +func (h *ixHandle) Stop(context.Context) error { |
| + h.mu.Lock() |
| + h.stops = append(h.stops, time.Now()) |
| + h.events = append(h.events, "stop") |
| + h.mu.Unlock() |
| + if t, ok := h.term.(*ixTerm); ok { |
| + t.close() |
| + } |
| + h.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "killed", Status: "15"}) |
| + return nil |
| +} |
| +func (h *ixHandle) Release() { |
| + h.mu.Lock() |
| + h.releases++ |
| + h.events = append(h.events, "release") |
| + h.mu.Unlock() |
| +} |
| +func (h *ixHandle) Terminal() activator.Terminal { return h.term } |
| + |
| +func (h *ixHandle) stopped() ([]time.Time, int) { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return append([]time.Time(nil), h.stops...), h.releases |
| +} |
| + |
| +// ixLaunch is the activator: it records each CmdSpec and answers err or |
| +// handle. |
| +type ixLaunch struct { |
| + mu sync.Mutex |
| + specs []activator.CmdSpec |
| + routes []registry.Route |
| + err error |
| + handle *ixHandle |
| + // block, when set, holds RunCmd until ctx ends. |
| + block bool |
| +} |
| + |
| +func (l *ixLaunch) RunCmd(ctx context.Context, rt registry.Route, spec activator.CmdSpec) (activator.CmdHandle, error) { |
| + l.mu.Lock() |
| + l.specs = append(l.specs, spec) |
| + l.routes = append(l.routes, rt) |
| + err, h, block := l.err, l.handle, l.block |
| + l.mu.Unlock() |
| + if block { |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + return h, nil |
| +} |
| + |
| +func (l *ixLaunch) calls() []activator.CmdSpec { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return append([]activator.CmdSpec(nil), l.specs...) |
| +} |
| + |
| +// ixDoor is the console's box door, faked: it records each dial's headers, |
| +// sends open, and hands the connection to script, if any. Frames the box |
| +// sends are on frames until script returns or the connection ends. |
| +type ixDoor struct { |
| + t *testing.T |
| + ts *httptest.Server |
| + mu sync.Mutex |
| + headers []http.Header |
| + refuse int // when set, the door answers this status before the upgrade |
| + open interactive.Open |
| + script func(ws *websocket.Conn) |
| + frames chan ixFrame |
| +} |
| + |
| +type ixFrame struct { |
| + kind byte |
| + payload []byte |
| +} |
| + |
| +func newIxDoor(t *testing.T, open interactive.Open) *ixDoor { |
| + t.Helper() |
| + d := &ixDoor{t: t, open: open, frames: make(chan ixFrame, 256)} |
| + srv := interactive.NewServer(func(ws *websocket.Conn) { |
| + if err := interactive.SendJSON(ws, interactive.KindOpen, d.open); err != nil { |
| + return |
| + } |
| + d.mu.Lock() |
| + script := d.script |
| + d.mu.Unlock() |
| + if script != nil { |
| + script(ws) |
| + return |
| + } |
| + d.collect(ws) |
| + }) |
| + d.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + d.mu.Lock() |
| + d.headers = append(d.headers, r.Header.Clone()) |
| + refuse := d.refuse |
| + d.mu.Unlock() |
| + if refuse != 0 { |
| + http.Error(w, http.StatusText(refuse), refuse) |
| + return |
| + } |
| + if !strings.HasPrefix(r.URL.Path, interactive.AttachPathPrefix) { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + srv.ServeHTTP(w, r) |
| + })) |
| + t.Cleanup(d.ts.Close) |
| + return d |
| +} |
| + |
| +// collect puts the box's frames on d.frames until an End or an error. |
| +func (d *ixDoor) collect(ws *websocket.Conn) { |
| + for { |
| + _ = ws.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| + kind, p, err := interactive.Receive(ws) |
| + if err != nil { |
| + return |
| + } |
| + d.frames <- ixFrame{kind, p} |
| + if kind == interactive.KindEnd { |
| + return |
| + } |
| + } |
| +} |
| + |
| +func (d *ixDoor) dials() []http.Header { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + return append([]http.Header(nil), d.headers...) |
| +} |
| + |
| +// next is the box's next frame other than a keepalive. |
| +func (d *ixDoor) next(t *testing.T) ixFrame { |
| + t.Helper() |
| + for { |
| + select { |
| + case f := <-d.frames: |
| + if f.kind == interactive.KindAlive { |
| + continue |
| + } |
| + return f |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("no frame from the box") |
| + } |
| + } |
| +} |
| + |
| +func (d *ixDoor) wantStatus(t *testing.T, state string) { |
| + t.Helper() |
| + f := d.next(t) |
| + var st interactive.Status |
| + if f.kind != interactive.KindStatus || json.Unmarshal(f.payload, &st) != nil || st.State != state { |
| + t.Fatalf("frame %q %s, want Status %s", f.kind, f.payload, state) |
| + } |
| +} |
| + |
| +func (d *ixDoor) wantEnd(t *testing.T) interactive.End { |
| + t.Helper() |
| + f := d.next(t) |
| + var e interactive.End |
| + if f.kind != interactive.KindEnd || json.Unmarshal(f.payload, &e) != nil { |
| + t.Fatalf("frame %q %s, want an End", f.kind, f.payload) |
| + } |
| + return e |
| +} |
| + |
| +// ixWorld is one box: the store holding bah's shop config and the grant, |
| +// the door, the launcher and a worker wired to them. |
| +type ixWorld struct { |
| + t *testing.T |
| + store *ixStore |
| + priv ed25519.PrivateKey |
| + pub ed25519.PublicKey |
| + door *ixDoor |
| + launch *ixLaunch |
| + w *interactiveWorker |
| + events *eventLog |
| + dialed atomic.Int32 |
| +} |
| + |
| +func ixArgvOpen() interactive.Open { |
| + return interactive.Open{Schema: 1, Argv: []string{"bin/rails", "console"}, Term: "xterm-256color", Cols: 80, Rows: 24} |
| +} |
| + |
| +func newIxWorld(t *testing.T) *ixWorld { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s := &ixStore{Store: release.NewDirStore(t.TempDir())} |
| + if _, err := appconfig.SetInteractive(context.Background(), s.Store, ixAcct, "shop", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + wd := &ixWorld{t: t, store: s, priv: priv, pub: pub, door: newIxDoor(t, ixArgvOpen()), events: &eventLog{}} |
| + wd.launch = &ixLaunch{handle: newIxHandle(newIxTerm())} |
| + wd.w = newInteractiveWorker(s, ixRoutes(ixRoute(ixHost)), wd.launch, pub, "box-a") |
| + wd.w.events = wd.events |
| + dial := wd.w.dial |
| + wd.w.dial = func(ctx context.Context, url, origin string, h http.Header) (*websocket.Conn, error) { |
| + wd.dialed.Add(1) |
| + return dial(ctx, url, origin, h) |
| + } |
| + return wd |
| +} |
| + |
| +// grant writes id's grant for rec, signed by key (the world's own when |
| +// nil), with mutate applied before signing. |
| +func (wd *ixWorld) grant(rec provision.Record, key ed25519.PrivateKey, mutate func(*interactive.Grant)) interactive.Grant { |
| + wd.t.Helper() |
| + if key == nil { |
| + key = wd.priv |
| + } |
| + now := time.Now().UTC() |
| + g := interactive.Grant{V: 1, ID: rec.Interactive.ID, Account: rec.Account, App: rec.App, Host: rec.Host, |
| + Incarnation: recordIncarnation(rec), Attach: interactive.AttachURL(wd.door.ts.URL, rec.Interactive.ID), |
| + Token: "tok-" + rec.Interactive.ID, By: "alice@keymail.dev", IssuedAt: now, PickupBy: now.Add(time.Minute)} |
| + if mutate != nil { |
| + mutate(&g) |
| + } |
| + wire, err := interactive.SignGrant(key, g) |
| + if err != nil { |
| + wd.t.Fatal(err) |
| + } |
| + if _, err := wd.store.Store.Put(context.Background(), interactive.GrantKey(g.Account, g.App, g.ID), wire, ""); err != nil { |
| + wd.t.Fatal(err) |
| + } |
| + return g |
| +} |
| + |
| +// session notes a fresh marked record with a valid grant and runs a pass. |
| +func (wd *ixWorld) session() (provision.Record, interactive.Grant) { |
| + wd.t.Helper() |
| + rec := ixRecord(ixID(wd.t), time.Now().Add(time.Minute)) |
| + g := wd.grant(rec, nil, nil) |
| + wd.store.reset() |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + return rec, g |
| +} |
| + |
| +// wait is the worker's sessions all ended. |
| +func (wd *ixWorld) wait() { |
| + wd.t.Helper() |
| + waitFor(wd.t, "the worker's sessions to end", func() bool { |
| + wd.w.mu.Lock() |
| + defer wd.w.mu.Unlock() |
| + return len(wd.w.active) == 0 |
| + }) |
| +} |
| + |
| +// eventMsgs is the session lines the worker published. |
| +func (wd *ixWorld) eventMsgs() []string { |
| + var out []string |
| + for _, e := range wd.events.all() { |
| + out = append(out, e.msg) |
| + } |
| + return out |
| +} |
| + |
| +// ixCaptureLog collects the package log for the test. |
| +func ixCaptureLog(t *testing.T) func() string { |
| + t.Helper() |
| + var mu sync.Mutex |
| + var buf bytes.Buffer |
| + prev := log.Writer() |
| + log.SetOutput(writerFunc(func(p []byte) (int, error) { mu.Lock(); defer mu.Unlock(); return buf.Write(p) })) |
| + t.Cleanup(func() { log.SetOutput(prev) }) |
| + return func() string { mu.Lock(); defer mu.Unlock(); return buf.String() } |
| +} |
| + |
| +func TestInteractiveWorkerIgnoresAForgedGrant(t *testing.T) { |
| + wd := newIxWorld(t) |
| + logs := ixCaptureLog(t) |
| + _, other, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + wd.grant(rec, other, nil) |
| + wd.store.reset() |
| + for range 2 { |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + } |
| + wd.wait() |
| + if wd.dialed.Load() != 0 || len(wd.door.dials()) != 0 || len(wd.launch.calls()) != 0 { |
| + t.Fatalf("a forged grant: %d dials, %d launches", wd.dialed.Load(), len(wd.launch.calls())) |
| + } |
| + if gets, writes, lists := wd.store.counts(); gets != 1 || writes != 0 || lists != 0 { |
| + t.Fatalf("requests: %d GETs, %d writes, %d lists; want the one grant GET, once", gets, writes, lists) |
| + } |
| + if n := strings.Count(logs(), rec.Interactive.ID); n != 1 { |
| + t.Fatalf("the forged grant was logged %d times, want once:\n%s", n, logs()) |
| + } |
| + if len(wd.events.all()) != 0 { |
| + t.Fatalf("a forged grant published %v", wd.eventMsgs()) |
| + } |
| +} |
| + |
| +// A grant that verifies but is not this record's session, or is past its |
| +// pickup, is ignored: no dial. |
| +func TestInteractiveWorkerIgnoresAGrantThatIsNotTheRecords(t *testing.T) { |
| + cases := map[string]func(*interactive.Grant){ |
| + "another host": func(g *interactive.Grant) { g.Host = "other.example.com" }, |
| + "another app": func(g *interactive.Grant) { g.App = "blog" }, |
| + "another account": func(g *interactive.Grant) { g.Account = domains.Sqid(8) }, |
| + "past its pickup": func(g *interactive.Grant) { |
| + g.IssuedAt, g.PickupBy = time.Now().Add(-2*time.Minute), time.Now().Add(-time.Second) |
| + }, |
| + } |
| + for name, mutate := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + g := wd.grant(rec, nil, mutate) |
| + if g.Account != rec.Account || g.App != rec.App { |
| + // The grant lives at the record's key all the same. |
| + wire, _, err := wd.store.Store.Get(context.Background(), interactive.GrantKey(g.Account, g.App, g.ID)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := wd.store.Store.Put(context.Background(), interactive.GrantKey(rec.Account, rec.App, g.ID), wire, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + wd.wait() |
| + if wd.dialed.Load() != 0 || len(wd.launch.calls()) != 0 { |
| + t.Fatalf("%s: %d dials, %d launches", name, wd.dialed.Load(), len(wd.launch.calls())) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A malformed id never becomes a store key (carried from Task 3). |
| +func TestInteractiveWorkerChecksTheIDBeforeTheGrantKey(t *testing.T) { |
| + wd := newIxWorld(t) |
| + for _, id := range []string{"../../../control/serial", "tty_short", ""} { |
| + rec := ixRecord(id, time.Now().Add(time.Minute)) |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + } |
| + if gets, _, _ := wd.store.counts(); gets != 0 || wd.dialed.Load() != 0 { |
| + t.Fatalf("malformed ids: %d GETs (%v), %d dials", gets, wd.store.keys, wd.dialed.Load()) |
| + } |
| +} |
| + |
| +// A dial the door refuses is logged once, starts nothing and is not tried |
| +// again. |
| +func TestInteractiveWorkerLogsADoorRefusalOnce(t *testing.T) { |
| + wd := newIxWorld(t) |
| + logs := ixCaptureLog(t) |
| + wd.door.refuse = http.StatusNotFound |
| + rec, _ := wd.session() |
| + wd.wait() |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + wd.wait() |
| + if len(wd.door.dials()) != 1 || len(wd.launch.calls()) != 0 { |
| + t.Fatalf("a refused door: %d dials, %d launches", len(wd.door.dials()), len(wd.launch.calls())) |
| + } |
| + if n := strings.Count(logs(), rec.Interactive.ID); n != 1 { |
| + t.Fatalf("the refusal was logged %d times:\n%s", n, logs()) |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerPassesTheProcessThrough(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + open interactive.Open |
| + process string |
| + args []string |
| + }{ |
| + {"console", interactive.Open{Schema: 1, Process: release.ProcessConsole, Term: "screen", Cols: 120, Rows: 40}, release.ProcessConsole, nil}, |
| + {"argv", interactive.Open{Schema: 1, Argv: []string{"bin/rails", "c"}}, "", []string{"bin/rails", "c"}}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.door.open = c.open |
| + rec, _ := wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + calls := wd.launch.calls() |
| + if len(calls) != 1 { |
| + t.Fatalf("%d launches", len(calls)) |
| + } |
| + sp := calls[0] |
| + want := c.open.Normalized() |
| + if sp.RunID != rec.Interactive.ID || sp.Process != c.process || fmt.Sprint(sp.Args) != fmt.Sprint(c.args) || |
| + (c.args == nil) != (sp.Args == nil) || sp.TTY == nil || |
| + sp.TTY.Term != want.Term || int(sp.TTY.Cols) != want.Cols || int(sp.TTY.Rows) != want.Rows || |
| + sp.RunDir != "" || sp.Stdout != nil || sp.Stderr != nil { |
| + t.Fatalf("spec %+v (tty %+v), want process %q args %q tty %s %dx%d", sp, sp.TTY, c.process, c.args, want.Term, want.Cols, want.Rows) |
| + } |
| + if rt := wd.launch.routes[0]; rt.Host != ixHost { |
| + t.Fatalf("launched on %+v", rt) |
| + } |
| + wd.launch.handle.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "0"}) |
| + wd.launch.handle.term.(*ixTerm).outW.Close() |
| + if e := wd.door.wantEnd(t); e.Reason != interactive.EndExited { |
| + t.Fatalf("end %+v", e) |
| + } |
| + wd.wait() |
| + }) |
| + } |
| +} |
| + |
| +// A refusal over the connection is an End refused, and nothing starts. |
| +func ixRefusal(t *testing.T, wd *ixWorld, rec provision.Record, want string) { |
| + t.Helper() |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + e := wd.door.wantEnd(t) |
| + if e.Reason != interactive.EndRefused || e.Refused != want { |
| + t.Fatalf("end %+v, want refused %q", e, want) |
| + } |
| + wd.wait() |
| + if n := len(wd.launch.calls()); n != 0 { |
| + t.Fatalf("a refused session launched %d times", n) |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerRefusesWhenTheAppDisallows(t *testing.T) { |
| + wd := newIxWorld(t) |
| + if _, err := appconfig.SetInteractive(context.Background(), wd.store.Store, ixAcct, "shop", false); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + wd.grant(rec, nil, nil) |
| + ixRefusal(t, wd, rec, interactive.RefusedOff) |
| + if got := wd.eventMsgs(); len(got) != 1 || got[0] != "interactive session "+rec.Interactive.ID+" did not start: interactive sessions are off for this app" { |
| + t.Fatalf("events %q", got) |
| + } |
| +} |
| + |
| +// The setting is read from the default bundle (carried from Task 4): an |
| +// environment's bundle that says on does not allow a session. |
| +func TestInteractiveWorkerReadsTheDefaultBundle(t *testing.T) { |
| + wd := newIxWorld(t) |
| + if _, err := appconfig.SetInteractive(context.Background(), wd.store.Store, ixAcct, "shop", false); err != nil { |
| + t.Fatal(err) |
| + } |
| + env := appconfig.Manifest{Schema: 1, App: "shop", Interactive: true, Vars: map[string]appconfig.Var{}} |
| + body, _ := json.Marshal(env) |
| + if _, err := wd.store.Store.Put(context.Background(), release.AppPrefix(ixAcct, "shop")+"environments/production/config.json", body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + rec.Environment = "production" |
| + wd.grant(rec, nil, nil) |
| + ixRefusal(t, wd, rec, interactive.RefusedOff) |
| +} |
| + |
| +func TestInteractiveWorkerRefusesAnotherIncarnation(t *testing.T) { |
| + wd := newIxWorld(t) |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + wd.grant(rec, nil, func(g *interactive.Grant) { g.Incarnation = "inc-of-an-older-instance" }) |
| + ixRefusal(t, wd, rec, runs.RefusedIncarnation) |
| +} |
| + |
| +func TestInteractiveWorkerRefusesAnUncommittedImport(t *testing.T) { |
| + wd := newIxWorld(t) |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + rec.Seed = &provision.SeedSource{ID: "seed_1", Kind: seeds.KindImport, State: seeds.StateSwapped, By: "t", At: time.Now().UTC()} |
| + if !rec.ImportUncommitted() { |
| + t.Fatal("fixture: the record is not an uncommitted import") |
| + } |
| + wd.grant(rec, nil, nil) |
| + ixRefusal(t, wd, rec, runs.RefusedImport) |
| +} |
| + |
| +func TestInteractiveWorkerMapsLaunchRefusals(t *testing.T) { |
| + for _, c := range []struct { |
| + err error |
| + refused, detail string |
| + words string |
| + }{ |
| + {activator.ErrCmdClaim, runs.RefusedClaim, "", "the box has host claims armed"}, |
| + {activator.ErrCmdNotNested, runs.RefusedFlat, "", "the box is not on the nested layout yet"}, |
| + {&activator.CmdWakeError{Reason: "its database could not be restored", Err: errors.New("s3")}, runs.RefusedWake, |
| + "its database could not be restored", "the instance did not wake. its database could not be restored"}, |
| + {activator.ErrTTYBusy, interactive.RefusedBusy, "", "the box was still closing the last session"}, |
| + } { |
| + t.Run(c.refused, func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.launch.err = fmt.Errorf("activator: %w", c.err) |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + wd.grant(rec, nil, nil) |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + e := wd.door.wantEnd(t) |
| + if e.Reason != interactive.EndRefused || e.Refused != c.refused || e.Detail != c.detail || !e.Started.IsZero() { |
| + t.Fatalf("end %+v, want refused %q detail %q", e, c.refused, c.detail) |
| + } |
| + wd.wait() |
| + if got := wd.eventMsgs(); len(got) != 1 || got[0] != "interactive session "+rec.Interactive.ID+" did not start: "+c.words { |
| + t.Fatalf("events %q", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Any other launch error, and a stop that beat the start, are interruptions |
| +// before the start. |
| +func TestInteractiveWorkerReportsAFailedStart(t *testing.T) { |
| + for _, c := range []struct { |
| + err error |
| + detail string |
| + }{ |
| + {errors.New("control: connection refused"), runs.InterruptedStartFailed}, |
| + {&activator.CmdStoppedError{Reason: activator.StopRestart}, activator.StopRestart}, |
| + } { |
| + wd := newIxWorld(t) |
| + wd.launch.err = c.err |
| + rec, _ := wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + e := wd.door.wantEnd(t) |
| + if e.Reason != interactive.EndInterrupted || e.Detail != c.detail || !e.Started.IsZero() { |
| + t.Fatalf("end %+v, want interrupted %q", e, c.detail) |
| + } |
| + wd.wait() |
| + if got := wd.eventMsgs(); len(got) != 1 || got[0] != "interactive session "+rec.Interactive.ID+" did not start: "+c.detail { |
| + t.Fatalf("events %q", got) |
| + } |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerOnlyActsOnOwnedRows(t *testing.T) { |
| + notManaged := ixRoute(ixHost) |
| + notManaged.Socket = "" |
| + otherAcct := ixRoute(ixHost) |
| + otherAcct.Account = domains.Sqid(8) |
| + unprovisioned := ixRoute(ixHost) |
| + unprovisioned.Provisioned = false |
| + for name, rt := range map[string]*registry.Route{"no row": nil, "not the activator's": notManaged, |
| + "another account's": otherAcct, "not provisioned": unprovisioned} { |
| + t.Run(name, func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.routes = ixRoutes(rt) |
| + wd.session() |
| + wd.wait() |
| + if gets, _, _ := wd.store.counts(); gets != 0 || wd.dialed.Load() != 0 || len(wd.launch.calls()) != 0 { |
| + t.Fatalf("%s: %d GETs, %d dials, %d launches", name, gets, wd.dialed.Load(), len(wd.launch.calls())) |
| + } |
| + }) |
| + } |
| + // Control: the owned row dials. |
| + wd := newIxWorld(t) |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + if wd.dialed.Load() != 1 { |
| + t.Fatal("an owned row did not dial") |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerOnAnHARouteOnlyWhenItHoldsTheHost(t *testing.T) { |
| + ha := ixRoute(ixHost) |
| + ha.HA = true |
| + t.Run("not held", func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.routes = ixRoutes(ha) |
| + var asked []string |
| + wd.w.holds = func(h string) bool { asked = append(asked, h); return false } |
| + logs := ixCaptureLog(t) |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + wd.grant(rec, nil, nil) |
| + wd.store.reset() |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + wd.wait() |
| + if gets, _, _ := wd.store.counts(); gets != 0 || wd.dialed.Load() != 0 || fmt.Sprint(asked) != "["+ixHost+"]" { |
| + t.Fatalf("a non-holder: %d GETs, %d dials, asked %q", gets, wd.dialed.Load(), asked) |
| + } |
| + if strings.Contains(logs(), rec.Interactive.ID) { |
| + t.Fatalf("a non-holder logged the session:\n%s", logs()) |
| + } |
| + }) |
| + t.Run("held", func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.routes = ixRoutes(ha) |
| + wd.w.holds = func(string) bool { return true } |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + }) |
| + t.Run("not HA", func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.holds = func(string) bool { t.Error("holds consulted for a route that is not HA"); return false } |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + }) |
| +} |
| + |
| +// The worker acts only on records reconcile's judged pass hands it: a |
| +// record whose host incarnation slot no longer vouches for it never reaches |
| +// the worker, so nothing is read for it and nothing dials. The control's |
| +// slot vouches. |
| +func TestInteractiveWorkerReadsRecordsJudged(t *testing.T) { |
| + for _, vouched := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("vouched=%v", vouched), func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + ctx := context.Background() |
| + judge := provision.NewLifetimeJudge() |
| + wd.w.judge = judge |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + rec.Pool, rec.Incarnation = "shared", 1 |
| + if err := console.WriteAccountManifest(ctx, wd.store.Store, 7, ixAcct, "Shop", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(ctx, wd.store.Store, ixAcct, "shop", provision.Manifest{Schema: 1, App: "shop", Domain: "example.com"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.CreateRecord(ctx, wd.store.Store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + state := provision.SlotLive |
| + if !vouched { |
| + state = provision.SlotRetired |
| + } |
| + if _, err := provision.WriteHostIncarnation(ctx, wd.store.Store, ixHost, |
| + provision.HostIncarnation{Account: rec.Account, App: rec.App, Incarnation: 1, State: state}, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + wd.grant(rec, nil, nil) |
| + armedInteractive.Store(wd.w) |
| + t.Cleanup(func() { armedInteractive.Store(nil) }) |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + cfg := withInteractiveHook(provision.ReconcileConfig{Region: "uk", Pools: []string{"shared"}, DataDir: t.TempDir(), Judge: judge, DryRun: true}) |
| + if err := provision.Reconcile(ctx, wd.store.Store, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + wd.store.reset() |
| + runInteractivePass(ctx) |
| + gets, _, _ := wd.store.counts() |
| + if !vouched { |
| + wd.wait() |
| + if gets != 0 || wd.dialed.Load() != 0 { |
| + t.Fatalf("a stale record: %d GETs (%q), %d dials", gets, wd.store.keys, wd.dialed.Load()) |
| + } |
| + return |
| + } |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + if wd.dialed.Load() != 1 { |
| + t.Fatal("control: a vouched record did not dial") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerPresentsTheFleetCredential(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.fleet = func() (string, string, bool) { return "f/box-a", "tok", true } |
| + _, g := wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + h := wd.door.dials()[0] |
| + if h.Get("Authorization") != "Bearer tok" || h.Get("Carlos-Tunnel-Name") != "f/box-a" || |
| + h.Get(interactive.HeaderToken) != g.Token || h.Get("X-Carlos-Box") != "box-a" { |
| + t.Fatalf("dial headers %v", h) |
| + } |
| + // Control: a platform box sends neither fleet header. |
| + wd2 := newIxWorld(t) |
| + wd2.session() |
| + wd2.door.wantStatus(t, interactive.StateStarting) |
| + h = wd2.door.dials()[0] |
| + if h.Get("Authorization") != "" || h.Get("Carlos-Tunnel-Name") != "" || h.Get("X-Carlos-Box") != "box-a" { |
| + t.Fatalf("platform dial headers %v", h) |
| + } |
| +} |
| + |
| +// The bridge: output to Data frames, Data to the terminal, Resize to the |
| +// terminal; the command's exit ends the session after its last output. |
| +func TestInteractiveWorkerBridgesAndEndsAfterTheLastOutput(t *testing.T) { |
| + wd := newIxWorld(t) |
| + inbound := make(chan ixFrame, 4) |
| + wd.door.script = func(ws *websocket.Conn) { |
| + go func() { |
| + for f := range inbound { |
| + _ = interactive.Send(ws, f.kind, f.payload) |
| + } |
| + }() |
| + wd.door.collect(ws) |
| + } |
| + rec, _ := wd.session() |
| + defer close(inbound) |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + inbound <- ixFrame{interactive.KindData, []byte("puts 1\r")} |
| + inbound <- ixFrame{interactive.KindResize, interactive.ResizePayload(132, 50)} |
| + term := wd.launch.handle.term.(*ixTerm) |
| + waitFor(t, "the input and the resize", func() bool { |
| + term.mu.Lock() |
| + defer term.mu.Unlock() |
| + return term.in.String() == "puts 1\r" && len(term.resizes) == 1 && term.resizes[0] == [2]uint16{132, 50} |
| + }) |
| + big := bytes.Repeat([]byte("x"), 100<<10) |
| + go func() { |
| + term.outW.Write(big) |
| + wd.launch.handle.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "3"}) |
| + time.Sleep(50 * time.Millisecond) |
| + term.outW.Write([]byte("bye")) |
| + term.outW.CloseWithError(errors.New("read /dev/ptmx: input/output error")) |
| + }() |
| + var got []byte |
| + for { |
| + f := wd.door.next(t) |
| + if f.kind == interactive.KindEnd { |
| + var e interactive.End |
| + if err := json.Unmarshal(f.payload, &e); err != nil || e.Reason != interactive.EndExited || e.Exit != 3 || e.Started.IsZero() || e.Box != "box-a" { |
| + t.Fatalf("end %s", f.payload) |
| + } |
| + break |
| + } |
| + if f.kind != interactive.KindData || len(f.payload) > 32<<10 { |
| + t.Fatalf("frame %q of %d bytes", f.kind, len(f.payload)) |
| + } |
| + got = append(got, f.payload...) |
| + } |
| + if want := append(append([]byte{}, big...), "bye"...); !bytes.Equal(got, want) { |
| + t.Fatalf("output: %d bytes, want %d, End before the last output", len(got), len(want)) |
| + } |
| + wd.wait() |
| + if stops, releases := wd.launch.handle.stopped(); len(stops) != 1 || releases != 1 { |
| + t.Fatalf("after the exit: %d stops, %d releases", len(stops), releases) |
| + } |
| + msgs := wd.eventMsgs() |
| + if len(msgs) != 2 || msgs[0] != "interactive session "+rec.Interactive.ID+" opened by alice@keymail.dev" || |
| + !strings.HasPrefix(msgs[1], "interactive session "+rec.Interactive.ID+" ended with exit 3 after ") { |
| + t.Fatalf("events %q", msgs) |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerEndsAnIdleSession(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.idle = 50 * time.Millisecond |
| + wd.w.grace = 20 * time.Millisecond |
| + rec, _ := wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + e := wd.door.wantEnd(t) |
| + if e.Reason != interactive.EndIdle { |
| + t.Fatalf("end %+v, want idle", e) |
| + } |
| + wd.wait() |
| + if wd.launch.handle.term.(*ixTerm).hungUp() == 0 { |
| + t.Fatal("an idle session was not hung up") |
| + } |
| + if stops, releases := wd.launch.handle.stopped(); len(stops) == 0 || releases != 1 { |
| + t.Fatalf("%d stops, %d releases", len(stops), releases) |
| + } |
| + msgs := wd.eventMsgs() |
| + if len(msgs) != 2 || !strings.HasSuffix(msgs[1], ": 30 minutes passed without a keystroke") || |
| + !strings.HasPrefix(msgs[1], "interactive session "+rec.Interactive.ID+" ended after ") { |
| + t.Fatalf("events %q", msgs) |
| + } |
| +} |
| + |
| +// Keystrokes hold the idle timer off. |
| +func TestInteractiveWorkerKeystrokesResetTheIdleTimer(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.idle = 300 * time.Millisecond |
| + wd.w.grace = 20 * time.Millisecond |
| + typed := make(chan struct{}) |
| + wd.door.script = func(ws *websocket.Conn) { |
| + go func() { |
| + for range 8 { |
| + time.Sleep(100 * time.Millisecond) |
| + _ = interactive.Send(ws, interactive.KindData, []byte("a")) |
| + } |
| + close(typed) |
| + }() |
| + wd.door.collect(ws) |
| + } |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + start := time.Now() |
| + e := wd.door.wantEnd(t) |
| + <-typed |
| + if e.Reason != interactive.EndIdle || time.Since(start) < 800*time.Millisecond { |
| + t.Fatalf("end %+v after %s: keystrokes did not hold the idle timer", e, time.Since(start)) |
| + } |
| + wd.wait() |
| +} |
| + |
| +func TestInteractiveWorkerEndsAtItsLimit(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.max = 80 * time.Millisecond |
| + wd.w.grace = 20 * time.Millisecond |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + if e := wd.door.wantEnd(t); e.Reason != interactive.EndLimit { |
| + t.Fatalf("end %+v, want limit", e) |
| + } |
| + wd.wait() |
| + if !strings.HasSuffix(wd.eventMsgs()[1], ": it reached its 6 hour limit") { |
| + t.Fatalf("events %q", wd.eventMsgs()) |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerHangsUpThenStops(t *testing.T) { |
| + for _, exits := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("exits within grace=%v", exits), func(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.grace = 150 * time.Millisecond |
| + var hungAt atomic.Int64 |
| + wd.door.script = func(ws *websocket.Conn) { |
| + go func() { |
| + time.Sleep(50 * time.Millisecond) |
| + raw, _ := json.Marshal(interactive.End{Reason: interactive.EndHangup, Ended: time.Now().UTC()}) |
| + hungAt.Store(time.Now().UnixNano()) |
| + _ = interactive.Send(ws, interactive.KindEnd, raw) |
| + }() |
| + wd.door.collect(ws) |
| + } |
| + h := wd.launch.handle |
| + term := h.term.(*ixTerm) |
| + go func() { |
| + waitFor(t, "the hangup", func() bool { return term.hungUp() > 0 }) |
| + if exits { |
| + h.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "129"}) |
| + } |
| + }() |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + if e := wd.door.wantEnd(t); e.Reason != interactive.EndHangup { |
| + t.Fatalf("end %+v, want hangup", e) |
| + } |
| + wd.wait() |
| + stops, releases := h.stopped() |
| + if term.hungUp() == 0 || len(stops) == 0 || releases != 1 { |
| + t.Fatalf("hangups %d, stops %d, releases %d", term.hungUp(), len(stops), releases) |
| + } |
| + after := stops[0].Sub(time.Unix(0, hungAt.Load())) |
| + if !exits && after < 150*time.Millisecond { |
| + t.Fatalf("stopped %s after the hangup, before the grace", after) |
| + } |
| + if exits && after >= 150*time.Millisecond { |
| + t.Fatalf("a unit that ended within the grace was stopped only after %s", after) |
| + } |
| + if !strings.HasSuffix(wd.eventMsgs()[1], ": the person's connection closed") { |
| + t.Fatalf("events %q", wd.eventMsgs()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The connection lost is a hangup, ended as lost. |
| +func TestInteractiveWorkerHangsUpWhenTheConnectionIsLost(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.grace = 20 * time.Millisecond |
| + wd.door.script = func(ws *websocket.Conn) { |
| + interactive.Receive(ws) // starting |
| + interactive.Receive(ws) // started |
| + ws.Close() |
| + } |
| + wd.session() |
| + wd.wait() |
| + h := wd.launch.handle |
| + if stops, releases := h.stopped(); h.term.(*ixTerm).hungUp() == 0 || len(stops) == 0 || releases != 1 { |
| + t.Fatalf("stops %d, releases %d", len(stops), releases) |
| + } |
| + if msgs := wd.eventMsgs(); len(msgs) != 2 || !strings.HasSuffix(msgs[1], ": the box lost its connection to the console") { |
| + t.Fatalf("events %q", msgs) |
| + } |
| +} |
| + |
| +// A console that goes silent is lost after KeepaliveLost; the box sends |
| +// its own keepalive every KeepaliveEvery. |
| +func TestInteractiveWorkerKeepsAliveAndLosesASilentConsole(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.alive, wd.w.lost, wd.w.grace = 30*time.Millisecond, 250*time.Millisecond, 20*time.Millisecond |
| + alive := make(chan int, 1) |
| + wd.door.script = func(ws *websocket.Conn) { |
| + n := 0 |
| + _ = ws.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| + for { |
| + kind, _, err := interactive.Receive(ws) |
| + if err != nil { |
| + break |
| + } |
| + if kind == interactive.KindAlive { |
| + n++ |
| + } |
| + } |
| + alive <- n |
| + } |
| + wd.session() |
| + wd.wait() |
| + if n := <-alive; n < 3 { |
| + t.Fatalf("%d keepalives in the session", n) |
| + } |
| + if msgs := wd.eventMsgs(); len(msgs) != 2 || !strings.HasSuffix(msgs[1], ": the box lost its connection to the console") { |
| + t.Fatalf("events %q", msgs) |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerReportsAnInterruption(t *testing.T) { |
| + wd := newIxWorld(t) |
| + h := wd.launch.handle |
| + rec, _ := wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + h.interrupt(activator.StopRestart, time.Now()) |
| + h.term.(*ixTerm).close() |
| + h.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "killed", Status: "15"}) |
| + e := wd.door.wantEnd(t) |
| + if e.Reason != interactive.EndInterrupted || e.Detail != activator.StopRestart { |
| + t.Fatalf("end %+v, want interrupted %q", e, activator.StopRestart) |
| + } |
| + wd.wait() |
| + if msgs := wd.eventMsgs(); len(msgs) != 2 || !strings.HasPrefix(msgs[1], "interactive session "+rec.Interactive.ID+" ended after ") || |
| + !strings.HasSuffix(msgs[1], ": "+activator.StopRestart) { |
| + t.Fatalf("events %q", msgs) |
| + } |
| + if _, releases := h.stopped(); releases != 1 { |
| + t.Fatalf("%d releases", releases) |
| + } |
| +} |
| + |
| +// A stop asked for after the command had finished does not turn its exit |
| +// into an interruption. |
| +func TestInteractiveWorkerKeepsAnExitThatCameFirst(t *testing.T) { |
| + wd := newIxWorld(t) |
| + h := wd.launch.handle |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + h.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "0"}) |
| + time.Sleep(20 * time.Millisecond) |
| + h.interrupt(activator.StopIdle, time.Now().Add(time.Second)) |
| + h.term.(*ixTerm).outW.Close() |
| + if e := wd.door.wantEnd(t); e.Reason != interactive.EndExited || e.Exit != 0 { |
| + t.Fatalf("end %+v, want exited 0", e) |
| + } |
| + wd.wait() |
| +} |
| + |
| +// A unit that ended without taking its terminal (activator.TTYStartFailed, |
| +// decided after the stop has joined the handoff) is the box failing to |
| +// start the command. |
| +func TestInteractiveWorkerReportsAStartThatNeverTookItsTerminal(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.drain = 50 * time.Millisecond |
| + h := wd.launch.handle |
| + wd.w.startFailed = func(term activator.Terminal, st instancectl.CmdStatus) bool { |
| + h.note("startFailed") |
| + return term == h.term && st.State == instancectl.CmdDone |
| + } |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + h.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "1"}) |
| + e := wd.door.wantEnd(t) |
| + if e.Reason != interactive.EndInterrupted || e.Detail != runs.InterruptedStartFailed { |
| + t.Fatalf("end %+v, want interrupted %q", e, runs.InterruptedStartFailed) |
| + } |
| + wd.wait() |
| + h.mu.Lock() |
| + order := strings.Join(h.events, ",") |
| + h.mu.Unlock() |
| + if !strings.HasPrefix(order, "stop,startFailed") || !strings.HasSuffix(order, "release") { |
| + t.Fatalf("order %s: the start's verdict must follow the stop", order) |
| + } |
| +} |
| + |
| +func TestInteractiveWorkerWritesNothingToTheBucket(t *testing.T) { |
| + wd := newIxWorld(t) |
| + rec := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + wd.grant(rec, nil, nil) |
| + wd.store.reset() |
| + wd.store.failWrites = true |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + wd.launch.handle.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "0"}) |
| + wd.launch.handle.term.(*ixTerm).outW.Close() |
| + if e := wd.door.wantEnd(t); e.Reason != interactive.EndExited { |
| + t.Fatalf("end %+v", e) |
| + } |
| + wd.wait() |
| + if _, writes, _ := wd.store.counts(); writes != 0 { |
| + t.Fatalf("the worker made %d writes", writes) |
| + } |
| +} |
| + |
| +// The request budget (plan Task 10, "Owning box"): one grant GET and one |
| +// config.json GET per session, nothing else; an idle pass and a pass on a |
| +// box that does not own the row make none. |
| +func TestInteractiveWorkerRequestBudget(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.pass(context.Background()) |
| + if gets, writes, lists := wd.store.counts(); gets+writes+lists != 0 { |
| + t.Fatalf("an idle pass: %d GETs, %d writes, %d lists", gets, writes, lists) |
| + } |
| + rec, _ := wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + wd.launch.handle.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "0"}) |
| + wd.launch.handle.term.(*ixTerm).outW.Close() |
| + wd.door.wantEnd(t) |
| + wd.wait() |
| + gets, writes, lists := wd.store.counts() |
| + want := []string{interactive.GrantKey(ixAcct, "shop", rec.Interactive.ID), appconfig.Key(ixAcct, "shop")} |
| + if gets != 2 || writes != 0 || lists != 0 || fmt.Sprint(wd.store.keys) != fmt.Sprint(want) { |
| + t.Fatalf("one session: %d GETs %q, %d writes, %d lists; want %q", gets, wd.store.keys, writes, lists, want) |
| + } |
| + // The same record again (a later reconcile pass) reads nothing. |
| + wd.store.reset() |
| + wd.w.note(rec) |
| + wd.w.pass(context.Background()) |
| + if gets, _, _ := wd.store.counts(); gets != 0 { |
| + t.Fatalf("a seen session read %d objects", gets) |
| + } |
| + other := newIxWorld(t) |
| + other.w.routes = noRoutes |
| + other.session() |
| + if gets, writes, lists := other.store.counts(); gets+writes+lists != 0 { |
| + t.Fatalf("a box that does not own the row: %d GETs, %d writes, %d lists", gets, writes, lists) |
| + } |
| +} |
| + |
| +// A newer session for the instance ends the one this worker still runs |
| +// first, as replaced, and then starts. |
| +func TestInteractiveWorkerReplacesAnOlderSession(t *testing.T) { |
| + wd := newIxWorld(t) |
| + wd.w.grace = 20 * time.Millisecond |
| + first := wd.launch.handle |
| + wd.session() |
| + wd.door.wantStatus(t, interactive.StateStarting) |
| + wd.door.wantStatus(t, interactive.StateStarted) |
| + |
| + // The second session's connection reports on frames2, with its own |
| + // handle; the first's still reports on the door's frames. |
| + second := newIxHandle(newIxTerm()) |
| + wd.launch.mu.Lock() |
| + wd.launch.handle = second |
| + wd.launch.mu.Unlock() |
| + frames2 := make(chan ixFrame, 256) |
| + wd.door.mu.Lock() |
| + wd.door.script = func(ws *websocket.Conn) { |
| + for { |
| + _ = ws.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| + kind, p, err := interactive.Receive(ws) |
| + if err != nil { |
| + return |
| + } |
| + frames2 <- ixFrame{kind, p} |
| + } |
| + } |
| + wd.door.mu.Unlock() |
| + rec2 := ixRecord(ixID(t), time.Now().Add(time.Minute)) |
| + wd.grant(rec2, nil, nil) |
| + wd.w.note(rec2) |
| + wd.w.pass(context.Background()) |
| + if e := wd.door.wantEnd(t); e.Reason != interactive.EndReplaced { |
| + t.Fatalf("the old session's end %+v, want replaced", e) |
| + } |
| + waitFor(t, "the new session to start", func() bool { return len(wd.launch.calls()) == 2 }) |
| + if stops, releases := first.stopped(); len(stops) == 0 || releases != 1 { |
| + t.Fatalf("the old session: %d stops, %d releases", len(stops), releases) |
| + } |
| + if calls := wd.launch.calls(); calls[1].RunID != rec2.Interactive.ID { |
| + t.Fatalf("second launch %+v", calls[1]) |
| + } |
| + second.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "0"}) |
| + second.term.(*ixTerm).outW.Close() |
| + wd.wait() |
| +} |
| + |
| +func TestInteractiveSessionLines(t *testing.T) { |
| + start := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) |
| + end := start.Add(5*time.Minute + 3*time.Second + 400*time.Millisecond) |
| + if got := sessionStartedLine("tty_a", "alice@keymail.dev"); got != "interactive session tty_a opened by alice@keymail.dev" { |
| + t.Fatal(got) |
| + } |
| + ran := func(e interactive.End) interactive.End { e.Started, e.Ended = start, end; return e } |
| + for _, c := range []struct { |
| + e interactive.End |
| + want string |
| + }{ |
| + {ran(interactive.End{Reason: interactive.EndExited, Exit: 2}), "interactive session tty_a ended with exit 2 after 5m3s"}, |
| + {ran(interactive.End{Reason: interactive.EndIdle}), "interactive session tty_a ended after 5m3s: 30 minutes passed without a keystroke"}, |
| + {ran(interactive.End{Reason: interactive.EndLimit}), "interactive session tty_a ended after 5m3s: it reached its 6 hour limit"}, |
| + {ran(interactive.End{Reason: interactive.EndHangup}), "interactive session tty_a ended after 5m3s: the person's connection closed"}, |
| + {ran(interactive.End{Reason: interactive.EndLost}), "interactive session tty_a ended after 5m3s: the box lost its connection to the console"}, |
| + {ran(interactive.End{Reason: interactive.EndInterrupted, Detail: activator.StopRelease}), "interactive session tty_a ended after 5m3s: the instance moved to a new release"}, |
| + {interactive.End{Reason: interactive.EndInterrupted, Detail: runs.InterruptedStartFailed, Ended: end}, "interactive session tty_a did not start: the box could not start the command"}, |
| + {interactive.End{Reason: interactive.EndRefused, Refused: interactive.RefusedOff, Ended: end}, "interactive session tty_a did not start: interactive sessions are off for this app"}, |
| + {interactive.End{Reason: interactive.EndRefused, Refused: interactive.RefusedBusy, Ended: end}, "interactive session tty_a did not start: the box was still closing the last session"}, |
| + {interactive.End{Reason: interactive.EndRefused, Refused: runs.RefusedImport, Ended: end}, "interactive session tty_a did not start: the instance is an import that is not committed yet"}, |
| + } { |
| + if got := sessionEndedLine("tty_a", c.e); got != c.want { |
| + t.Errorf("%+v: %q, want %q", c.e, got, c.want) |
| + } |
| + } |
| +} |
| + |
| +func TestInteractiveHookIsOnlyThereWhenArmed(t *testing.T) { |
| + armedInteractive.Store(nil) |
| + if cfg := withInteractiveHook(provision.ReconcileConfig{}); cfg.InteractiveSeen != nil { |
| + t.Fatal("an unarmed box must not hook reconcile") |
| + } |
| + runInteractivePass(context.Background()) // no-op, no panic |
| + wd := newIxWorld(t) |
| + armedInteractive.Store(wd.w) |
| + t.Cleanup(func() { armedInteractive.Store(nil) }) |
| + cfg := withInteractiveHook(provision.ReconcileConfig{}) |
| + if cfg.InteractiveSeen == nil { |
| + t.Fatal("an armed box hooks reconcile") |
| + } |
| + cfg.InteractiveSeen(ixRecord(ixID(t), time.Now().Add(time.Minute))) |
| + if len(wd.w.noted) != 1 { |
| + t.Fatal("the hook does not reach the worker") |
| + } |
| +} |
| + |
| +// The fleet credential is the tunnel's name and token, both set. |
| +func TestInteractiveFleetCredential(t *testing.T) { |
| + env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } |
| + if name, tok, ok := fleetCredential(env(map[string]string{"CARLOS_TUNNEL_NAME": "f/box-a", "CARLOS_TUNNEL_TOKEN": "tok"}))(); !ok || name != "f/box-a" || tok != "tok" { |
| + t.Fatalf("%q %q %v", name, tok, ok) |
| + } |
| + for _, m := range []map[string]string{{}, {"CARLOS_TUNNEL_NAME": "f/box-a"}, {"CARLOS_TUNNEL_TOKEN": "tok"}} { |
| + if _, _, ok := fleetCredential(env(m))(); ok { |
| + t.Fatalf("%v gave a credential", m) |
| + } |
| + } |
| +} |
| + |
| +// armInteractivePass arms only with an activator, a registry, a store and a |
| +// parseable CARLOS_RELEASE_PUBKEY, and otherwise says why once. |
| +func TestArmInteractivePassNeedsItsInputs(t *testing.T) { |
| + armedInteractive.Store(nil) |
| + t.Cleanup(func() { armedInteractive.Store(nil) }) |
| + pub, _, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { reg.Close() }) |
| + svc := activator.New(activator.Config{Bucket: "test-bucket", Idle: time.Minute}, &activator.ExecBackend{DataDir: t.TempDir()}, reg) |
| + t.Setenv("CARLOS_DEPLOYMENT_BUCKET", "") |
| + t.Setenv("CARLOS_FLEET", "") |
| + t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| + keyB64 := base64.StdEncoding.EncodeToString(pub) |
| + for _, c := range []struct { |
| + name string |
| + svc *activator.Service |
| + reg *registry.Registry |
| + key string |
| + }{ |
| + {"no activator", nil, reg, keyB64}, |
| + {"no registry", svc, nil, keyB64}, |
| + {"no release key", svc, reg, ""}, |
| + {"a bad release key", svc, reg, "bm90IGEga2V5"}, |
| + } { |
| + t.Setenv("CARLOS_RELEASE_PUBKEY", c.key) |
| + logs := ixCaptureLog(t) |
| + armInteractivePass(c.svc, c.reg, nil, nil) |
| + if armedInteractive.Load() != nil || strings.Count(logs(), "agent: interactive sessions disabled: ") != 1 { |
| + t.Fatalf("%s: armed %v, log:\n%s", c.name, armedInteractive.Load() != nil, logs()) |
| + } |
| + } |
| + t.Setenv("CARLOS_RELEASE_PUBKEY", keyB64) |
| + t.Setenv("CARLOS_TUNNEL_NAME", "f/box-a") |
| + t.Setenv("CARLOS_TUNNEL_TOKEN", "tok") |
| + judge := provision.NewLifetimeJudge() |
| + armInteractivePass(svc, reg, nil, judge) |
| + w := armedInteractive.Load() |
| + if w == nil || !w.pub.Equal(pub) || w.holds == nil || w.judge != judge || w.events != nil { |
| + t.Fatalf("all inputs: armed %+v", w) |
| + } |
| + if name, tok, ok := w.fleet(); !ok || name != "f/box-a" || tok != "tok" { |
| + t.Fatalf("fleet credential %q %q %v", name, tok, ok) |
| + } |
| +} |
| + |
| +// ixConsole is a real console (console.NewServer over the deployment |
| +// store, its mux and box door) with bah's shop, interactive sessions on, a |
| +// hibernating instance at ixHost, and a CLI token for its owner. |
| +type ixConsole struct { |
| + ts *httptest.Server |
| + store release.Store |
| + cst *console.Store |
| + pub ed25519.PublicKey |
| + token string |
| +} |
| + |
| +func newIxConsole(t *testing.T) *ixConsole { |
| + t.Helper() |
| + pub, priv, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rs := release.NewDirStore(t.TempDir()) |
| + dir := t.TempDir() |
| + cst, err := console.Open(filepath.Join(dir, "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var srv *console.Server |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) })) |
| + t.Cleanup(func() { |
| + ts.Close() |
| + cst.Close() |
| + }) |
| + if srv, err = console.NewServer(console.Config{Origin: ts.URL, Keymail: "http://keymail.invalid", |
| + Registry: filepath.Join(dir, "registry.db"), Releases: rs, ReleasePub: pub, Key: priv, AppScheme: "http", |
| + HomeRegion: "uk"}, cst); err != nil { |
| + t.Fatal(err) |
| + } |
| + now := time.Now() |
| + owner := "paul@keymail.dev" |
| + if err := cst.CreateAccount(7, ixAcct, "Shop", owner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := cst.CreateAppIn(7, "shop", owner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := console.WriteAccountManifest(context.Background(), rs, 7, ixAcct, "Shop", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + userCode, deviceCode, err := cst.NewCLIAuth("paul@laptop", "127.0.0.1", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cst.ApproveCLIAuth(userCode, owner, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, token, _, err := cst.PollCLIAuth(deviceCode, now) |
| + if err != nil || token == "" { |
| + t.Fatalf("no CLI token: %v", err) |
| + } |
| + yes := true |
| + rec := provision.Record{Schema: 1, Host: ixHost, Slug: "shop", App: "shop", Account: ixAcct, Region: "uk", Channel: "stable", |
| + CreatedAt: time.Now().UTC(), Hibernate: &yes} |
| + if err := provision.CreateRecord(context.Background(), rs, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := appconfig.SetInteractive(context.Background(), rs, ixAcct, "shop", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + return &ixConsole{ts: ts, store: rs, cst: cst, pub: pub, token: token} |
| +} |
| + |
| +// open dials the session door as the owner, sends o and waits for the |
| +// Status waiting that says the session is admitted. |
| +func (c *ixConsole) open(t *testing.T, o interactive.Open) *websocket.Conn { |
| + t.Helper() |
| + u, err := interactive.WebSocketURL(c.ts.URL + "/api/cli/apps/" + ixAcct + "/shop/instances/" + ixHost + "/interactive") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + ws, err := interactive.Dial(ctx, u, c.ts.URL, http.Header{"Authorization": {"Bearer " + c.token}}) |
| + if err != nil { |
| + t.Fatalf("dial the session door: %v", err) |
| + } |
| + t.Cleanup(func() { ws.Close() }) |
| + if err := interactive.SendJSON(ws, interactive.KindOpen, o); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st := cliStatus(t, ws); st != interactive.StateWaiting { |
| + t.Fatalf("first status %q, want waiting", st) |
| + } |
| + return ws |
| +} |
| + |
| +// record is the stored record of ixHost. |
| +func (c *ixConsole) record(t *testing.T) provision.Record { |
| + t.Helper() |
| + rec, err := provision.GetRecord(context.Background(), c.store, ixAcct, "shop", ixHost) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return *rec |
| +} |
| + |
| +func (c *ixConsole) audit(t *testing.T) []string { |
| + t.Helper() |
| + evs, err := c.cst.Events(7, "shop", 100) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []string |
| + for _, e := range evs { |
| + out = append(out, e.Action) |
| + } |
| + return out |
| +} |
| + |
| +// cliNext is the CLI's next frame other than a keepalive. |
| +func cliNext(t *testing.T, ws *websocket.Conn) (byte, []byte) { |
| + t.Helper() |
| + for { |
| + _ = ws.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| + kind, p, err := interactive.Receive(ws) |
| + if err != nil { |
| + t.Fatalf("the CLI's connection: %v", err) |
| + } |
| + if kind != interactive.KindAlive { |
| + return kind, p |
| + } |
| + } |
| +} |
| + |
| +func cliStatus(t *testing.T, ws *websocket.Conn) string { |
| + t.Helper() |
| + kind, p := cliNext(t, ws) |
| + var st interactive.Status |
| + if kind != interactive.KindStatus || json.Unmarshal(p, &st) != nil { |
| + t.Fatalf("frame %q %s, want a Status", kind, p) |
| + } |
| + return st.State |
| +} |
| + |
| +func cliEnd(t *testing.T, ws *websocket.Conn) interactive.End { |
| + t.Helper() |
| + for { |
| + kind, p := cliNext(t, ws) |
| + if kind == interactive.KindData { |
| + continue |
| + } |
| + var e interactive.End |
| + if kind != interactive.KindEnd || json.Unmarshal(p, &e) != nil { |
| + t.Fatalf("frame %q %s, want an End", kind, p) |
| + } |
| + return e |
| + } |
| +} |
| + |
| +// grantStore serves one saved grant at its key, whatever the store under |
| +// it holds now: worker B reads the grant A read, as if the console had not |
| +// yet deleted it. |
| +type grantStore struct { |
| + release.Store |
| + key string |
| + wire []byte |
| +} |
| + |
| +func (s *grantStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == s.key { |
| + return s.wire, "etag", nil |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +func TestARestartedWorkerCannotRelaunchAnEndedSession(t *testing.T) { |
| + c := newIxConsole(t) |
| + cli := c.open(t, interactive.Open{Schema: 1, Argv: []string{"sh"}, Term: "xterm", Cols: 80, Rows: 24}) |
| + rec := c.record(t) |
| + if rec.Interactive == nil { |
| + t.Fatal("the console wrote no marker") |
| + } |
| + id := rec.Interactive.ID |
| + key := interactive.GrantKey(ixAcct, "shop", id) |
| + wire, _, err := c.store.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + // Worker A runs the session, which ends early: the command exits. |
| + launchA := &ixLaunch{handle: newIxHandle(newIxTerm())} |
| + a := newInteractiveWorker(c.store, ixRoutes(ixRoute(ixHost)), launchA, c.pub, "box-a") |
| + a.note(rec) |
| + a.pass(context.Background()) |
| + if st := cliStatus(t, cli); st != interactive.StateStarting { |
| + t.Fatalf("status %q", st) |
| + } |
| + if st := cliStatus(t, cli); st != interactive.StateStarted { |
| + t.Fatalf("status %q", st) |
| + } |
| + launchA.handle.finish(instancectl.CmdStatus{State: instancectl.CmdDone, Code: "exited", Status: "0"}) |
| + launchA.handle.term.(*ixTerm).outW.Close() |
| + if e := cliEnd(t, cli); e.Reason != interactive.EndExited { |
| + t.Fatalf("A's end %+v", e) |
| + } |
| + waitFor(t, "A's session to end", func() bool { a.mu.Lock(); defer a.mu.Unlock(); return len(a.active) == 0 }) |
| + |
| + // Worker B, as after an agent restart: nothing seen. Its grant is valid |
| + // and before its pickup, but the door has ended the session. |
| + logs := ixCaptureLog(t) |
| + launchB := &ixLaunch{handle: newIxHandle(newIxTerm())} |
| + b := newInteractiveWorker(&grantStore{Store: c.store, key: key, wire: wire}, ixRoutes(ixRoute(ixHost)), launchB, c.pub, "box-a") |
| + var dials atomic.Int32 |
| + dial := b.dial |
| + b.dial = func(ctx context.Context, url, origin string, h http.Header) (*websocket.Conn, error) { |
| + dials.Add(1) |
| + return dial(ctx, url, origin, h) |
| + } |
| + for range 2 { |
| + b.note(rec) |
| + b.pass(context.Background()) |
| + waitFor(t, "B's attempt to end", func() bool { b.mu.Lock(); defer b.mu.Unlock(); return len(b.active) == 0 }) |
| + } |
| + if dials.Load() != 1 || len(launchB.calls()) != 0 { |
| + t.Fatalf("B: %d dials, %d launches; want one dial the door refuses, no launch", dials.Load(), len(launchB.calls())) |
| + } |
| + if n := strings.Count(logs(), id); n != 1 { |
| + t.Fatalf("B logged the refusal %d times:\n%s", n, logs()) |
| + } |
| + if !b.isSeen(id) { |
| + t.Fatal("B did not mark the id seen") |
| + } |
| +} |
| + |
| +// The session worker rides the runs worker's triggers (the request budget: |
| +// nothing polled of its own): every production function that arms the runs |
| +// worker, hooks its note into reconcile or runs its pass does the same for |
| +// the session worker. |
| +func TestInteractiveWorkerIsWiredBesideTheRunsWorker(t *testing.T) { |
| + pairs := map[string]string{"armRunsPass": "armInteractivePass", "withRunsHook": "withInteractiveHook", "runRunsPass": "runInteractivePass"} |
| + found := map[string]int{} |
| + for _, name := range []string{"agent.go", "changeindex.go"} { |
| + f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + calls := map[string]bool{} |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + if c, ok := n.(*ast.CallExpr); ok { |
| + if id, ok := c.Fun.(*ast.Ident); ok { |
| + calls[id.Name] = true |
| + } |
| + } |
| + return true |
| + }) |
| + for runs, sessions := range pairs { |
| + if calls[runs] { |
| + found[runs]++ |
| + if !calls[sessions] { |
| + t.Errorf("%s: %s calls %s but not %s", name, fd.Name.Name, runs, sessions) |
| + } |
| + } |
| + } |
| + } |
| + } |
| + for runs := range pairs { |
| + if found[runs] == 0 { |
| + t.Errorf("no production call of %s found", runs) |
| + } |
| + } |
| +} |
diff --git a/internal/host/lifetime_gating_test.go b/internal/host/lifetime_gating_test.go| index c5ebec904..365f0cbc5 100644 |
| --- a/internal/host/lifetime_gating_test.go |
| +++ b/internal/host/lifetime_gating_test.go |
| @@ -529,7 +529,7 @@ func TestBoxJudgeIsSharedAndGated(t *testing.T) { |
| if n := calls.assigns["boxJudge"]; n != 1 { |
| t.Fatalf("runAgent assigns boxJudge %d times, want once", n) |
| } |
| - for _, callee := range []string{"armMovesPass", "armRunsPass", "fastConvergeLoop", "instancesLoop", "statusLoop", "retentionLoop", "steeringLoop"} { |
| + for _, callee := range []string{"armMovesPass", "armRunsPass", "armInteractivePass", "fastConvergeLoop", "instancesLoop", "statusLoop", "retentionLoop", "steeringLoop"} { |
| if !calls.passes(callee, "boxJudge") { |
| t.Errorf("runAgent's %s call does not pass boxJudge", callee) |
| } |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index ac85d82f1..75c6e60b9 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -43,4 +43,4 @@ plan14-root-reads-region-ha-dead-holder-backoff.tsv 8f6a1865b0abcea9d4fb68232cc2 |
| plan14-root-reads-managed-fleets-1c-451.tsv af326671321edda76c7e6217a47892605a9e3b886fa880ad6d049c2f28f63873 |
| plan14-root-reads-fleet-public-routes.tsv bca6ef741a96b72767b1747789cd01b3111d61b68548cbe368258c31f3d53a2e |
| plan14-root-reads-fleet-routes-followups.tsv 1379d066c8dd2335d95d5f6e9c7bce65ff57f00b2b287a308d9b3f47911ae5e7 |
| -plan14-root-reads-rootfs-apps-6.tsv f02fd204e9316044a993e8c66318a8429555366b3e1a7b5a0388ed4376d334ad |
| +plan14-root-reads-rootfs-apps-6.tsv 75b5bf971620474d35c8cd06aab78f0c4edfc24d925729daa3567bcf369ca644 |
diff --git a/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv b/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv| index de8675138..1e02a976a 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-rootfs-apps-6.tsv |
| @@ -1,7 +1,7 @@ |
| # Census overlay rootfs-apps-6, written by census-propose (#369). census-ruling-rootfs-apps-6, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-rootfs-apps-6.md. |
| -# 24 body, 5 sites, 9 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 25 body, 5 sites, 10 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| # 1 removed: each unit's declaration, or each envelope's directory, is absent from the scanned tree, so its row goes, a frozen declaration is retired as absent, and an envelope is retired. |
| -# 17 new dispositions: 1 reads re-frozen at their disposition with the claim, 16 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +# 28 new dispositions: 1 reads re-frozen at their disposition with the claim, 27 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| @legacy c41d9a1319e7f19435f88127ae64ec2739a24900da6942fe69e710eb6d47e36c internal/activator/activator.go Service.finishStop legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body with a run's settle checked before replication closes, which keeps the stop pending until the run is proven stopped; read sites unchanged, offsets moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: an HA entry (its replica is an HA one, haEntryRep) now releases through releaseHAClean (a new unit on this card) instead of e.rep.Close; when that answers errHostSliceUnproven the stop is kept pending (keepPendingLocked) with the lease held and renewing, and the sweep finishes it once proven; a non-HA entry is unchanged; the same five sites, no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: a forgotten entry's stop is noted for its resident (noteResidentStopLocked: crash or lost lease backs off, any other stop restarts on the next tick) and its ownerDone channel is closed; no read added;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: while the host has a release command's record (a.releaseOps[e.host], running or not proven stopped), replication and the lease stay and the stop is kept pending (keepPendingLocked) until the record's proof; the same five read sites, no read added; only holds a release back;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1.20: while a rootfs worker may run or is a stray (rootfsWorkersLiveLocked, in-memory, read under a.mu), replication and the lease stay and the stop is kept pending (keepPendingLocked) until the workers are proven stopped; the same five read sites, no read added; only holds a release back;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1 (Astra P1): beside the worker check, under the same lock, a stop with a lease stop of its commands outstanding (e.leaseStops) is kept pending, the replica and lease held, and the sweep finishes it once they have returned; the entry is never released while a kill captured for it may still reach its unit; the same five read sites, no read added Task 9 (PF-3): the count is pendingLeaseStopsLocked(e), the sum of e.leaseStops over both one-shot roles (now a map per role, cmd and tty), so a session's lease stop of the tty unit keeps the stop pending, the replica and lease held, as a run's does; the same five read sites, no read added registry:Socket@4068,registry:Socket@4173,whole:Route@4018,whole:Route@4070,whole:Route@4175 9748565e756038b7da9a06daefeb758fae4705ecb8ce400a1d4ea3e5231a7271 |
| @legacy 1f6bcc9cf0f66285a303c9d14a8ac511b721f7941c0fe45c18eeaf5ec7c42662 internal/activator/activator.go Service.installProcLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: the one place a process, its generation and the lease replica are installed on an entry; a resident is put under its lease watch (watchResidentLeaseLocked) at that moment; reads only the entry's route;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a (Call A1, Astra R1 P1-1): the lease watch is installed for every rootfs row (e.route.Rootfs()), not only a resident, so a hibernating rootfs row's run or session is reached at the lease's loss; the same one read of the entry's route; installs nothing else whole:Route@144 cacc399eb6e09be70d3a2ad1774800fb6a252590cebd62dd0e9f369e97275f81 |
| @legacy 2401ee86a2ee7e9138b032f65973c8049d9452d18d2e0c04d21edeea4dcca3d6 internal/activator/activator.go Service.sweepOnce legacy accepted-legacy accepted-legacy;rev3=PROPOSED-seed;basis=census-ruling-FS-R6; registry remains legacy; PROPOSED-plans-2-box-limits: the sweep also narrows an entry's idle window to its account's plan idle through the SetIdleFor hook (never lengthens it; always-on workers and held probe entries are untouched; the hibernate, inflight and held-for-tick guards are unchanged).;rev3=census-ruling-plans-4c-box-throttle;basis=after the worker max_run branch, stops a non-worker entry past the plans continuous-awake ceiling (maxRunFor, passed the row), busy or not, never mid-command (plans 4c). One more whole-row read: the row handed to the hook, as idleFor already is. This bypasses the inflight and held-for-tick protections the idle stop keeps, on purpose: escalated by Astra and ACCEPTED by Paul (census owner), 2026-10-25.;rev3=census-ruling-plans-4d-lapse;basis=stops a live entry the turned-off hook names (never mid-command, never a move's active probe), stands down an exited worker it names instead of restarting it (Astra finding 4), and skips such rows in the due loop and the always-on arm so they are not woken (plans 4d). Four more whole-row reads: the row handed to the hook (a.disabled), as idleFor and maxRunFor already are. Only stops or skips.;rev3=census-ruling-remote-instance-metrics;basis=its two entries-map insertions go through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more call at the top, a.retryOwedMarkers() (harelease.go), which starts at most one background lease.RetryPending pass over owed region HA release markers, off a.mu; the due query, idle, max-run and lapse logic are unchanged; the same 38 sites, no read added; merge of origin/main d7ae1d76: main's change is kept as main has it (census-ruling-remote-instance-metrics: its two entries-map insertions go through putEntryLocked); this branch's change is the same as above; read sites the same 38, offsets moved;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: a resident (Route.Resident) is never stopped for idleness or by the continuous-awake ceiling; the due-wake check is left on Hibernate (comment); stops less, not more;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: an entry whose host has a release record open (the in-memory a.releaseOps[e.host]) is not stopped by its plan's turn-off, by idleness or by the continuous-awake ceiling until the record goes; one more sweep pass, reapReleaseOpsLocked, retries an unproven release's stop (through finishPendingStops); the same 39 read sites, no read added; stops less, not more;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 9 (PF-18): the four checks that left an entry with a run attached alone (e.cmd == nil) now read holdsAttachedLocked(e), a run or a session attached, so a session holds the idle sleep, the plans awake ceiling, the plans turned-off stop and the turned-off worker's stand-down as a run does; in-memory under a.mu; only keeps an entry awake longer; no read added, read sites unchanged registry:Hibernate@10801,registry:Hibernate@14559,registry:Hibernate@23817,registry:Hibernate@5676,registry:Hibernate@7875,registry:Host@23886,registry:Host@23944,registry:Host@24411,registry:Host@24504,registry:Host@25239,registry:Host@25328,registry:Host@26392,registry:Host@26679,registry:Host@26735,registry:NextDue@25194,registry:Status@23833,whole:Route@10803,whole:Route@11662,whole:Route@14561,whole:Route@16494,whole:Route@18204,whole:Route@18394,whole:Route@18687,whole:Route@18859,whole:Route@19006,whole:Route@23217,whole:Route@23993,whole:Route@24908,whole:Route@25248,whole:Route@25255,whole:Route@26207,whole:Route@26508,whole:Route@26712,whole:Route@5487,whole:Route@5678,whole:Route@7708,whole:Route@7877,whole:Route@8070,whole:Route@8533 ddf9a21dc0ae724138b1b0963155d8f555f2ce6982f7e61b9dc05f2bdd80bbe6 |
| @@ -37,10 +37,21 @@ |
| @legacy 6d3fbdea661079d19e104dae75e1fe1943ee5fbaf40435e501b5afd8d4bd2c98 internal/activator/rootfs_service.go Service.residentLeaseLostLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: a census unit now (two whole:Route sites, e.route to stopOneShotsAtLeaseLocked and e.route.Resident()): also returns the one-shot kill funcs of any rootfs entry that is the host's, whatever its state; a hibernating entry gets no stop and no generation kills; in memory only whole:Route@198,whole:Route@218 6266ff6af94cc58e1226f3921da636cc6fa7d365340ecce216f0493d2d7e97a7 |
| @legacy 44b446f87f5f55a32ba63c481687b01c59c7a8c20d2b41ff82b9a37709081399 internal/activator/rootfs_service.go Service.residentLeaseShort legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: a census unit now (two whole:Route sites, e.route to stopOneShotsAtLeaseLocked and e.route.Resident()): stops every one-shot unit that may run, whatever the entry's state, off a.mu; begins a resident's graceful stop only while it is awake, as before; in memory only whole:Route@188,whole:Route@377 c39a0d4aeb53d0608e3c3e95ea3742ef6dab8ea3419a061a3415ffe5c491ecfe |
| @legacy 9d3d5ea17a224dd06eaa558ec8862ef403fe00dbfb483c40f52ff27864872eb9 internal/activator/rootfsenv.go ExecBackend.rootfsTTYVars legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 8, new: a rootfs session environment: ttyVars over the generation launch environment, then rootfsVars with the row canonical socket and dbPath set after the file environment, as rootfsCmdVars does; map composition only registry:Socket@202,whole:Route@163 6f561ab8a1e4a8063afeb0be152cee2f5fbb30d78e3008a2b515bc4aeba9735b |
| +@legacy 3daeabb64386c5c369bf464104882f1c19a66112e29fcd90c29997bbebdc66e0 internal/host/interactive.go interactiveWorker.consider legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: the box's session worker decides one reconcile-noted record (InteractiveSeen): its row from the agent's own registry (owned), for an HA row (rt.HA) only when the activator holds the host awake (HoldsAwake), then the signed grant GET from the deployment store at interactive.GrantKey of the record's own account, app and a session id that passed interactive.ValidID, verified under CARLOS_RELEASE_PUBKEY (VerifyGrant) and matched to the record; it runs as the agent (user carlos), writes nothing, and nothing it reads reaches root registry:HA@181,whole:Route@1751,whole:Route@1755 37cc833b3ca261c129eb1c0e1f966140e57550936a1ae50b42c31a0b01803e8c |
| +@legacy c6851e192e7ecbbcaf506a5a5a7aff21b89bc3d340affe2eaacf62e54a7f315d internal/host/interactive.go interactiveWorker.owned legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: runsWorker.owned's rule for the session worker: the agent's registry row for the record's host, provisioned for the record's account and app and activator-managed; in-memory reads of the row, agent only, nothing reaches root registry:Account@162,registry:App@191,registry:Provisioned@144,whole:Route@130,whole:Route@241,whole:Route@292 6efa21c1510d9f42538d47c49c2111895d3d5cc0226da21161786103a21aa79e |
| +@legacy 69546dd142d35b47f31a59448ef868dd1fd45676c84a5fad4bb665456ec38756 internal/host/interactive.go sessionRun.bridge legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: relays a started session between the console's box door and the session's pty master the agent itself holds (CmdHandle.Terminal, the activator's ptyTerminal): file:Read is a read of that master, at most 32 KiB per frame; writes keystrokes and resizes to it, polls, hangs up, stops and releases through the activator's CmdHandle; agent only, nothing reaches root file:Read@391 06bd6e3b26b7f3e73b42c6c237fe506ce5984524f1616aa9e8df0f91aa438d5a |
| +@legacy d2b0185be4f88ddd8749aa5f06ddc47327e0bea1e5a7f5a91f6404e8a0c39983 internal/host/interactive.go sessionRun.receiveOpen legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: reads the console's first frame on the box door's WebSocket within OpenWait and decodes interactive.Open, normalized and checked (Open.Check); the file:Open sites are the type name interactive.Open and its methods, not a file open; agent only, nothing reaches root file:Open@194,file:Open@265,file:Open@343,file:Open@36,file:Open@422,file:Open@513 71508261339c1285dff476b2bb095e7b821ac586bfd198ef86b1e0c8f7d63557 |
| +@legacy ced2bf6b5c16e765e2b613e649a20c07136b5d1c25a839ac42e1e04bfb08eb61 internal/host/interactive.go sessionRun.serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: refuses over the connection (incarnation from the grant against the record, the app's setting from config.json of the default bundle via appconfig.GetInteractive, an uncommitted import), then RunCmd with spec.TTY {Term, Cols, Rows}, Process and Args exactly as the checked Open names them, on the owned row; root's tty start validates the process or argv itself (Tasks 6 to 8, unchanged); the file:Open site is the interactive.Open parameter type; adds no root input file:Open@32,whole:Route@1551 0dc848ec6db6196485b3f561463dd1c4895acdf4a3df7bdecf6923a83f74b3d0 |
| @legacy 14cec7be2873b15f373f40e319f5c6c61d441f521121499f2a04b331bd3453f3 internal/host/units/carlos-instance-rootfs-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the rootfs tty template, carlos-instance-rootfs-cmd@.service outside named lines held by TestRootfsTTYTemplateEqualsRootfsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit --rootfs tty %I, StandardInput=file:/run/carlos/logs/%I.tty.sock with StandardOutput/StandardError=journal, and RootImage plus the two BindReadOnlyPaths sources under /run/carlos-control/exe/%I/rootfs/tty/ (root-only exe layout) instead of rootfs/cmd/. The rootfs namespace block byte for byte (TestRootfsTemplatesShareOneNamespace), runs as carlos, binds only the instance own and root paths (TestRootfsTemplatesBindOnlyTheInstancesOwnAndRoots). Task 6: POST /tty runtime=rootfs (startRootfsCmd with RoleTTY) starts it through Plan 2's rootfs one-shot path (preflight, validateStagedImage, ensureRootfsExe under rootfs/tty/, jit drop-in and owed reload, post-start MemoryDenyWriteExecute check); its files go only through removeRootfsUnitFiles (stopRootfs and cleanCmdExe with RoleTTY, the sweep) file:external@0 d57f6d6fbe553e5ba5a5762ab2bd72586835ce1db748b67044edd1bf90af6953 |
| @legacy b18625dfcfcaa6d4e0ae128e2b77ad7fb53d0a4206458b43ef4125d248e6ef58 internal/host/units/carlos-instance-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the binary tty template, carlos-instance-cmd@.service outside six named lines held by TestTTYTemplateEqualsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit tty %I (the same root binary as every template), StandardInput=file:/run/carlos/logs/%I.tty.sock replacing the cmd StandardOutput socket (PID 1 opens it as root on the nosymfollow logs mount, as the cmd streams), StandardOutput=journal, StandardError=journal, and BindReadOnlyPaths sources tty-app/tty-live under /run/carlos-control/exe/%I (root-only exe layout, as cmd-app/cmd-live). Same namespace block byte for byte, runs as carlos. Task 6: POST /tty (handleOneShot(RoleTTY), claimAwareLegacy) starts it, after the role lock, the loaded-state refusal and refuseStagedExe; the tty-app/tty-live sources are laid out by ensureCmdExeAt(RoleTTY) and removed by removeCmdExe(RoleTTY) at /stop role=tty and /sweep file:external@0 060295d0956afad52db77dba1988c508cf4289f9b5a18242a206a315145b8e0d |
| @legacy 9491fe16a762f2bfb2e6b288428f67b157b813d01c226917ec4c3366ebffb305 internal/instancectl/cmd.go Server.oneShotStatus legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: handleCmdStatus's body moved whole and made role-aware (it serves GET /cmd/{host} and GET /tty/{host} through handleOneShotStatus(role), both claimAwareLegacy): the same three file:Query sites (the URL query read for the invocation, for parseQuery and for the role check); the role check now refuses any role field but the route's own (role=tty on /cmd and role=cmd on /tty are 400, before any show); the unit shown is UnitName(role, host) or RootfsUnitName(role, host) for runtime=rootfs, a name root builds from a validated host and a route constant; read-only systemctl show, starts and stops nothing; no file read added file:Query@1090,file:Query@384,file:Query@759 9ea847d9a1e6b0e0929f27b27a9ade5c783c0de1ba0d997523c939be8293e701 |
| @legacy 8e00efef4ecab3057d44b14e01fba5aa93e5359ba841c4fea91b57487481202f internal/instanceexec/tty_linux.go receivePTY legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7 (PF-9), new: the trampoline's tty role, run by instance-exec [--rootfs] tty %I as carlos inside the instance's namespace (never root): one recvmsg on its own stdin (the tty unit's StandardInput= socket to the agent), exactly the hello carlos-tty/1 and exactly one SCM_RIGHTS fd (received close-on-exec), else refused with every received fd closed; the one Fstat is of that received fd, which must be a character device of a Unix98 pty slave major (136-143) that answers TCGETS, else refused and closed; it opens, runs and follows no path; the fd becomes only the tenant's stdio and controlling terminal (runTTYInit through runInitChecked, which closes the init's copy after the fork); no root process reads anything new file:Fstat@1454 1099af8a1dc0732b74afbe42bc45ccce6df3db9662ff7dc41f278e2bd4a274ce |
| +@legacy 18a10bcf3209d920c99f0a72c8f96a25be52f391b0d37190d6ed5a31a1427f80 internal/interactive/frames.go Receive legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: package interactive enters the root binary's scope, unchanged (Task 2, reviewed there), because the agent's session worker imports it; Receive reads one WebSocket frame from a connection the agent dialed (file:ReadAll is the frame header reader); nothing root reads file:ReadAll@349 eb3c090baaf5cbdd95d4fc687533d9bc8718a09f2c825dd17aaac560fe7d4258 |
| +@legacy 73e30cba17a190ceb15d043b51f71cd71efced333803bfb166114eedc79d85eb internal/interactive/frames.go handshakeRecorder.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); records the dial's handshake response bytes from the agent's own connection; nothing root reads file:Read@28,file:Read@69 b7a9a92dbc3123e7dce85de78e6a0a9a8c522affb4b66fce729493b85e305062 |
| +@legacy 58fd6f7a9276687c44512a2acc415fc5c89a4f5a9779edf0786e02c2eafca6f5 internal/interactive/grant.go MintToken legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); reads crypto/rand for a console token (the console's caller; the agent never calls it); nothing root reads file:Read@90 3a68f4541e11c18dd6367555a260565a152d0f175e43f763ea70e788e337f094 |
| +@legacy 0d7bb9ecaf1ac28bc128a6507aeb0ca47bd5575f64b0410e20f396887fd4cbc7 internal/interactive/interactive.go Open.Check legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); validates the Open frame's fields in memory; file:Open is the type's name; nothing root reads file:Open@8 85e0b6d5317672f9e959d6cb2640de6e28d48eb333f2a6ce1e5557e15cc32b22 |
| +@legacy ffbd90e0f820dbbd99a5cd53f828ea520ad469522b34ccb67386f69f5a3b71b3 internal/interactive/interactive.go Open.Normalized legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); fills the Open frame's defaults in memory; file:Open is the type's name; nothing root reads file:Open@27,file:Open@8 f72134011675ffc8b37585f99962812cef053e600c54c5216245cad8920c3cce |
| +@legacy 7fa09e38ea17338b467b1cc6ca5e557d2ed77bb0f6477083d17e33484393f8b4 internal/interactive/interactive.go type Open legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); the Open frame's declaration; file:Open is the type's name; reads nothing file:Open@5 ad72d02e636f55e4c1d4b62129780432b5b949672042ec59d4cb7dbfbc027a3b |
| @legacy 42df81763fd67911e0e9dc84bca80d45f90fdc374fda09040eff0e07627f8bc0 internal/activator/cmdunit.go cmdUnit.StopAndSettle legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): asks instance control to stop the unit, then waits; the agent keeps the lease until this is proven; no root decision;rev3=census-ruling-rootfs-apps-2;basis=the stop goes through stopRole with the row instead of Control.Stop with its host, so one Host site goes; for a rootfs row that is the rootfs stop verb's request (StopRootfs) over the same control socket; the proof (stop, cgroup empty, streams drained) is unchanged; no file read added;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 8 (PF-7): stops and proves the unit own role (stopRole and waitRoleCgroupEmpty with u.role, cmd or tty), never a hard-coded cmd; a unit of no one-shot role is refused; after the proof it drains the two streams, or closes the session handoff and master; new sites are the refusal text (rt.Host) and the route registry:Host@216,whole:Route@218,whole:Route@365,whole:Route@517 68abc85a8850ee4e740e177636b40026b5cea4fb3545d2995ccbab6ff05bd0dc |
| @legacy 80d2897553e3f5a31e55ecabdf1da017c7a6f5fbe2adde5a643c0c1a1887a8e1 internal/activator/backend_rootfs.go ExecBackend.startRootfsCmd legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R0.1, R1.4]: new; the agent's first caller of root's existing CmdRootfs (POST /cmd to root's control socket, unchanged). In order: rootfsGates; refuses a partial staged identity (version, path, digest); rootfsControl; prepare(rt, RoleCmd) (the instance's own directories); two stream listeners on the agent's own log sockets (logSocketNamed); the schema-2 launch file for RoleCmd with env alone (writeRootfsLaunchFor, the same writer and the same root reader as the web start's RoleRun file, rootfsLaunchEnv: never the agent's own environment); the caller's exec gate (runExecGate); then CmdRootfs(host, the row's tier memory.max, StagedImage{staged path, version, digest, process}), process being a declared process name root checks against the staged manifest. ErrStagedImage and ErrStartRefused are refusals with no unit; any other error returns a unit to stop and settle. Root validates the staged image and the process itself (instancectl, unchanged); registry:Host sites are log lines, socket and unit names;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: takes a rootfsCmdLaunch, a declared process or an operator's argv, exactly one or refused before anything is laid out; the launch file names the process or cmd, never an argv; CmdRootfs names the image with the process or with the argv in the request body, which root validates against the staged image itself (instancectl, unchanged); new site +registry:Host is that refusal's message; Plan 6 Task 8 (PF-1): takes the role, cmd or tty, and oneShotSinks; refused before anything is laid out unless the role is a one-shot whose I/O matches (a terminal for tty alone), and for tty unless the control channel has the session verbs (TTYControl, else ErrNoTTY); prepare(rt, role); for tty the session pty and its handoff socket on the agent own logs path (openTTY, TTYSocketName) take the place of the two stream listeners; the launch file is the role one (launch.tty.json for tty: schema 2, process console or cmd, never an argv, env alone through rootfsLaunchEnv); a tty starts through TTYControl.TTYRootfs (POST /tty runtime=rootfs; root Task 6 handler validates the staged image and the process or argv itself), a cmd through CmdRootfs as before; the same refusal and may-have-begun handling; -whole:Route is b.tier(rt) read once registry:Host@1135,registry:Host@1299,registry:Host@1428,registry:Host@1645,registry:Host@2062,registry:Host@2211,registry:Host@2274,registry:Host@2542,registry:Host@2870,registry:Host@2996,registry:Host@3094,registry:Host@320,registry:Host@490,registry:Host@685,registry:Host@963,whole:Route@1351,whole:Route@2089,whole:Route@2935,whole:Route@2939,whole:Route@3161,whole:Route@3165,whole:Route@780 9a8131053dfff1c24d5a222612df56c09d2c105234b9a471773243ba88aabfec |
| @legacy a26d326b74fee7875e7b7b462cbb9cef5c275cb7291b6e8634874122fba2fa9e internal/activator/cmd.go Service.RunCmd legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): admits one run against an awake entry under the agent's own lease, fence and swap checks; it starts nothing itself and root validates what it later names;rev3=census-ruling-edge-request-records;basis=passes nil for begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: a carlos run is refused with ErrCmdBusy while a release record of the host is open (a.releaseOps[rt.Host], in-memory), as a run already in flight refuses it; new site +registry:Host (that map lookup); adds a refusal only;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: AfterSettled honoured on every path (called before return on each path that starts no unit, else by the settle that proves the unit gone); a rootfs run is refused as a lost lease (CmdStoppedError StopLeaseLost) when its entry is not under the lease watch (residentWatchedLocked), and, off a.mu, when the replica's in-memory SafeUntil leaves less than oneShotStartLead (oneShotHeadroom); new sites are e.route.Rootfs() and a log line; adds refusals only Task 9 (PF-17): a session (spec.TTY) takes the entry's tty slot and a run its cmd slot (holdSlot), the hold carrying its role (newCmdHold); each is refused only for its own role (holdBusyLocked: ErrCmdBusy or ErrTTYBusy), so a run and a session coexist; a release command (a.releaseOps) refuses a run only, since the session's tty unit is its own; no read added, read sites unchanged file:Prepare@2455,file:Prepare@2489,registry:Host@1502,registry:Host@1865,registry:Host@7461,registry:Host@8697,registry:Kind@437,whole:Route@683,whole:Route@7865,whole:Route@8329,whole:Route@869,whole:Route@8862 8a2e42ff8bb02e61ddbe1ac30e3d9ee68d5fa90c8e537e31646c24d894552663 |
| @@ -57,6 +68,7 @@ internal/activator/prepare.go ExecBackend.prepareKeyedAt legacy accepted-legacy |
| internal/activator/rootfs_service.go Service.residentLeaseLost legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8 (C7): a resident's lost lease marks it and then kills its generations off a.mu (killResidentGens);rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1.10: a resident's lost lease stops its workers (stopRootfsWorkersAtLoss, proven gone) in parallel with killResidentGens; rt is taken under the lock and passed to killResidentGens in place of e.route (the same route); site +whole:Route (that local rt); no file read;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a (Call A1): residentLeaseLostLocked also returns one kill func per one-shot unit that may run; each runs off a.mu in the same WaitGroup as stopRootfsWorkersAtLoss and killResidentGens, which still run only for a resident (gens non-nil); the kills go to root's existing /stop through KillOneShot; no read added whole:Route@137,whole:Route@394 64ce2f74e65941ea2a731518c773cb9b27456f2db298c69ed4e02de375b1777f |
| internal/activator/rootfsrelease.go Service.releaseAdmitLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R1.10]: new; the owner's half of a release's admission under a.mu: refuses while a run holds the cmd unit, and for an awake owner mirrors Swap's exclusions (worker or non-instance kind, a layout other than flat or nested through the existing swapLayout, members, a raised parent, a resize, a cmd start in flight); in-memory only; refusals only;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 9 (PF-17): the busy check is holdBusyLocked(e, RoleCmd) where it was cmdBusyLocked(e): only established cmd-unit holds and cmd-unit lease stops refuse a release command, never a started session, whose tty unit is its own; cmdStartInFlightLocked now also counts a session's start in flight (merge ruling M2), so a release is refused during either role's start window, short and bounded, as swap admission is (fix round 2 ruling: a refusal at admission is not executed and takes the ordinary retry); no read added, read sites unchanged registry:Kind@309,whole:Route@311,whole:Route@390 d1f6ba85b88b217e9d82caa7f033f20f61429bc319f48099e60e3aea37234916 |
| internal/activator/rootfsrelease.go Service.runRelease legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1: new; the one place a release command runs. Refuses while any record of the host is open; skips the row's good build (releaseRan); reads the declared processes (declaredProcesses: the existing staged-manifest read) and refuses on a read error, never treating it as no release; runs only when releaseDue; needs a lease watch and a ReleaseBackend; its gate is the caller's plus the lease's Err and its safety deadline more than releaseStopLead (cmdStopBound, 2 min) away; creates the record under a.mu after releaseAdmitLocked; publishes the generations file and the build state (recordBuild) before anything runs; times out at the manifest's timeout_sec (default, capped at runs.MaxTimeout); ReleaseEnv; a supervisor stops the unit ahead of the lease's safety deadline; StartRelease under the exec gate; polls the unit (root's existing cmd status); stops and settles it (the existing cmd hold's stop, cmdStopBound); only a non-zero exit, a signal or the timeout with the unit proven gone is the build's failure (*ReleaseError); registry:Host sites are the record key and log lines;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 9: newCmdHold takes the hold's role; a release command's hold is instancectl.RoleCmd, the unit it runs in; nothing else changed, no read added registry:Host@184,whole:Route@2955,whole:Route@3184,whole:Route@3672,whole:Route@3701,whole:Route@5749,whole:Route@589,whole:Route@6217,whole:Route@6494,whole:Route@6924,whole:Route@817,whole:Route@902 442d93ec958dea41fe2eb1c49b1600e77450fc54c79a236c9cdd7c613d48f972 |
| +internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites file:Exec@17043,file:Open@1150,file:Statfs@42963,registry:App@11199,whole:Route@11191,whole:Route@27218 aff93cec62fdc1c04c35ec0f51d6f5e8b14bbd21936c038f7ade2f38eb611dcd |
| internal/host/runexec.go runsWorker.execute legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): runs one picked run to its result in the bucket; every root action goes through instance control;rev3=PROPOSED-325;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=emits the run's start and end as member log events through the agent's EventSink; reads unchanged;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a (INV-2): sets CmdSpec.AfterSettled to remove the run's directory (runs.RemoveRunDir under the instance's own directory, as cleanUp did) once the activator has proven no unit of the run runs; finish and cleanUp take removeDir, true only on the incarnation refusal before RunCmd; the directory goes later or at the same point, never earlier; no read added file:Prepare@1905,whole:Route@2916 43bd160066b4d3e7aef00e3891001bc5ffa9a40f597cb6e5cc7215eae2814df9 |
| internal/host/units/carlos-instance-cmd@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the cmd unit template (applied by PID 1 as root; its process runs as carlos): extends the J4 seed pattern to the run role. The template equals the seed template outside named lines, and the template-equality test pins that. Root lays out a staged executable validated by the same refuseStagedExe the seed and generation paths use, then starts this unit, which runs as carlos with the instance's own reach. No new trust of registry, /data or agent-asserted content beyond the seed path;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else file:external@0 925113f4c51c091f0da65c2c67c5902aa35ab37abbe6491ca935820517e8149d |
| internal/host/units/carlos-instance-gen@.service external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5: the same one namespace-block line, TemporaryFileSystem=/dev/pts:ro, as carlos-instance@.service; nothing else file:external@0 0bd25fefd9306449d55e235e9bd8986466bc4cd68ad56b5614d32596ce39c262 |
| @@ -83,10 +95,21 @@ internal/activator/pty_linux.go ptyTerminal.Read legacy accepted-legacy accepted |
| internal/activator/rootfs_service.go Service.residentLeaseLostLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: a census unit now (two whole:Route sites, e.route to stopOneShotsAtLeaseLocked and e.route.Resident()): also returns the one-shot kill funcs of any rootfs entry that is the host's, whatever its state; a hibernating entry gets no stop and no generation kills; in memory only whole:Route@198,whole:Route@218 6266ff6af94cc58e1226f3921da636cc6fa7d365340ecce216f0493d2d7e97a7 |
| internal/activator/rootfs_service.go Service.residentLeaseShort legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: a census unit now (two whole:Route sites, e.route to stopOneShotsAtLeaseLocked and e.route.Resident()): stops every one-shot unit that may run, whatever the entry's state, off a.mu; begins a resident's graceful stop only while it is awake, as before; in memory only whole:Route@188,whole:Route@377 c39a0d4aeb53d0608e3c3e95ea3742ef6dab8ea3419a061a3415ffe5c491ecfe |
| internal/activator/rootfsenv.go ExecBackend.rootfsTTYVars legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 8, new: a rootfs session environment: ttyVars over the generation launch environment, then rootfsVars with the row canonical socket and dbPath set after the file environment, as rootfsCmdVars does; map composition only registry:Socket@202,whole:Route@163 6f561ab8a1e4a8063afeb0be152cee2f5fbb30d78e3008a2b515bc4aeba9735b |
| +internal/host/interactive.go interactiveWorker.consider legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: the box's session worker decides one reconcile-noted record (InteractiveSeen): its row from the agent's own registry (owned), for an HA row (rt.HA) only when the activator holds the host awake (HoldsAwake), then the signed grant GET from the deployment store at interactive.GrantKey of the record's own account, app and a session id that passed interactive.ValidID, verified under CARLOS_RELEASE_PUBKEY (VerifyGrant) and matched to the record; it runs as the agent (user carlos), writes nothing, and nothing it reads reaches root registry:HA@181,whole:Route@1751,whole:Route@1755 37cc833b3ca261c129eb1c0e1f966140e57550936a1ae50b42c31a0b01803e8c |
| +internal/host/interactive.go interactiveWorker.owned legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: runsWorker.owned's rule for the session worker: the agent's registry row for the record's host, provisioned for the record's account and app and activator-managed; in-memory reads of the row, agent only, nothing reaches root registry:Account@162,registry:App@191,registry:Provisioned@144,whole:Route@130,whole:Route@241,whole:Route@292 6efa21c1510d9f42538d47c49c2111895d3d5cc0226da21161786103a21aa79e |
| +internal/host/interactive.go sessionRun.bridge legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: relays a started session between the console's box door and the session's pty master the agent itself holds (CmdHandle.Terminal, the activator's ptyTerminal): file:Read is a read of that master, at most 32 KiB per frame; writes keystrokes and resizes to it, polls, hangs up, stops and releases through the activator's CmdHandle; agent only, nothing reaches root file:Read@391 06bd6e3b26b7f3e73b42c6c237fe506ce5984524f1616aa9e8df0f91aa438d5a |
| +internal/host/interactive.go sessionRun.receiveOpen legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: reads the console's first frame on the box door's WebSocket within OpenWait and decodes interactive.Open, normalized and checked (Open.Check); the file:Open sites are the type name interactive.Open and its methods, not a file open; agent only, nothing reaches root file:Open@194,file:Open@265,file:Open@343,file:Open@36,file:Open@422,file:Open@513 71508261339c1285dff476b2bb095e7b821ac586bfd198ef86b1e0c8f7d63557 |
| +internal/host/interactive.go sessionRun.serve legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12, new: refuses over the connection (incarnation from the grant against the record, the app's setting from config.json of the default bundle via appconfig.GetInteractive, an uncommitted import), then RunCmd with spec.TTY {Term, Cols, Rows}, Process and Args exactly as the checked Open names them, on the owned row; root's tty start validates the process or argv itself (Tasks 6 to 8, unchanged); the file:Open site is the interactive.Open parameter type; adds no root input file:Open@32,whole:Route@1551 0dc848ec6db6196485b3f561463dd1c4895acdf4a3df7bdecf6923a83f74b3d0 |
| internal/host/units/carlos-instance-rootfs-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the rootfs tty template, carlos-instance-rootfs-cmd@.service outside named lines held by TestRootfsTTYTemplateEqualsRootfsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit --rootfs tty %I, StandardInput=file:/run/carlos/logs/%I.tty.sock with StandardOutput/StandardError=journal, and RootImage plus the two BindReadOnlyPaths sources under /run/carlos-control/exe/%I/rootfs/tty/ (root-only exe layout) instead of rootfs/cmd/. The rootfs namespace block byte for byte (TestRootfsTemplatesShareOneNamespace), runs as carlos, binds only the instance own and root paths (TestRootfsTemplatesBindOnlyTheInstancesOwnAndRoots). Task 6: POST /tty runtime=rootfs (startRootfsCmd with RoleTTY) starts it through Plan 2's rootfs one-shot path (preflight, validateStagedImage, ensureRootfsExe under rootfs/tty/, jit drop-in and owed reload, post-start MemoryDenyWriteExecute check); its files go only through removeRootfsUnitFiles (stopRootfs and cleanCmdExe with RoleTTY, the sweep) file:external@0 d57f6d6fbe553e5ba5a5762ab2bd72586835ce1db748b67044edd1bf90af6953 |
| internal/host/units/carlos-instance-tty@.service external legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 5, new: the binary tty template, carlos-instance-cmd@.service outside six named lines held by TestTTYTemplateEqualsCmdOutsideTheNamedLines: Description (tty), ExecStart/ExecStopPost instance-exec/instance-exit tty %I (the same root binary as every template), StandardInput=file:/run/carlos/logs/%I.tty.sock replacing the cmd StandardOutput socket (PID 1 opens it as root on the nosymfollow logs mount, as the cmd streams), StandardOutput=journal, StandardError=journal, and BindReadOnlyPaths sources tty-app/tty-live under /run/carlos-control/exe/%I (root-only exe layout, as cmd-app/cmd-live). Same namespace block byte for byte, runs as carlos. Task 6: POST /tty (handleOneShot(RoleTTY), claimAwareLegacy) starts it, after the role lock, the loaded-state refusal and refuseStagedExe; the tty-app/tty-live sources are laid out by ensureCmdExeAt(RoleTTY) and removed by removeCmdExe(RoleTTY) at /stop role=tty and /sweep file:external@0 060295d0956afad52db77dba1988c508cf4289f9b5a18242a206a315145b8e0d |
| internal/instancectl/cmd.go Server.oneShotStatus legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: handleCmdStatus's body moved whole and made role-aware (it serves GET /cmd/{host} and GET /tty/{host} through handleOneShotStatus(role), both claimAwareLegacy): the same three file:Query sites (the URL query read for the invocation, for parseQuery and for the role check); the role check now refuses any role field but the route's own (role=tty on /cmd and role=cmd on /tty are 400, before any show); the unit shown is UnitName(role, host) or RootfsUnitName(role, host) for runtime=rootfs, a name root builds from a validated host and a route constant; read-only systemctl show, starts and stops nothing; no file read added file:Query@1090,file:Query@384,file:Query@759 9ea847d9a1e6b0e0929f27b27a9ade5c783c0de1ba0d997523c939be8293e701 |
| internal/instanceexec/tty_linux.go receivePTY legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7 (PF-9), new: the trampoline's tty role, run by instance-exec [--rootfs] tty %I as carlos inside the instance's namespace (never root): one recvmsg on its own stdin (the tty unit's StandardInput= socket to the agent), exactly the hello carlos-tty/1 and exactly one SCM_RIGHTS fd (received close-on-exec), else refused with every received fd closed; the one Fstat is of that received fd, which must be a character device of a Unix98 pty slave major (136-143) that answers TCGETS, else refused and closed; it opens, runs and follows no path; the fd becomes only the tenant's stdio and controlling terminal (runTTYInit through runInitChecked, which closes the init's copy after the fork); no root process reads anything new file:Fstat@1454 1099af8a1dc0732b74afbe42bc45ccce6df3db9662ff7dc41f278e2bd4a274ce |
| +internal/interactive/frames.go Receive legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: package interactive enters the root binary's scope, unchanged (Task 2, reviewed there), because the agent's session worker imports it; Receive reads one WebSocket frame from a connection the agent dialed (file:ReadAll is the frame header reader); nothing root reads file:ReadAll@349 eb3c090baaf5cbdd95d4fc687533d9bc8718a09f2c825dd17aaac560fe7d4258 |
| +internal/interactive/frames.go handshakeRecorder.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); records the dial's handshake response bytes from the agent's own connection; nothing root reads file:Read@28,file:Read@69 b7a9a92dbc3123e7dce85de78e6a0a9a8c522affb4b66fce729493b85e305062 |
| +internal/interactive/grant.go MintToken legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); reads crypto/rand for a console token (the console's caller; the agent never calls it); nothing root reads file:Read@90 3a68f4541e11c18dd6367555a260565a152d0f175e43f763ea70e788e337f094 |
| +internal/interactive/interactive.go Open.Check legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); validates the Open frame's fields in memory; file:Open is the type's name; nothing root reads file:Open@8 85e0b6d5317672f9e959d6cb2640de6e28d48eb333f2a6ce1e5557e15cc32b22 |
| +internal/interactive/interactive.go Open.Normalized legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); fills the Open frame's defaults in memory; file:Open is the type's name; nothing root reads file:Open@27,file:Open@8 f72134011675ffc8b37585f99962812cef053e600c54c5216245cad8920c3cce |
| +internal/interactive/interactive.go type Open legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: enters scope unchanged with package interactive (Task 2); the Open frame's declaration; file:Open is the type's name; reads nothing file:Open@5 ad72d02e636f55e4c1d4b62129780432b5b949672042ec59d4cb7dbfbc027a3b |
| internal/activator/cmdunit.go cmdUnit.StopAndSettle legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): asks instance control to stop the unit, then waits; the agent keeps the lease until this is proven; no root decision;rev3=census-ruling-rootfs-apps-2;basis=the stop goes through stopRole with the row instead of Control.Stop with its host, so one Host site goes; for a rootfs row that is the rootfs stop verb's request (StopRootfs) over the same control socket; the proof (stop, cgroup empty, streams drained) is unchanged; no file read added;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 8 (PF-7): stops and proves the unit own role (stopRole and waitRoleCgroupEmpty with u.role, cmd or tty), never a hard-coded cmd; a unit of no one-shot role is refused; after the proof it drains the two streams, or closes the session handoff and master; new sites are the refusal text (rt.Host) and the route registry:Host@216,whole:Route@218,whole:Route@365,whole:Route@517 68abc85a8850ee4e740e177636b40026b5cea4fb3545d2995ccbab6ff05bd0dc |
| internal/activator/backend_rootfs.go ExecBackend.startRootfsCmd legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R, R1 [pf R0.1, R1.4]: new; the agent's first caller of root's existing CmdRootfs (POST /cmd to root's control socket, unchanged). In order: rootfsGates; refuses a partial staged identity (version, path, digest); rootfsControl; prepare(rt, RoleCmd) (the instance's own directories); two stream listeners on the agent's own log sockets (logSocketNamed); the schema-2 launch file for RoleCmd with env alone (writeRootfsLaunchFor, the same writer and the same root reader as the web start's RoleRun file, rootfsLaunchEnv: never the agent's own environment); the caller's exec gate (runExecGate); then CmdRootfs(host, the row's tier memory.max, StagedImage{staged path, version, digest, process}), process being a declared process name root checks against the staged manifest. ErrStagedImage and ErrStartRefused are refusals with no unit; any other error returns a unit to stop and settle. Root validates the staged image and the process itself (instancectl, unchanged); registry:Host sites are log lines, socket and unit names;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: takes a rootfsCmdLaunch, a declared process or an operator's argv, exactly one or refused before anything is laid out; the launch file names the process or cmd, never an argv; CmdRootfs names the image with the process or with the argv in the request body, which root validates against the staged image itself (instancectl, unchanged); new site +registry:Host is that refusal's message; Plan 6 Task 8 (PF-1): takes the role, cmd or tty, and oneShotSinks; refused before anything is laid out unless the role is a one-shot whose I/O matches (a terminal for tty alone), and for tty unless the control channel has the session verbs (TTYControl, else ErrNoTTY); prepare(rt, role); for tty the session pty and its handoff socket on the agent own logs path (openTTY, TTYSocketName) take the place of the two stream listeners; the launch file is the role one (launch.tty.json for tty: schema 2, process console or cmd, never an argv, env alone through rootfsLaunchEnv); a tty starts through TTYControl.TTYRootfs (POST /tty runtime=rootfs; root Task 6 handler validates the staged image and the process or argv itself), a cmd through CmdRootfs as before; the same refusal and may-have-begun handling; -whole:Route is b.tier(rt) read once registry:Host@1135,registry:Host@1299,registry:Host@1428,registry:Host@1645,registry:Host@2062,registry:Host@2211,registry:Host@2274,registry:Host@2542,registry:Host@2870,registry:Host@2996,registry:Host@3094,registry:Host@320,registry:Host@490,registry:Host@685,registry:Host@963,whole:Route@1351,whole:Route@2089,whole:Route@2935,whole:Route@2939,whole:Route@3161,whole:Route@3165,whole:Route@780 9a8131053dfff1c24d5a222612df56c09d2c105234b9a471773243ba88aabfec |
| internal/activator/cmd.go Service.RunCmd legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): admits one run against an awake entry under the agent's own lease, fence and swap checks; it starts nothing itself and root validates what it later names;rev3=census-ruling-edge-request-records;basis=passes nil for begin's new req parameter; no read added;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: a carlos run is refused with ErrCmdBusy while a release record of the host is open (a.releaseOps[rt.Host], in-memory), as a run already in flight refuses it; new site +registry:Host (that map lookup); adds a refusal only;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a: AfterSettled honoured on every path (called before return on each path that starts no unit, else by the settle that proves the unit gone); a rootfs run is refused as a lost lease (CmdStoppedError StopLeaseLost) when its entry is not under the lease watch (residentWatchedLocked), and, off a.mu, when the replica's in-memory SafeUntil leaves less than oneShotStartLead (oneShotHeadroom); new sites are e.route.Rootfs() and a log line; adds refusals only Task 9 (PF-17): a session (spec.TTY) takes the entry's tty slot and a run its cmd slot (holdSlot), the hold carrying its role (newCmdHold); each is refused only for its own role (holdBusyLocked: ErrCmdBusy or ErrTTYBusy), so a run and a session coexist; a release command (a.releaseOps) refuses a run only, since the session's tty unit is its own; no read added, read sites unchanged file:Prepare@2455,file:Prepare@2489,registry:Host@1502,registry:Host@1865,registry:Host@7461,registry:Host@8697,registry:Kind@437,whole:Route@683,whole:Route@7865,whole:Route@8329,whole:Route@869,whole:Route@8862 8a2e42ff8bb02e61ddbe1ac30e3d9ee68d5fa90c8e537e31646c24d894552663 |
| @@ -96,11 +119,12 @@ internal/activator/rootfs_service.go Service.rootfsTick legacy accepted-legacy a |
| @remove internal/instancectl/cmd.go Server.handleCmdStatus |
| @removed internal/instancectl/cmd.go Server.handleCmdStatus H3 census-ruling-rootfs-apps-6;absent;basis=rootfs Plan 6 Task 6: moved whole to Server.oneShotStatus (role-aware; see its claim), not deleted: no check, refusal or validation is lost |
| @coverage . fbc28f10f89cd03cac31bae0d798ae7f707eb7671284a6115abd8c1c214369b6 |
| -@coverage internal/activator 57739010c191b3e5674925faaea8263d1709f64bb1868766bedb51229a9a94ff |
| +@coverage internal/activator 089879d2d79f4193310e975248cdd2ac6c6114162d9caa6ba38db48f6487a658 |
| @coverage internal/appconfig cac8d8ef7538a456d034801c95ce6508a4983e5516b3bbbd302bec0fbafdd479 |
| -@coverage internal/host 69c09eff5b3b87756182f001086b391c02b867e82e8d21ea40722c992fec43a7 |
| +@coverage internal/host d7bb9b20bcf4f304042025e5373c6aefa6d4df179a2d7b7b46a5760cc7a408ca |
| @coverage internal/host/units c3cc4f3b917fdb938f20d406b1704ec54e24553851c298e312056d397d10b0e1 |
| @coverage internal/instancectl 096e845eb71478e8b68726160cff450f8ba850869dae65582dabd25f445527e9 |
| @coverage internal/instanceexec 65f6db1c6bf469f1d19615ec989f54c20de3b73c3c03ae2d677cffbcc60470fd |
| +@coverage internal/interactive b26ea602e245e4011ecc5e4f48c2cac87cdcf6b6a3b038f4c8dc18fa7f59a42d |
| @coverage internal/layout 1527c3b31d87743798002b1ebefcd2cb0dc422a8642f72a3ff8dbefbd2c84d9b |
| @coverage internal/provision b987b9c81cae353279ac80747047e3b29783643bfe39c67167a535f3fd529254 |