console-remote-instances: console pages show instances on other boxes (records + box reports; no remote metrics yet)
Squashed from console-remote-instances into main.
40 files changed,
+4,048
−55
docs/superpowers/notes/census-proposal-console-remote-instances.md+39 −0docs/superpowers/notes/console-remote-instances.md+417 −0internal/console/accountfleet.go+36 −1internal/console/apiinstanceimport.go+1 −0internal/console/apiinstances.go+57 −3internal/console/apiinstances_test.go+1 −1internal/console/apiroutes.go+1 −1internal/console/claim_invariant_world_test.go+3 −0internal/console/claim_purge.go+3 −0internal/console/claim_retire.go+3 −0internal/console/expirypass.go+1 −0internal/console/hostclaimops.go+6 −0internal/console/instancepage.go+9 −2internal/console/lifetimes_create.go+2 −0internal/console/lifetimes_purge.go+1 −0internal/console/lifetimes_retire.go+2 −0internal/console/listquery.go+7 −2internal/console/metricsview.go+105 −1internal/console/overview.go+45 −6internal/console/overview_test.go+3 −0internal/console/ownership.go+1 −0internal/console/perfwiring_test.go+1 −1internal/console/remoteinstances.go+734 −0internal/console/remoteinstances_round1_test.go+300 −0internal/console/remoteinstances_round2_test.go+220 −0internal/console/remoteinstances_round3_test.go+329 −0internal/console/remoteinstances_round4_test.go+274 −0internal/console/remoteinstances_round5_test.go+118 −0internal/console/remoteinstances_round6_test.go+112 −0internal/console/remoteinstances_test.go+778 −0internal/console/seedfinish.go+1 −0internal/console/server.go+219 −23internal/console/server_test.go+3 −0internal/console/templates/app_overview.html+3 −3internal/console/view.go+101 −1internal/console/view_test.go+9 −9internal/provision/console_remote_instances_census_test.go+76 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-console-remote-instances.tsv+25 −0
CI passed — run details
landed from console-remote-instances
diff --git a/docs/superpowers/notes/census-proposal-console-remote-instances.md b/docs/superpowers/notes/census-proposal-console-remote-instances.md| new file mode 100644 |
| index 000000000..2c9edb0c9 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-console-remote-instances.md |
| @@ -0,0 +1,39 @@ |
| +# Census approval: console-remote-instances |
| + |
| +Ruling `census-ruling-console-remote-instances`. Every change below keeps the disposition it already has, so it needs an approval, not a decision. |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/console/accountfleet.go` `Server.assembleAccountFleet` | body | unchanged (9) | Fleet tab: the shared-fleet app count also reads the account's own instance records (per app of the account, under its own prefix, region not a fleet placement); the registry read is unchanged. | |
| +| `internal/console/apiinstances.go` `Server.healthByHost` | body | unchanged (12) | Takes only the caller's ownership start per host (sinceByHost): readings only from samples at or after it, via ownerAppMetricsFrom. The awake set, the box pin and the until window are gone. Registry reads unchanged. | |
| +| `internal/console/apiroutes.go` `Server.handleAPIRoutes` | body | unchanged (33) | Passes nil for healthByHost's ownership-start argument; nothing else. | |
| +| `internal/console/claim_retire.go` `Server.retireClaimHostRecord` | body | unchanged (1) | Notes the app in the console's in-memory deletion log (noteRecordDeletion, which also invalidates the pages' held box reports) before retiring a record, for the canary-retire guard; the retire itself is unchanged. | |
| +| `internal/console/instancepage.go` `Server.handleAppInstance` | body | unchanged (6) | A remote row (no local registry row) runs none of the hostname-keyed box joins (layout, rollout, updates): it shows only what its row brought through remoteFacts, aliases included. Local rows read layout, rollout join and ListAliases as before. | |
| +| `internal/console/metricsview.go` `buildUnitRows` | body | unchanged (2) | Each unit row also keeps its raw per-sample readings (float32 CPU, int64 memory) so an owner's graph can be redrawn from only their samples; reads nothing new. | |
| +| `internal/console/metricsview.go` `type UnitRow` | body | unchanged (1) | Two unexported fields carrying those raw per-sample readings; schema only. | |
| +| `internal/console/server.go` `Server.channelHosts` | body | unchanged (4) | Canary-retire guard also counts the account's instance records (ListRecordsStrict under the lifetime judge, listRecordsStrict) and sidecar records (listed, then each read with GetSidecarRecord; any read error refuses) naming the channel; with none, it refuses unless the app has settled (retireUnsettled). The registry read is as on main. Fails closed. | |
| +| `internal/console/templates/app_overview.html` `external` | body | unchanged (1) | Running tile does not claim Served when a route's state is unknown and reads the existing 'no data right now' when every instance's state is unknown; Web addresses tile reads 'no data right now' instead of 'DNS & certs OK' for a domain with no reading; display only. | |
| +| `internal/console/apiinstances.go` `Server.instanceHealth` | sites | +whole:Route ×3 | Records with no local registry row get health only from remoteFacts (a box report whose rollout entry names the record's own account and app, generated after the record was created): awake is Running, held down is Failed, transient or unidentified is Can't tell right now. No metrics readings at all and no registry.Route literal for them. Local records unchanged. | |
| +| `internal/console/view.go` `Assemble` | sites | +registry:Host, +whole:Route | Collects the set of local registry hosts (rt.Host) so a record host the registry has gets no remote row (its record's created_at bounds the local row's metrics history); adds rows from the account's records and remoteFacts when given a remote source. | |
| + |
| +Envelopes re-pinned: `internal/console`, `internal/console/templates`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Escalate if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. An escalation goes to the census owner as a decision. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/console/accountfleet.go` `Server.assembleAccountFleet`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| +- `internal/console/apiinstances.go` `Server.healthByHost`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| +- `internal/console/apiroutes.go` `Server.handleAPIRoutes`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| +- `internal/console/claim_retire.go` `Server.retireClaimHostRecord`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/console/instancepage.go` `Server.handleAppInstance`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=merge-ruling-2;basis=Instance page adds updates view from rollout join; browser rendering remains legacy. |
| +- `internal/console/metricsview.go` `buildUnitRows`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/console/metricsview.go` `type UnitRow`: diagnostic, task H3. Basis: schema-only |
| +- `internal/console/server.go` `Server.channelHosts`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| +- `internal/console/templates/app_overview.html` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/console/apiinstances.go` `Server.instanceHealth`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| +- `internal/console/view.go` `Assemble`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-perf-1;basis=takes the request context instead of context.Background() and wraps the registry List in a perf db span (perf.SpanContext); the same registry and store reads, no read added |
| + |
| +Seal: `da85f1ae6035c36915225c78195aac28ca6f7263d21e1dc6d20c10cfb78fc600` → `129e42ead28394976233059b786097bbd42654afee5caa54f24ed17621181fe3`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-console-remote-instances.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/console-remote-instances.md b/docs/superpowers/notes/console-remote-instances.md| new file mode 100644 |
| index 000000000..2c85af005 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/console-remote-instances.md |
| @@ -0,0 +1,417 @@ |
| +# Console app pages: instances on other boxes |
| + |
| +Branch `console-remote-instances`, 2026-10-25. Console only: no wire |
| +change, no box release. |
| + |
| +## The problem |
| + |
| +Every app page and the account app list built their instance rows from one |
| +place: `Assemble`, which opened the console box's own `/data/registry.db`. |
| +An instance whose route lives on another box was invisible. Moving an |
| +account's instances to another region (or creating one there) left its app |
| +pages saying "No instances yet", with no metrics and a 404 on each |
| +instance page. A comment in `apistatusinstances.go` already described the |
| +trap and called it inert because production was single-box. It stopped |
| +being inert when the AU and UK boxes started hosting instances. |
| + |
| +## The fix |
| + |
| +`Assemble` takes an optional remote source. Page views build one with |
| +`Server.remoteSource` (`internal/console/remoteinstances.go`): |
| + |
| +1. **Rows.** For each of the viewed account's apps, the app's instance |
| + records are read, and each record whose host has no row in the console |
| + box's registry becomes a `RouteView` (plus its parallel `DomainView`). |
| + A host the registry has, under any account, keeps its local row: the |
| + local row is authoritative for Status, Unit, Backing, Caps and the |
| + mismatch review. Rows stay in host order. |
| +2. **Live state.** Version, database size, the host's own DNS and |
| + certificate reading, the custom domains routed to it, and whether it is |
| + awake come from the box reports (`status/boxes/*.json`). A remote row's |
| + Status is `ready` when a fresh box reports the host, and `pending` |
| + ("Setting up") when every box was read and none does. Its process state |
| + is known only from a report whose rollout names this account and app. |
| + Without one (an incomplete read, a record on a customer fleet, or an |
| + older box's report that names no tenant) the row's health is "Can't tell |
| + right now", the console's existing wording, and the Overview verdict |
| + says the same. It is never guessed as Asleep, Not responding or Serving, |
| + and a static-only app is not "Served" or "All good" on no evidence. A |
| + host the box reports held down after a failed hold-mode build |
| + (`AttemptDown`) is "Failed", the local rows' word, and makes the |
| + Overview "Needs attention"; a host mid-start or mid-stop (`Transient`) |
| + is "Can't tell right now", never healthy sleep. |
| +3. **Metrics.** A remote row joins readings only from the one box whose |
| + report was accepted for it and names this account and app |
| + (`RouteView.metricsBox`, enforced in `ownerAppMetricsFrom`). A row with |
| + no such report joins none. The host name alone is not this tenant's: |
| + another box may serve the same name for someone else, and its samples |
| + must not land here. A remote row carries no `Unit`, so the allowlist |
| + gains the host and nothing a record can name. `carlos instances list` |
| + applies the same rule. |
| + |
| + Readings are also bounded in time by the record's `created_at`. A unit |
| + name derives from the hostname, and a hostname can have had another |
| + tenant earlier in the 48-hour window, on the same box. Graphs are redrawn |
| + from the owner's samples only (the memory graph scaled to the owner's own |
| + peak), a current sample older than `created_at` is not shown, and a |
| + remote row with no `created_at` shows nothing. The same leak existed for |
| + local rows (a reused hostname on the console's box), so local rows with |
| + an instance record are bounded by that record too, and a provisioned |
| + local row whose record cannot be read (a failed listing, an unreadable |
| + record) has an unknown start and shows nothing. Only a hand route with |
| + no record keeps its whole window, as before: no record says when its |
| + tenancy began. The bound reads only the record, never the registry's |
| + `created_at` column. The metrics box label and the status box label |
| + are the same (`status.Label(machineID)` on platform boxes); if they ever |
| + differed, remote rows would lose their readings, not gain someone |
| + else's. |
| + |
| +### The tenant boundary |
| + |
| +- A remote row exists only for a record under `apps/<viewed account>/<app>/` |
| + whose body names that account and app (`provision.GetRecord` checks the |
| + path; `addRemoteRows` checks again). |
| +- The box maps are keyed by host and carry no tenant. They are joined only |
| + for hosts this account's records name, and a box whose rollout report |
| + names another account or app for the host is not joined at all (the R18 |
| + rule `boxJoin.rollout` already applies). When two fresh boxes report one |
| + host (a move in flight), a report naming this tenant beats one naming |
| + none, then the freshest wins. The page shows one row. |
| +- `assembleOverview`'s cross-account guard is unchanged: every count still |
| + skips rows whose `Account` is not the viewed account, and remote rows are |
| + stamped with it only after the checks above. |
| + |
| +## Page by page |
| + |
| +| Page | Change | |
| +|---|---| |
| +| Account app list | Remote rows count: URL, "Deployed", version. | |
| +| Overview | All tiles, the verdict and the flow diagram see remote rows. The Database tile reads the shared box-report read; a remote row's size comes from the one report it joined. | |
| +| Running | Remote rows with health from the sweep, or from the box's "awake" when the sweep has no sample yet. No restart button on remote rows. | |
| +| Instance page | Finds remote hosts (no 404). Aliases come from the box report. | |
| +| Deployments, Releases | Counts and canary followers include remote rows. | |
| +| Settings, Domains | Remote hosts are listed with the box's DNS status and certificate date. | |
| +| Fleet tab | "Apps on the shared fleet" also counts apps with a record not placed on a customer fleet. | |
| +| `channelHosts` | The canary-retire guard also counts instance and sidecar records whose channel matches, and refuses while the app has not settled (Round 3, below). They are read strictly and live from the bucket, never through the record view, because this is the reader whose "nobody" deletes a pointer. A failed listing, a listed record that will not read (even one deleted between the listing and the read), or more records than the cap refuses the retire. | |
| +| `carlos instances list` | A record with no local row takes its health from its box report and the sweep, instead of always "Setting up". Same cause, same fix. | |
| + |
| +## What stays local, on purpose |
| + |
| +- **Route status** (`issuing`, `failed`, `last_error`) for remote rows. The |
| + box report does not carry it, so a remote row is `ready` or "Setting up" |
| + as above. An additive `route_status` map in `BoxMetrics` would close this |
| + but needs a box release. |
| +- **The account-mismatch banner.** `appAccountReview` is about local rows |
| + stamped with another account, which only the console box's registry can |
| + show. Its two whole-app claims now count remote rows: "No instances yet" |
| + is not shown while the app has remote instances, and "this app is not |
| + deploying" (`AllMismatched`) needs no remote instances either. |
| +- **The restart button.** `handleBrowserRestart` acts on the console box's |
| + registry. Remote rows are not restartable from the page until the button |
| + goes through the bucket `restart-scope` door. `carlos restart --host` |
| + already works for any box. |
| +- Customer fleets, `appPlacementSection`, `carlos routes` and the plan-cap |
| + checks (`onOwnBoxes`) are unchanged. |
| +- **Remote sidecars** do not get rows (sidecar records are not read for the |
| + pages). `channelHosts` does count them. |
| +- **Hand routes on other boxes with no record** are still not shown. The |
| + edges files' per-host `account` and `app` could cover them later. |
| + |
| +## `carlos status --instances` and economics |
| + |
| +Not the same fix, so not in this branch. `status --instances`, |
| +`censusPass`, `fleetMeters` and `statementsPass` attribute usage by joining |
| +fleet-wide readings to the console box's registry, so a remote tenant's |
| +usage reads as platform overhead. That is a billing question and wants its |
| +own design (the edges files already carry `account` and `app` per host). It |
| +is filed as an amadan discussion. |
| + |
| +## Request budget |
| + |
| +- **Steady state, nothing changing:** 0 new requests per box per day and 0 |
| + new console requests. No loop, no poll, no box change. |
| +- **Per page view (people browsing only):** |
| + - Records: 0 when the change-index record view is armed and its latest |
| + snapshot is Complete (the flagship console). The page reads the |
| + snapshot without refreshing it; the run and seed sweeps keep it within a |
| + pass. Unarmed: 1 LIST plus 1 GET per record of the app (local rows read |
| + their record too, for the metrics bound), the read the Logs tab always |
| + made. There is no cap: every record is read, so no instance is ever |
| + dropped from the pages. |
| + - Box reports and edges files: 1 LIST plus 1 GET per box each, held console-wide for 60 seconds |
| + (10 seconds after a failed or incomplete read), timed from when the load |
| + finished. One load at a time; a view waiting behind a slow load stops |
| + waiting when its own request ends. Boxes rewrite their reports every five |
| + minutes, so nothing is lost. That caps it at one read a minute however |
| + many people browse: at 4 boxes, at most 5 requests a minute and 7,200 a |
| + day under continuous browsing, 0 when idle. The Overview's Database tile |
| + used to make this read on every view; it now shares the cached one, so |
| + the Overview costs less than before. |
| + - Metrics: unchanged (shared in-process cache). |
| + - `channelHosts`: 1 LIST plus 1 GET per instance record, plus the same for |
| + sidecar records, per canary create or retire; when no record names the |
| + channel, 2 modification-time LISTs, one console audit query and the |
| + shared box-report read. Write doors only. |
| +- **Pinned by `TestRemoteInstanceRequestBudget`:** an armed Overview view |
| + makes 1 LIST and 2 GETs of box reports (two boxes) and no record reads; a |
| + second Overview, Deployments and the account app list within the minute |
| + make none; after the minute the Overview reads once more; unarmed, the |
| + Overview makes 1 record LIST and 1 GET. The Running tab's region note |
| + (`appDefault` through `liveEdges`), the instance page's rollout join and |
| + Settings' domain readings make box-report reads of their own that predate |
| + this change and are unchanged. |
| + |
| +## Tests |
| + |
| +`internal/console/remoteinstances_test.go`. Two boxes and one bucket: |
| +instances are created through the console's create door, minted by each |
| +box's `provision.Reconcile`, reported by `status.CollectBox` over each box's |
| +own registry and written with `status.WriteBox`, with a metrics chunk in the |
| +sweep's shape. Pages are driven through the HTTP server with a real |
| +session. Covered: account home, Overview tiles, Running, the instance page, |
| +Deployments, Settings domains, the Fleet count and `instances list`; a |
| +same-named app in another account on the same box, report and metrics chunk |
| +(nothing leaks, either way round); the local row winning during a move; a |
| +report naming another tenant; stale and incomplete reads; canary retire |
| +refused for a remote follower and fail-closed on an unreadable record; |
| +`channelHosts` over instance and sidecar records and failing listings; and |
| +the request budget. |
| + |
| +The rollout report in the test is built from each box's own registry rows, |
| +because the real one comes from the agent's scheduler, which the console |
| +package cannot run. |
| + |
| +Mutations run against the account filter, the R18 check, the local-row |
| +rule, the records' account scope, every branch of `channelHosts` and the |
| +cache were all caught. One survivor is equivalent: `awake` is only ever set |
| +from a rollout entry, which always sets `tenantKnown`. |
| + |
| +## Round 1 review (Astra, f2b993c3) |
| + |
| +Four findings, all fixed, each with a test that failed on f2b993c3 |
| +(`internal/console/remoteinstances_round1_test.go`): |
| + |
| +1. A rejected report's readings still joined, because the metrics |
| + allowlist took the host name alone. Readings are now pinned to the |
| + accepted, tenant-named report's box (Metrics, above). |
| +2. Unknown remote state rendered as Asleep, Not responding or Serving. It |
| + now renders "Can't tell right now" (Running row, instance page, `carlos |
| + instances list`), counts as neither up nor asleep, and the Overview |
| + verdict and tile say they can't tell. |
| +3. A load that timed out was published already expired. Reads are now |
| + timed from completion, incomplete reads get the failure TTL, and waiting |
| + is cancellable. |
| +4. The 500-record cap silently dropped instances. The page reader now |
| + reads every record, and only the records it shows. |
| + |
| +## Round 2 review (Astra, 02edd585) |
| + |
| +Three findings, all fixed, each with a test that failed on 02edd585 |
| +(`internal/console/remoteinstances_round2_test.go`): |
| + |
| +1. A previous tenant's metrics history under the same hostname reached the |
| + new owner's graphs. Readings are bounded by the record's `created_at` |
| + (Metrics, above), local rows included. |
| +2. A remote instance held down after a failed hold-mode build read as |
| + healthy "Asleep". It now reads "Failed" and counts as needing attention; |
| + a transient one reads "Can't tell right now". Astra's note that a |
| + static-only app with unknown remote state still read "All good" and |
| + "Served" is fixed with it. |
| +3. (Superseded by the simpler rule in Round 3, below.) Canary retire |
| + missed a remote follower whose record had moved to |
| + another channel but whose box had not converged. Box reports do not |
| + carry a host's channel, so the guard uses builds and time. A record on |
| + another box is a possible follower of the retiring channel when a fresh |
| + report of its box, naming this account and app, still shows the host on |
| + the retiring channel's build (and its new channel points elsewhere), |
| + whatever the record's age; or when the record changed within |
| + `channelSettle` (15 minutes), or has no modification time, unless such a |
| + report shows the host on its new channel's own build. When both channels |
| + point at one build no report can tell them apart, and only the window |
| + decides. An unreadable retiring pointer, a store without modification |
| + times or a failed listing refuses. Fifteen |
| + minutes is three status snapshot periods, the fleet's own staleness |
| + rule (`status.BoxStale`): boxes converge record changes within seconds |
| + of the serial bump, and one that has not done so in that time is one the |
| + fleet already treats as dark. The guard is deliberately conservative: a |
| + remote record created or edited in the last 15 minutes, with no fresh |
| + report yet, also holds a retire back, and the refusal names it with the |
| + existing "still has a host following it" wording. Local hosts are read |
| + off their registry row and are never held by the window. A store that |
| + cannot list modification times (both real stores can) refuses. |
| + |
| +The Codex census review of the round 2 tip (d09ea830) escalated four |
| +gaps in these fixes, all closed before CI: an unknown local start fell |
| +back to the whole window; a record missing from the modification-time |
| +listing counted as settled; an unreadable retiring pointer read as "no |
| +build"; and record age alone was taken as convergence even while the box |
| +reported the retiring build. |
| + |
| +## Round 3 review (Astra, 18b5884b) |
| + |
| +Paul ruled to keep the 15-minute window for the same-build case. Astra's |
| +remaining findings were fixed, and the retire guard was simplified to one |
| +conservative rule. |
| + |
| +1. A box report with no tenant identity for a host (no rollout entry) now |
| + contributes nothing: no version, size, domains, certificate date or |
| + readings. The host's state is "Can't tell right now", and it is never |
| + "Setting up" while some box serves it. The Web addresses tile no longer |
| + calls a domain with no reading "DNS & certs OK"; it says the existing |
| + "no data right now". A held-down instance with a sample from before its |
| + failure is no longer counted as reporting. |
| +2. The retire guard no longer tries to prove convergence from builds. |
| + Retiring channel C of an app is allowed only when no route on the |
| + console's box and no instance or sidecar record names C, and the app has |
| + settled: |
| + - no record was created or changed in the last `channelSettle` (15 |
| + minutes), and none is missing from the modification-time listing or |
| + listed with no modification time; |
| + - no record was deleted in that time. The change index carries no |
| + times, so deletions are dated by the console itself: every record |
| + deletion the console makes (`retireHostRecord`, `retireClaimHostRecord` |
| + including claim recovery, the ordinary delete's `deleteRead`, seed |
| + cleanup's `finishSeedOnce`, the owner's purge, the claim purge and |
| + the temporary-app expiry purge) notes the app in memory before deleting |
| + anything (a note that cannot fail to be |
| + written, unlike the best-effort audit row). Memory does not survive a |
| + restart, so a console refuses every retire for `channelSettle` after |
| + it starts. The audit log is read as well, and an unreadable one, or |
| + one too busy to look back that far, counts as a recent deletion; |
| + - every box report was read; and |
| + - no fresh box report names this account and app for a host that no |
| + record names. That covers a deletion made behind the console's back, |
| + and a route a box has not yet dropped after its record went. It also |
| + holds a retire for an app with a hand route on another box, which |
| + could be following the channel and whose channel nobody can see. |
| + |
| + Records of hosts on the console's own box count like any other, so a |
| + local route never stands in for a remote copy. The refusal is the |
| + existing "Could not verify no hosts follow this channel — try again." |
| + sentence, shown as a flash. A clearer sentence that names the wait would |
| + be new copy, for Luna. The cost: a retire right after any record change, |
| + or in the first 15 minutes after a console restart, waits up to 15 |
| + minutes. A record deleted directly from the bucket, behind every |
| + console door, is caught only while a box still reports its host. |
| + |
| +## Round 4 review (Astra, d8f11e4f) |
| + |
| +1. **Successor samples.** A remote row's readings are now bounded on both |
| + sides: from the record's `created_at` up to when the box report it joined |
| + observed the host as this account's: the generation of the box report |
| + whose rollout entry names this account and app. An identity from the |
| + edges file alone joins no readings at all: the box rewrites that file |
| + only when something changes and publishes it independently of its |
| + report, so nothing dates when its owner last held. A |
| + hostname can change hands on the same box while the console still holds |
| + the old ownership, and a newer sample may then be the successor's. The |
| + current reading is the newest sample inside the window, and nothing at |
| + all if that sample is older than the metrics fresh window (8 minutes). A |
| + remote row's reading therefore lags by up to one status snapshot period |
| + (5 minutes). A report generated before the record existed |
| + joins nothing. Every console deletion also invalidates the held box |
| + reports (a load already in flight cannot put its older result back) and makes the pages read that app's records from the bucket, not |
| + the record view's snapshot, for `channelSettle`. |
| +2. **Records created between the retire listings.** The modification-time |
| + listing refuses any record key the follower read did not see. There is |
| + no lock that record writes take (the app-mutation runner is a claim-mode |
| + admission, not a lock), so the retire door takes the app's record keys |
| + and modification times before its check and again just before deleting |
| + the pointer, and refuses on any difference. The delete is conditional on |
| + the pointer the check read, re-read just before, so a promotion or a |
| + removal meanwhile refuses. A record written in the instant between that |
| + last comparison and the delete reaches its box only after the serial |
| + bump, by which time the pointer is gone: no different from creating an |
| + instance on a channel nobody promoted, which the create door allows. No |
| + restore is attempted after the delete: the store cannot tell "deleted the |
| + revision read" from "already gone", so putting bytes back could |
| + resurrect a pointer someone else removed. |
| +3. **Identity for every route kind.** The rollout report covers only the |
| + routes the rollout manages (never statics, non-hibernating instances or |
| + unit-backed routes). Each box's edges file publishes the account and app |
| + that own every host it serves. It is read with the box reports, in the |
| + same cached load, and identifies the hosts the rollout does not cover: |
| + their rows show the box's version, size, domains and status, but only |
| + once that one record has been read live from the bucket with the same |
| + `created_at` (a record that exists now means no successor can hold the |
| + hostname, whichever console deleted anything). A rollout entry that |
| + names no tenant lends such a host no process state. Their |
| + readings do not join (above), so an instance identified this way reads |
| + "Can't tell right now" for health; a static site, served with no |
| + process, reads "Serving". |
| + Where both sources speak and disagree, the host has no identity to join, |
| + but the retire guard still counts either source naming the app as a |
| + possible follower. |
| + Reports with no identity still contribute nothing. The test helper now |
| + writes rollout entries by production's `rollout.Managed` rule, and |
| + writes an edges file in the producer's shape. |
| + |
| +Request budget change: the cached load also lists and reads |
| +`control/edges/` (1 LIST plus 1 GET per box), at most once a minute |
| +console-wide. |
| + |
| +## Round 5 review (Astra, 59c2cd61): shrink, by ruling |
| + |
| +Each round's P1 had come from the previous round's new path, so the |
| +coordinator ruled to remove paths rather than patch them. |
| + |
| +1. **One accessor.** Every page, API answer and check learns remote facts |
| + through `remoteFacts(acct, app)` (`appFacts`): `host(record)` is the one |
| + report that may be joined to a record, and `complete`, `seen` and |
| + `unrecorded` answer the rest. Nothing else folds or reads box reports |
| + for a remote host. `TestRemoteFactsOneAccessor` parses the package and |
| + fails on any other caller. The instance page of a remote host runs none |
| + of the hostname-keyed box joins (layout, rollout, updates), whose tenant |
| + rules are weaker; it shows what the row brought. |
| +2. **The edges-file identity path from round 4 is gone.** Identity is the |
| + record plus a box report entry (rollout) naming the same account and |
| + app, generated after the record's creation. Anything else is unknown. |
| + Static sites and instances that never sleep, which the rollout report |
| + does not cover, show the record's facts and "Can't tell right now" for |
| + live state. Their metadata (version, size, domains) does not join. |
| +3. **Retire inventory.** The records, the console box's routes, and the |
| + box reports' hosts of the app (by their rollout entries). Any unreadable |
| + or incomplete source refuses, and a box report naming a host of the app |
| + that no record names refuses. |
| + |
| +The round 4 notes above about the edges file, edges-only identities, |
| +`fromEdges` and live record confirmation describe code that no longer |
| +exists. The budget line for `control/edges/` is void: the cached load |
| +reads `status/boxes/` only, as before round 4. |
| + |
| + |
| +## Round 6 review (Astra, 9788f4d1): no remote metrics, held slot reads |
| + |
| +1. **Remote rows take no metrics.** Astra found that a predecessor's |
| + samples could still join a remote row when they were taken after the |
| + record's creation. The coordinator ruled to cut remote metrics rather |
| + than bound them again. A row for an instance on another box shows no |
| + CPU, memory or graphs, and uses the existing no-data wording. Its |
| + health comes from the rollout entry alone: awake is Running, held down |
| + is Failed, and transient or unidentified is "Can't tell right now". |
| + The box pin (`metricsBox`), the upper bound (`until`) and |
| + `windowReading` are deleted. `appResourceMetrics` skips remote rows, |
| + and `instanceHealth` gives remote records no readings. Local rows keep |
| + their readings and their record-bounded history (`since`). |
| + `TestRemoteRowsNeverCarrySamples` puts a fresh sample of the remote |
| + unit on every box and fails if any remote row carries one. The |
| + Metrics item at the top of this note and the round 1 to 4 metrics |
| + fixes describe code that no longer exists. |
| +2. **Held record reads.** With lifetimes on, each judged record read also |
| + reads the host's incarnation slot, live, on every page view. Now |
| + `pageRecords` holds each app's judged read in the box-report cache for |
| + `boxReportTTL`, so a page view within the minute makes no request for |
| + records, slots or the listing, armed or not. `invalidate`, which every |
| + deleting path reaches through `noteRecordDeletion`, drops the held |
| + reads. `TestRemoteInstanceRequestBudget` now runs with lifetimes on and |
| + counts slot GETs: one per remote record on the first view, none within |
| + the minute, and one again after it. Unarmed, the LIST and record GETs |
| + come once a minute too. `TestHeldRecordReadExpiresAfterTheMinute` pins |
| + the expiry. Main's whole-session perf count (`TestPerfSessionS3Requests`) |
| + is 994 on this branch, against main's 1000. |
| + Residual: a record created, or a lifetime that ends without a deletion |
| + by this console, shows on the pages up to a minute late. That is the |
| + same lag the box reports already have, and only the page rows read this |
| + way. The retire guard and the deleting paths read live. |
| +3. **Detach and recovery bypass the deletion evidence (P2).** Filed as |
| + discussion #415. |
diff --git a/internal/console/accountfleet.go b/internal/console/accountfleet.go| index ab2dd6327..75d9a0ce4 100644 |
| --- a/internal/console/accountfleet.go |
| +++ b/internal/console/accountfleet.go |
| @@ -144,9 +144,44 @@ func (s *Server) assembleAccountFleet(ctx context.Context, acct *Account) (card |
| platformApps[rt.App] = true |
| } |
| } |
| + // The console box's registry holds only the routes on this box. An |
| + // app whose instances run on the shared fleet's other boxes is |
| + // counted from its instance records, the same rule: a record not |
| + // placed on a customer fleet runs on the shared fleet. Records are |
| + // read per app of THIS account, under its own prefix, so nothing of |
| + // another account's can be counted. |
| + known := true |
| + if apps, err := s.store.AppsIn(acct.ID); err != nil { |
| + log.Printf("console: account fleet %s: apps: %v", acct.Sqid, err) |
| + known = false |
| + } else { |
| + for _, app := range apps { |
| + if platformApps[app] { |
| + continue |
| + } |
| + recs, err := s.pageRecords(ctx, acct.Sqid, app) |
| + if err != nil { |
| + log.Printf("console: account fleet %s: records of %s: %v", acct.Sqid, app, err) |
| + known = false |
| + continue |
| + } |
| + for _, rec := range recs { |
| + if rec.Account != acct.Sqid || rec.App != app { |
| + continue |
| + } |
| + if _, placed := registry.FleetPlacement(rec.Region); !placed { |
| + platformApps[app] = true |
| + break |
| + } |
| + } |
| + } |
| + } |
| + if !known && warn == "" { |
| + warn = "Could not read where your apps are running." |
| + } |
| card.PlatformApps = len(platformApps) |
| card.Active = card.PlatformApps > 0 |
| - card.PlacementKnown = true |
| + card.PlacementKnown = known |
| } |
| rows, err := reg.ListFleets() |
diff --git a/internal/console/apiinstanceimport.go b/internal/console/apiinstanceimport.go| index 2db5e622d..333be8355 100644 |
| --- a/internal/console/apiinstanceimport.go |
| +++ b/internal/console/apiinstanceimport.go |
| @@ -1080,6 +1080,7 @@ func (s *Server) deleteRead(w http.ResponseWriter, r *http.Request, acct *Accoun |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| defer cancel() |
| + s.noteRecordDeletion(acct.Sqid, app, time.Now()) // the canary-retire guard's evidence, first |
| var err error |
| if lifetimesUnit(ctx) { |
| // Admitted on: a retirement through the tombstone, bound to this |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index ebe0d33e6..c56015417 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -282,7 +282,58 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma |
| unitByHost[rec.Host] = rt.Unit |
| } |
| } |
| - for h, word := range s.healthByHost(ctx, routeFor) { |
| + // A record whose route is on another box has no row here. Its health |
| + // comes from the box that reports it, the same join the app pages make |
| + // (remoteinstances.go): only a report whose rollout names this record's |
| + // own account and app. It takes no metrics readings at all: the word |
| + // comes from the rollout's awake, down and transient alone. A record no |
| + // box reports stays "Setting up" when every box was read; when the read |
| + // was incomplete, the record is placed on a customer fleet, or the only |
| + // report names no tenant, its state is unknown and says so. |
| + if s.cfg.Releases != nil { |
| + var facts appFacts |
| + loaded := false |
| + for _, rec := range recs { |
| + if _, local := byHost[rec.Host]; local { |
| + continue |
| + } |
| + if !loaded { |
| + facts, loaded = s.remoteFacts(ctx, rec.Account, rec.App), true |
| + } |
| + rep := facts.host(rec) |
| + if rep == nil { |
| + if _, fleetPlaced := registry.FleetPlacement(rec.Region); facts.seen(rec.Host) || !facts.complete() || fleetPlaced { |
| + out[rec.Host] = healthUnknown |
| + } |
| + continue |
| + } |
| + if rep.transient { |
| + // Starting or stopping on its box: not asleep, not up. |
| + out[rec.Host] = healthUnknown |
| + continue |
| + } |
| + kind := rec.Kind |
| + if kind == "" { |
| + kind = "instance" |
| + } |
| + status := "ready" |
| + if rep.down { |
| + // Held down after a failed hold-mode build: "Failed", as the |
| + // page says. |
| + status = "failed" |
| + } |
| + out[rec.Host] = healthWord(kind, status, rec.HibernateOrDefault(), rep.awake, true) |
| + } |
| + } |
| + // Readings start with each record's created_at, as on the app pages: a |
| + // previous tenant's samples of the same hostname are not this one's. |
| + sinceByHost := make(map[string]time.Time, len(routeFor)) |
| + for _, rec := range recs { |
| + if _, ok := routeFor[rec.Host]; ok { |
| + sinceByHost[rec.Host] = rec.CreatedAt |
| + } |
| + } |
| + for h, word := range s.healthByHost(ctx, routeFor, sinceByHost) { |
| out[h] = word |
| } |
| return out |
| @@ -300,7 +351,10 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma |
| // reaching unitByHost below would widen the metrics view past the caller's |
| // own app. The scoping lives in each caller, beside the reason that |
| // caller's rows are the caller's to see. |
| -func (s *Server) healthByHost(ctx context.Context, routeFor map[string]registry.Route) map[string]string { |
| +// |
| +// sinceByHost bounds a host's readings by when its owner came to have it |
| +// (ownerAppMetricsFrom); nil for routes the caller has no record for. |
| +func (s *Server) healthByHost(ctx context.Context, routeFor map[string]registry.Route, sinceByHost map[string]time.Time) map[string]string { |
| out := make(map[string]string, len(routeFor)) |
| hosts := make([]string, 0, len(routeFor)) |
| unitByHost := map[string]string{} |
| @@ -310,7 +364,7 @@ func (s *Server) healthByHost(ctx context.Context, routeFor map[string]registry. |
| unitByHost[h] = rt.Unit |
| } |
| } |
| - am, err := s.OwnerAppMetrics(ctx, hosts, unitByHost) |
| + am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost) |
| if err != nil { |
| // An unreadable sweep is not knowledge that these instances are |
| // down: every host reads as not-reporting below, which healthWord |
diff --git a/internal/console/apiinstances_test.go b/internal/console/apiinstances_test.go| index 7bd168219..88523c1e9 100644 |
| --- a/internal/console/apiinstances_test.go |
| +++ b/internal/console/apiinstances_test.go |
| @@ -726,7 +726,7 @@ func TestAPIInstanceListHealthAndFilters(t *testing.T) { |
| // rather than every word coming from the registry alone. |
| fx.addRoute(t, registry.Route{Host: "run.go.tito.io", Kind: "instance", Status: "ready", |
| App: "titogo", Account: fx.sqid, Channel: "stable", Provisioned: true}) |
| - at := time.Now().UTC().Add(-time.Minute) |
| + at := time.Now().UTC() // after the records: earlier samples are a previous owner's |
| if err := metrics.WriteRaw(context.Background(), fx.rel, metrics.RawChunk{ |
| V: 1, Box: "box-health", Hour: metrics.HourOf(at), |
| Samples: []metrics.Sample{{At: at, Units: map[string]metrics.UnitSample{ |
diff --git a/internal/console/apiroutes.go b/internal/console/apiroutes.go| index 3c4905dc2..64206b1ee 100644 |
| --- a/internal/console/apiroutes.go |
| +++ b/internal/console/apiroutes.go |
| @@ -153,7 +153,7 @@ func (s *Server) handleAPIRoutes(w http.ResponseWriter, r *http.Request) { |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), routeListTimeout) |
| defer cancel() |
| - health := s.healthByHost(ctx, routeFor) |
| + health := s.healthByHost(ctx, routeFor, nil) |
| join := loadBoxJoin(ctx, s.cfg.Releases, time.Now()) |
| rows := make([]apiRoute, 0, len(routeFor)) |
| for _, rt := range routeFor { |
diff --git a/internal/console/claim_invariant_world_test.go b/internal/console/claim_invariant_world_test.go| index 6b56214f3..4f1d799fa 100644 |
| --- a/internal/console/claim_invariant_world_test.go |
| +++ b/internal/console/claim_invariant_world_test.go |
| @@ -563,6 +563,9 @@ func newClaimCaseWith(t *testing.T, opts ...func(*Config)) *claimCase { |
| if err != nil { |
| t.Fatalf("NewServer with HostClaim: %v", err) |
| } |
| + // A console that has been up a while: the canary-retire guard does not |
| + // vouch for the window before a console started (recentRecordDeletion). |
| + srv.startedAt = time.Now().Add(-24 * time.Hour) |
| if err := srv.ConfigureClaimRuntime(ctx); err != nil { |
| t.Fatalf("ConfigureClaimRuntime: %v", err) |
| } |
diff --git a/internal/console/claim_purge.go b/internal/console/claim_purge.go| index f64d6a5e5..d96f44d56 100644 |
| --- a/internal/console/claim_purge.go |
| +++ b/internal/console/claim_purge.go |
| @@ -314,6 +314,9 @@ func (p *ClaimPurgeCoordinator) Resume(ctx context.Context, account, app, id, ap |
| return err |
| case "torn-down": |
| if err = p.stage(ctx, h, "retire-hosts", func(ctx context.Context) error { |
| + if p.Server != nil { |
| + p.Server.noteRecordDeletion(account, app, time.Now()) // the canary-retire guard's evidence, first |
| + } |
| return p.Controller.RetirePurgeHosts(ctx, account, app, id, appID) |
| }); err != nil { |
| return err |
diff --git a/internal/console/claim_retire.go b/internal/console/claim_retire.go| index faf5f44d2..c31728bb5 100644 |
| --- a/internal/console/claim_retire.go |
| +++ b/internal/console/claim_retire.go |
| @@ -31,6 +31,9 @@ import ( |
| // operation: a step that is only waiting (parking, a box acknowledgement) |
| // answers claimRetireAccepted, and recovery or a retry carries it on. |
| func (s *Server) retireClaimHostRecord(ctx context.Context, ref provision.RetireRef) error { |
| + // The canary-retire guard's evidence, before anything is deleted: this |
| + // door is also where claim recovery finishes a delayed deletion. |
| + s.noteRecordDeletion(ref.Account, ref.App, time.Now()) |
| c := s.cfg.HostClaimOps |
| if c == nil || c.Control == nil || s.claimOwner == (hostops.RegistrationOwner{}) { |
| return provision.ErrClaimRetirer |
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go| index 2839d36ef..21ff9ec9c 100644 |
| --- a/internal/console/expirypass.go |
| +++ b/internal/console/expirypass.go |
| @@ -211,6 +211,7 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide |
| s.audit(acct, r.App, expiryActor, "purge-refused", "did not delete "+r.App+": it has email set up. Delete it from the Trash page") |
| return |
| } |
| + s.noteRecordDeletion(r.Sqid, r.App, time.Now()) // the canary-retire guard's evidence, first |
| if lifetimesUnit(ctx) { |
| // Every lifetime of the app retired first, under the lock this |
| // pass holds (lifetimes_purge.go). |
diff --git a/internal/console/hostclaimops.go b/internal/console/hostclaimops.go| index 65c31b8c1..6ca3ebffe 100644 |
| --- a/internal/console/hostclaimops.go |
| +++ b/internal/console/hostclaimops.go |
| @@ -13,6 +13,12 @@ import ( |
| ) |
| func (s *Server) retireHostRecord(ctx context.Context, ref provision.RetireRef) error { |
| + // Before anything is deleted, and in memory, where it cannot fail: the |
| + // canary-retire guard's evidence that this app lost a record just now |
| + // (recentRecordDeletion). A delete that then fails costs at most a |
| + // retire held back for channelSettle. Every other console path that |
| + // deletes a record does the same. |
| + s.noteRecordDeletion(ref.Account, ref.App, time.Now()) |
| if s.cfg.HostClaim { |
| return s.retireClaimHostRecord(ctx, ref) |
| } |
diff --git a/internal/console/instancepage.go b/internal/console/instancepage.go| index 34067fe19..fa8f2e543 100644 |
| --- a/internal/console/instancepage.go |
| +++ b/internal/console/instancepage.go |
| @@ -281,7 +281,14 @@ func (s *Server) handleAppInstance(w http.ResponseWriter, r *http.Request) { |
| // error both leave the approved unknown text already set above, the |
| // same soft-degrade the alias lookup just below gives a broken registry. |
| detail.App, detail.Channel = p.AppName, selected.Channel |
| - if s.cfg.Releases != nil { |
| + if selected.remote { |
| + // An instance on another box: everything the page shows about it |
| + // came through remoteFacts when its row was built. The box joins |
| + // below (layout, rollout, updates) read reports by hostname with |
| + // their own, weaker tenant rules, so none of them runs for it; the |
| + // page shows the unknown layout and no rollout or updates section. |
| + detail.Aliases = append(detail.Aliases, selected.aliases...) |
| + } else if s.cfg.Releases != nil { |
| if boxes, _, err := s.systemBoxes(r.Context(), false); err == nil { |
| detail.Layout = layoutWordFor(boxes, host) |
| } |
| @@ -294,7 +301,7 @@ func (s *Server) handleAppInstance(w http.ResponseWriter, r *http.Request) { |
| // the Installed and Serving facts above come from one reading. |
| detail.Updates = s.updatesPage(r.Context(), acct, p.AppName, host, detail, join.update(host, acct.Sqid, p.AppName), p.Role == RoleOwner) |
| } |
| - if reg, err := openRegistry(s.cfg.Registry); err == nil { |
| + if reg, err := openRegistry(s.cfg.Registry); err == nil && !selected.remote { |
| if aliases, err := reg.ListAliases(); err == nil { |
| for _, alias := range aliases { |
| if alias.Host == host && alias.Account == acct.Sqid && alias.App == p.AppName { |
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go| index 3448209ee..a5550cec6 100644 |
| --- a/internal/console/lifetimes_create.go |
| +++ b/internal/console/lifetimes_create.go |
| @@ -10,6 +10,7 @@ import ( |
| "net/http" |
| "os" |
| "strings" |
| + "time" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -312,6 +313,7 @@ func (s *Server) allocSlotLocked(ctx context.Context, a Allocation) error { |
| // Any failure, a conflict included, leaves the allocation pending. |
| func (s *Server) allocCleanLocked(ctx context.Context, a Allocation, staleETag string, plan createPlan) error { |
| if staleETag != "" { |
| + s.noteRecordDeletion(a.Account, a.App, time.Now()) // the canary-retire guard's evidence, first |
| if err := release.DeleteIfMatch(ctx, s.cfg.Releases, provision.RecordKey(a.Account, a.App, a.Host), staleETag); err != nil { |
| log.Printf("console: lifetimes: allocation %s of %s: remove the stale record: %v (pending)", a.OpID, a.Host, err) |
| return errLifetimePending |
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go| index bc1fa6e6b..460e858b2 100644 |
| --- a/internal/console/lifetimes_purge.go |
| +++ b/internal/console/lifetimes_purge.go |
| @@ -38,6 +38,7 @@ import ( |
| // error leaves the marker: errLifetimePending and errLifetimeSettling stop |
| // the purge for a later run, and every step is idempotent. |
| func (s *Server) purgeAppWithLifetimes(ctx context.Context, sqid, app string, want, now time.Time) error { |
| + s.noteRecordDeletion(sqid, app, time.Now()) // the canary-retire guard's evidence, first |
| if err := release.PurgeAppGuards(ctx, s.cfg.Releases, s.cfg.ReleasePub, sqid, app, want, now); err != nil { |
| return err |
| } |
diff --git a/internal/console/lifetimes_retire.go b/internal/console/lifetimes_retire.go| index 169400474..8bb2c3165 100644 |
| --- a/internal/console/lifetimes_retire.go |
| +++ b/internal/console/lifetimes_retire.go |
| @@ -6,6 +6,7 @@ import ( |
| "fmt" |
| "log" |
| "net/http" |
| + "time" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -83,6 +84,7 @@ func (s *Server) retireRecordWithLifetime(ctx context.Context, acct, app, host s |
| if expect.Set() > 1 { |
| return errRetireExpectation |
| } |
| + s.noteRecordDeletion(acct, app, time.Now()) // the canary-retire guard's evidence, first |
| return s.withAppHost(acct, app, host, func() error { |
| return s.retireRecordWithLifetimeLocked(ctx, acct, app, host, expect) |
| }) |
diff --git a/internal/console/listquery.go b/internal/console/listquery.go| index 6ab7cfd42..e848a815e 100644 |
| --- a/internal/console/listquery.go |
| +++ b/internal/console/listquery.go |
| @@ -22,7 +22,12 @@ const instancePageSize = 50 |
| // slugs, filters and links all derive from here. Waking/Crashed/Never |
| // started are sidecarHealthWord's own vocabulary (overview.go); Running and |
| // Asleep are shared with the instance family, not duplicated here. |
| -var healthWords = []string{"Running", "Serving", "Setting up", "Asleep", "No readings", "Not responding", "Failed", "Waking", "Crashed", "Never started"} |
| +var healthWords = []string{"Running", "Serving", "Setting up", "Asleep", "No readings", "Not responding", "Failed", "Waking", "Crashed", "Never started", healthUnknown} |
| + |
| +// healthUnknown is the health of an instance on another box whose state no |
| +// box report vouches for (RouteView.unknown). It is the console's existing |
| +// "can't tell" wording, not a new phrase. |
| +const healthUnknown = "Can't tell right now" |
| // instanceQuery is one request's list controls. Zero value = everything, |
| // first page. |
| @@ -48,7 +53,7 @@ func parseInstanceQuery(v url.Values) instanceQuery { |
| // healthSlug is a health word's URL form: "Not responding" ↔ |
| // "not-responding". |
| func healthSlug(word string) string { |
| - return strings.ReplaceAll(strings.ToLower(word), " ", "-") |
| + return strings.ReplaceAll(strings.ReplaceAll(strings.ToLower(word), "'", ""), " ", "-") |
| } |
| func healthTone(word string) string { |
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go| index 7f1c70307..70587ba37 100644 |
| --- a/internal/console/metricsview.go |
| +++ b/internal/console/metricsview.go |
| @@ -14,6 +14,7 @@ import ( |
| "errors" |
| "fmt" |
| "log" |
| + "math" |
| "os" |
| "sort" |
| "strconv" |
| @@ -42,6 +43,14 @@ type UnitRow struct { |
| MemBytes *int64 |
| ReadBytes, WriteBytes *int64 |
| SparkCPU, SparkMem string // SVG polyline points, "" when no data |
| + |
| + // cpu and mem are the unit's raw readings at each of the box's swept |
| + // samples (BoxMetricsView.times), NaN and -1 where absent, kept so an |
| + // owner's graph can be redrawn from only the samples that are theirs |
| + // (ownerAppMetricsFrom's ownership start). Compact on purpose: one |
| + // float32 and one int64 per sample per running unit. |
| + cpu []float32 |
| + mem []int64 |
| } |
| // BoxMetricsView is one box's assembled dashboard row: latest host readings |
| @@ -52,6 +61,10 @@ type BoxMetricsView struct { |
| CPU, Mem, Disk *float64 |
| SparkCPU, SparkMem, SparkDisk string // SVG polyline points, "" when no data |
| Units []UnitRow // sorted by CPUFrac desc, nil-CPU rows last |
| + |
| + // times is each swept sample's time, oldest first: the x axis of every |
| + // unit's cpu and mem series. |
| + times []time.Time |
| } |
| // AlertRow is one currently-firing rule on one box. LoadMetrics only ever |
| @@ -576,6 +589,10 @@ func buildBoxView(box string, samples []metrics.Sample) BoxMetricsView { |
| view.SparkDisk = sparkPoints(disk, 240, 40) |
| view.Units = buildUnitRows(samples) |
| + view.times = make([]time.Time, len(samples)) |
| + for i, sm := range samples { |
| + view.times[i] = sm.At |
| + } |
| return view |
| } |
| @@ -601,6 +618,8 @@ func buildUnitRows(samples []metrics.Sample) []UnitRow { |
| WriteBytes: u.WriteBytes, |
| SparkCPU: sparkPoints(unitCPUSeries(samples, name), 240, 40), |
| SparkMem: sparkPoints(unitMemSeries(samples, name), 240, 40), |
| + cpu: unitRawCPU(samples, name), |
| + mem: unitRawMem(samples, name), |
| }) |
| } |
| // Name order first so the CPU-desc sort below, being stable, ties out |
| @@ -619,6 +638,66 @@ func buildUnitRows(samples []metrics.Sample) []UnitRow { |
| return rows |
| } |
| +// unitRawCPU and unitRawMem are one unit's raw readings at each swept |
| +// sample, NaN and -1 where the unit or the reading is absent. |
| +func unitRawCPU(samples []metrics.Sample, unit string) []float32 { |
| + out := make([]float32, len(samples)) |
| + for i, sm := range samples { |
| + out[i] = float32(math.NaN()) |
| + if u, ok := sm.Units[unit]; ok && u.CPUFrac != nil { |
| + out[i] = float32(*u.CPUFrac) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func unitRawMem(samples []metrics.Sample, unit string) []int64 { |
| + out := make([]int64, len(samples)) |
| + for i, sm := range samples { |
| + out[i] = -1 |
| + if u, ok := sm.Units[unit]; ok && u.MemBytes != nil { |
| + out[i] = *u.MemBytes |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// sparksSince redraws a unit's two graphs from only the samples at or after |
| +// since, the memory one scaled to the peak within them. ok is false when |
| +// the unit has no sample there at all. |
| +func sparksSince(times []time.Time, u UnitRow, since time.Time) (cpu, mem string, ok bool) { |
| + if len(times) != len(u.cpu) || len(times) != len(u.mem) { |
| + return "", "", false |
| + } |
| + k := sort.Search(len(times), func(i int) bool { return !times[i].Before(since) }) |
| + if k >= len(times) { |
| + return "", "", false |
| + } |
| + n := len(times) - k |
| + cs := make([]*float64, n) |
| + var peak int64 |
| + for i := k; i < len(times); i++ { |
| + if c := u.cpu[i]; !math.IsNaN(float64(c)) { |
| + f := float64(c) |
| + cs[i-k] = &f |
| + } |
| + if u.mem[i] > peak { |
| + peak = u.mem[i] |
| + } |
| + } |
| + var ms []*float64 |
| + if peak > 0 { |
| + ms = make([]*float64, n) |
| + for i := k; i < len(times); i++ { |
| + if u.mem[i] >= 0 { |
| + f := float64(u.mem[i]) / float64(peak) |
| + ms[i-k] = &f |
| + } |
| + } |
| + } |
| + return sparkPoints(cs, 240, 40), sparkPoints(ms, 240, 40), true |
| +} |
| + |
| // unitCPUSeries is one unit's CPU fraction at each swept sample index. A |
| // sample where the unit is absent, or present without a CPU reading, stays |
| // nil — sparkPoints draws a gap, never a zero. |
| @@ -712,6 +791,16 @@ func (m InstanceMetrics) Reporting() bool { return m.Box != "" } |
| // readings, Reporting false), never zeros and never silently dropped — an |
| // owner whose instance is asleep must still see it listed. |
| func (s *Server) OwnerAppMetrics(ctx context.Context, hosts []string, unitByHost map[string]string) ([]InstanceMetrics, error) { |
| + return s.ownerAppMetricsFrom(ctx, hosts, unitByHost, nil) |
| +} |
| + |
| +// ownerAppMetricsFrom is OwnerAppMetrics where sinceByHost bounds a host's |
| +// readings by when its current owner's route or record came to exist |
| +// (graphs redrawn from later samples only; a zero time is no readings). A |
| +// host not named there reads as before: the freshest box's sample. Only |
| +// instances on the console's own box are ever asked for: an instance on |
| +// another box takes no readings (remoteinstances.go). |
| +func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitByHost map[string]string, sinceByHost map[string]time.Time) ([]InstanceMetrics, error) { |
| // The allowlist, keyed by the unit names each host can legally match. |
| // Matching is exact-string on this map: a unit the caller did not ask |
| // for cannot be reached by any path below. |
| @@ -761,13 +850,22 @@ func (s *Server) OwnerAppMetrics(ctx context.Context, hosts []string, unitByHost |
| if !ok { |
| continue // not this app's — the whole boundary is this line |
| } |
| + // Ownership start: a unit name derives from the hostname, and a |
| + // hostname can have had another owner earlier in the window. |
| + // Nothing before since is this owner's: with no start known, no |
| + // readings at all; with a newest sample older than the start, |
| + // not even the current one. |
| + since, bounded := sinceByHost[host] |
| + if bounded && (since.IsZero() || box.At.Before(since)) { |
| + continue |
| + } |
| // A host that reports on two boxes at once (a move in flight) |
| // shows the freshest box's reading, not whichever sorted first. |
| if prev, taken := at[host]; taken && !box.At.After(prev) { |
| continue |
| } |
| at[host] = box.At |
| - found[host] = InstanceMetrics{ |
| + row := InstanceMetrics{ |
| Host: host, |
| ObservedAt: box.At, |
| Box: box.Box, |
| @@ -776,6 +874,12 @@ func (s *Server) OwnerAppMetrics(ctx context.Context, hosts []string, unitByHost |
| SparkCPU: u.SparkCPU, |
| SparkMem: u.SparkMem, |
| } |
| + if bounded && (len(box.times) == 0 || box.times[0].Before(since)) { |
| + // Part of the window predates the owner: redraw from only |
| + // their samples, or draw nothing when that cannot be done. |
| + row.SparkCPU, row.SparkMem, _ = sparksSince(box.times, u, since) |
| + } |
| + found[host] = row |
| } |
| } |
diff --git a/internal/console/overview.go b/internal/console/overview.go| index 03db7eba9..fc1b260fc 100644 |
| --- a/internal/console/overview.go |
| +++ b/internal/console/overview.go |
| @@ -31,6 +31,11 @@ type OverviewStats struct { |
| // unknowns — the tile names them separately and the verdict must not |
| // treat them as down (the 2026-08-10 tito false alarm). |
| InstanceNoReadings int |
| + // InstanceUnknown counts routes on other boxes, of any kind, whose state |
| + // no box report vouches for (RouteView.unknown). The instance-kind ones |
| + // are left out of the denominator like InstanceNoReadings; the verdict |
| + // says it can't tell, and the tile does not claim "Served". |
| + InstanceUnknown int |
| // InstanceCounted is the Running tile's denominator: InstanceExpected |
| // minus the unknowable. Templates render facts, never compute them. |
| InstanceCounted int |
| @@ -84,6 +89,10 @@ type OverviewStats struct { |
| // pointing here yet, or a cert that is not ready. |
| DomainTotal int |
| DomainAttention int |
| + // DomainUnknown counts domains of instances on other boxes that no |
| + // accepted box report has a DNS or certificate reading for: the tile |
| + // must not call those OK. |
| + DomainUnknown int |
| // Shipped releases. The versions list is capped (versionsCap), so |
| // ReleasesCapped says "20+" rather than lying with "20". |
| @@ -103,6 +112,7 @@ type OverviewStats struct { |
| // wave its failed cert on it. |
| func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, versions []VersionView, dbJoin boxJoin) OverviewStats { |
| st := OverviewStats{MetricsUnavailable: metrics == nil} |
| + unknownInstances := 0 |
| st.Deployment = observedDeployment(view.Routes, acct) |
| reporting := make(map[string]bool, len(metrics)) |
| for _, m := range metrics { |
| @@ -127,7 +137,14 @@ func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, ver |
| if rt.Account != acct || rt.Platform { |
| continue |
| } |
| - if n := dbJoin.dbSize(rt.Host); n != nil { |
| + // A remote row carries the size from the one box report it joined |
| + // (remoteinstances.go: never a report naming another tenant); the |
| + // host-keyed join has no tenant to check. |
| + n := dbJoin.dbSize(rt.Host) |
| + if rt.remote { |
| + n = rt.dbBytes |
| + } |
| + if n != nil { |
| if st.DBSizeSum == nil { |
| st.DBSizeSum = new(int64) |
| } |
| @@ -138,18 +155,32 @@ func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, ver |
| continue |
| } |
| st.InstanceTotal++ |
| + if rt.unknown { |
| + // A route on another box whose state no report vouches for, |
| + // whatever its kind: neither up, down nor asleep, and a static |
| + // one is not "served" on no evidence (remoteinstances.go). |
| + st.InstanceUnknown++ |
| + } |
| if rt.Kind == "instance" { |
| st.InstanceExpected++ |
| - if reporting[rt.Host] { |
| + if rt.unknown { |
| + unknownInstances++ |
| + } else if rt.Status == "failed" { |
| + // Failed (an instance held down after a failed build) wins |
| + // over a reading: a sample from before the failure is not |
| + // health. Counted, and neither reporting nor asleep. |
| + } else if reporting[rt.Host] || rt.boxAwake { |
| st.InstanceReporting++ |
| - } else if rt.Hibernate { |
| + } else if rt.Hibernate && rt.Status != "failed" { |
| + // A failed instance (one held down after a failed build) is |
| + // not sleeping: it will not wake, so it is not counted here. |
| st.InstanceAsleep++ |
| } else if !expectsReadings(rt.Provisioned, rt.Unit, rt.Backing) { |
| st.InstanceNoReadings++ |
| } |
| } |
| } |
| - st.InstanceCounted = st.InstanceExpected - st.InstanceNoReadings |
| + st.InstanceCounted = st.InstanceExpected - st.InstanceNoReadings - unknownInstances |
| // Routes and Domains are parallel slices — Assemble appends one of each |
| // per registry route, in the same loop — which is what lets the domain |
| // rows be account-filtered here at all (DomainView carries no account of |
| @@ -164,6 +195,8 @@ func assembleOverview(view *AppView, acct string, metrics []InstanceMetrics, ver |
| st.DomainTotal++ |
| if domainNeedsAttention(view.Domains[i]) { |
| st.DomainAttention++ |
| + } else if rt.remote && view.Domains[i].DNS == "" && view.Domains[i].TLS == "" { |
| + st.DomainUnknown++ |
| } |
| } |
| } |
| @@ -189,6 +222,8 @@ func healthVerdict(st OverviewStats) (string, string) { |
| return "attention", "Needs attention" |
| case st.InstanceReporting+st.InstanceAsleep < st.InstanceCounted: |
| return "attention", "Needs attention" |
| + case st.InstanceUnknown > 0: |
| + return "unknown", "Can't tell right now" |
| case st.Deployment.ReportableCount == 0: |
| return "ok", "All good" |
| case !st.Deployment.HasReportedVersion(): |
| @@ -252,6 +287,11 @@ func assembleInstanceRows(view *AppView, acct *Account, metrics []InstanceMetric |
| if status == "" { |
| status = "ready" // registry contract: empty status means ready |
| } |
| + health := healthWord(rt.Kind, status, rt.Hibernate, byHost[rt.Host].Reporting() || rt.boxAwake, |
| + expectsReadings(rt.Provisioned, rt.Unit, rt.Backing)) |
| + if rt.unknown { |
| + health = healthUnknown |
| + } |
| rows = append(rows, InstanceRow{ |
| Host: rt.Host, |
| Channel: rt.Channel, |
| @@ -261,8 +301,7 @@ func assembleInstanceRows(view *AppView, acct *Account, metrics []InstanceMetric |
| Hibernate: rt.Hibernate, |
| Metrics: byHost[rt.Host], |
| Restartable: rt.Restartable, |
| - HealthWord: healthWord(rt.Kind, status, rt.Hibernate, byHost[rt.Host].Reporting(), |
| - expectsReadings(rt.Provisioned, rt.Unit, rt.Backing)), |
| + HealthWord: health, |
| }) |
| } |
| return rows |
diff --git a/internal/console/overview_test.go b/internal/console/overview_test.go| index fece75e74..42abeaab0 100644 |
| --- a/internal/console/overview_test.go |
| +++ b/internal/console/overview_test.go |
| @@ -753,6 +753,9 @@ func TestAppOverviewDatabaseTileRenders(t *testing.T) { |
| if err := status.WriteBox(context.Background(), fx.rel, box); err != nil { |
| t.Fatal(err) |
| } |
| + // The pages share a minute-old read of the box reports |
| + // (pageBoxReports); a new report shows once that read ages out. |
| + fx.srv.boxReports.expire() |
| _, _, body = get(t, c, fx.u("/apps/kass")) |
| if !strings.Contains(body, "3.0 MB") || !strings.Contains(body, "on disk, including copies that are asleep") { |
| t.Fatalf("sized app: want 3.0 MB on the Database tile in:\n%s", body) |
diff --git a/internal/console/ownership.go b/internal/console/ownership.go| index 3a75c603c..f776ff4a5 100644 |
| --- a/internal/console/ownership.go |
| +++ b/internal/console/ownership.go |
| @@ -515,6 +515,7 @@ func (s *Server) handlePurgeApp(w http.ResponseWriter, r *http.Request) { |
| s.audit(acct, app, addr, "email-teardown", "tore down the email estate (credentials, IAM principal, domain claims) during permanent deletion") |
| } |
| } |
| + s.noteRecordDeletion(acct.Sqid, app, time.Now()) // the canary-retire guard's evidence, first |
| var purgeErr error |
| if lifetimesUnit(r.Context()) { |
| // Admitted on: every lifetime of the app is retired first, under |
diff --git a/internal/console/perfwiring_test.go b/internal/console/perfwiring_test.go| index ecd9870c4..0ca62c495 100644 |
| --- a/internal/console/perfwiring_test.go |
| +++ b/internal/console/perfwiring_test.go |
| @@ -213,7 +213,7 @@ func TestAssembleTimesTheRegistryRead(t *testing.T) { |
| var rec perf.Recorder |
| mux := http.NewServeMux() |
| mux.HandleFunc("GET /assemble", func(w http.ResponseWriter, r *http.Request) { |
| - if _, err := Assemble(r.Context(), fx.srv.cfg.Registry, fx.srv.cfg.Releases, fx.srv.cfg.ReleasePub, release.OpsAccount, []string{"kass"}, DNSTargets{}); err != nil { |
| + if _, err := Assemble(r.Context(), fx.srv.cfg.Registry, fx.srv.cfg.Releases, fx.srv.cfg.ReleasePub, release.OpsAccount, []string{"kass"}, DNSTargets{}, nil); err != nil { |
| t.Errorf("Assemble: %v", err) |
| } |
| }) |
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go| new file mode 100644 |
| index 000000000..f3cfcc612 |
| --- /dev/null |
| +++ b/internal/console/remoteinstances.go |
| @@ -0,0 +1,734 @@ |
| +package console |
| + |
| +// Instances on other boxes (docs/superpowers/notes/console-remote-instances.md). |
| +// |
| +// The app pages used to draw every instance row from the console box's own |
| +// registry, so an instance whose route lives on another box (a region move, |
| +// an instance created in another region) was invisible: "No instances yet", |
| +// no metrics, a 404 on its page. The account's bucket instance records are |
| +// the region-neutral list, and every box's status report says what it serves. |
| +// This file joins the two into extra RouteView rows for Assemble. |
| +// |
| +// Two reads, neither of them new polling: |
| +// |
| +// - Records come from the change-index record view's latest Complete |
| +// snapshot when the console has one armed (zero requests), else from the |
| +// bucket, which is the read the Logs and Settings tabs already make. |
| +// - Box reports (status/boxes/*.json) come from one console-wide read held |
| +// for boxReportTTL. Boxes rewrite them every status.SnapshotPeriod (five |
| +// minutes), so a minute's cache loses nothing. |
| +// |
| +// The tenant boundary is the record: a remote row exists only for a host |
| +// that a record under apps/<this account>/<this app>/ names. The box maps |
| +// are keyed by host and carry no tenant, so they are joined only for those |
| +// hosts, and a box whose rollout report names another tenant for the host |
| +// is not joined at all (the R18 rule boxJoin.rollout applies). |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + "slices" |
| + "sort" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// boxReportTTL is how long a page view's read of the box reports serves |
| +// every later page view. boxReportFailTTL is the shorter hold for a read |
| +// that failed, so a bucket hiccup costs the pages a few seconds of |
| +// "can't tell" rather than a minute, without every view retrying at once. |
| +const ( |
| + boxReportTTL = 60 * time.Second |
| + boxReportFailTTL = 10 * time.Second |
| +) |
| + |
| +// boxReportCache is the console-wide read of status/boxes/. One load at a |
| +// time, so a burst of page views costs one read; mu guards the fields and |
| +// is never held across a load, and loading is closed when the running load |
| +// is published. |
| +type boxReportCache struct { |
| + mu sync.Mutex |
| + at time.Time // when the held read FINISHED |
| + valid bool |
| + failed bool // the held read failed or was incomplete: boxReportFailTTL |
| + boxes []status.Box |
| + complete bool |
| + // gen counts invalidations: a load that began before one publishes its |
| + // result to its own caller but does not hold it for later views. |
| + gen uint64 |
| + loading chan struct{} |
| + // now is the cache's clock; nil is time.Now. Tests set it. |
| + now func() time.Time |
| + // records holds the page views' reads of each app's instance records |
| + // (pageRecords), for boxReportTTL each, so a page view within the |
| + // minute reads no record, slot or listing. invalidate drops them all. |
| + records map[pageRecordsKey]heldRecords |
| +} |
| + |
| +// pageRecordsKey names one held record read: an app, and whether its |
| +// reads were judged against the lifetime slots. |
| +type pageRecordsKey struct { |
| + acct, app string |
| + judged bool |
| +} |
| + |
| +type heldRecords struct { |
| + recs []provision.Record |
| + at time.Time |
| +} |
| + |
| +// heldRecordsMax bounds the held record reads; past it, expired ones go. |
| +const heldRecordsMax = 4096 |
| + |
| +func (c *boxReportCache) heldRecords(k pageRecordsKey) ([]provision.Record, bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + h, ok := c.records[k] |
| + if !ok || c.clock().Sub(h.at) >= boxReportTTL { |
| + return nil, false |
| + } |
| + return h.recs, true |
| +} |
| + |
| +// holdRecords holds a record read that began at generation gen, unless an |
| +// invalidation came since. |
| +func (c *boxReportCache) holdRecords(gen uint64, k pageRecordsKey, recs []provision.Record) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if gen != c.gen { |
| + return |
| + } |
| + now := c.clock() |
| + if c.records == nil { |
| + c.records = map[pageRecordsKey]heldRecords{} |
| + } |
| + if len(c.records) >= heldRecordsMax { |
| + for old, h := range c.records { |
| + if now.Sub(h.at) >= boxReportTTL { |
| + delete(c.records, old) |
| + } |
| + } |
| + } |
| + c.records[k] = heldRecords{recs: recs, at: now} |
| +} |
| + |
| +func (c *boxReportCache) generation() uint64 { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.gen |
| +} |
| + |
| +func (c *boxReportCache) clock() time.Time { |
| + if c.now != nil { |
| + return c.now() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// invalidate drops the held read, so the next page view reads afresh. Every |
| +// console path that deletes a record calls it (noteRecordDeletion): a held |
| +// read may still name the deleted record's tenant for its host. |
| +func (c *boxReportCache) invalidate() { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.valid = false |
| + c.records = nil |
| + c.gen++ |
| +} |
| + |
| +// pageBoxReports returns every box's report, from the cache when it is |
| +// young enough, and whether the read saw every box (status.LoadBoxesComplete). |
| +// |
| +// A read is held for boxReportTTL, or boxReportFailTTL when it failed or |
| +// skipped a box (complete false: a partial read must not stand for a |
| +// minute), timed from when the load finished, so a load that ran to its |
| +// timeout is not published already expired. The load runs on its own |
| +// bounded context, detached from the request's, so one closed browser tab |
| +// cannot fail the read for the views behind it. A view that arrives while a |
| +// load runs waits for it, and stops waiting when its own request ends: it |
| +// then gets whatever the cache held before, reported incomplete. The |
| +// snapshots are shared and must not be changed. |
| +func (s *Server) pageBoxReports(ctx context.Context) ([]status.Box, bool) { |
| + if s.cfg.Releases == nil { |
| + return nil, false |
| + } |
| + c := &s.boxReports |
| + for { |
| + c.mu.Lock() |
| + ttl := boxReportTTL |
| + if c.failed { |
| + ttl = boxReportFailTTL |
| + } |
| + if c.valid && c.clock().Sub(c.at) < ttl { |
| + boxes, complete := c.boxes, c.complete |
| + c.mu.Unlock() |
| + return boxes, complete |
| + } |
| + if wait := c.loading; wait != nil { |
| + held := c.boxes |
| + c.mu.Unlock() |
| + select { |
| + case <-wait: |
| + continue |
| + case <-ctx.Done(): |
| + return held, false |
| + } |
| + } |
| + done := make(chan struct{}) |
| + c.loading = done |
| + gen := c.gen |
| + c.mu.Unlock() |
| + |
| + loadCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), instanceStoreTimeout) |
| + boxes, complete, err := status.LoadBoxesComplete(loadCtx, s.cfg.Releases) |
| + cancel() |
| + if err != nil { |
| + log.Printf("console: box reports for the app pages: %v", err) |
| + boxes, complete = nil, false |
| + } |
| + c.mu.Lock() |
| + c.at, c.valid, c.failed, c.boxes, c.complete = c.clock(), c.gen == gen, err != nil || !complete, boxes, complete |
| + c.loading = nil |
| + close(done) |
| + c.mu.Unlock() |
| + return boxes, complete |
| + } |
| +} |
| + |
| +// hostReport is one fresh box's word about one host it serves. |
| +type hostReport struct { |
| + box string |
| + at time.Time // the report's generation |
| + // version is the box's registry Version for the host (RouteVersions), |
| + // the same column a local row's Version reads. |
| + version string |
| + dbBytes *int64 |
| + // reading is the host's own DNS and certificate reading (an Aliases |
| + // entry whose Route is the host itself), nil when the box has none. |
| + reading *status.AliasReading |
| + // aliases are the custom domains this box routes to the host. |
| + aliases []string |
| + // tenantKnown is whether the box's rollout report names the host's |
| + // account and app, the only identity a report can carry for a host; |
| + // awake, down and transient are that entry's process state. |
| + tenantKnown bool |
| + account, app string |
| + awake bool |
| + down, transient bool |
| +} |
| + |
| +// fleetReports is every fresh box's word about every host. |
| +type fleetReports struct { |
| + byHost map[string][]hostReport |
| + // complete is whether every box's report was read. Only a complete read |
| + // can say "no box serves this host". |
| + complete bool |
| +} |
| + |
| +// foldFleetReports folds box reports into per-host reports. Stale boxes are |
| +// left out under the fleet's one staleness rule (status.BoxStale), as every |
| +// other box join does. Only remoteFacts calls it. |
| +func foldFleetReports(boxes []status.Box, complete bool, now time.Time) fleetReports { |
| + f := fleetReports{byHost: map[string][]hostReport{}, complete: complete} |
| + for _, b := range boxes { |
| + m := b.Metrics |
| + if m == nil || status.BoxStale(b, now, status.SnapshotPeriod) { |
| + continue |
| + } |
| + reps := map[string]*hostReport{} |
| + get := func(host string) *hostReport { |
| + r := reps[host] |
| + if r == nil { |
| + r = &hostReport{box: b.Label, at: b.GeneratedAt} |
| + reps[host] = r |
| + } |
| + return r |
| + } |
| + for host, v := range m.RouteVersions { |
| + get(host).version = v |
| + } |
| + for host := range m.RouteServing { |
| + get(host) |
| + } |
| + for host, n := range m.RouteDBBytes { |
| + get(host).dbBytes = &n |
| + } |
| + if m.Rollout != nil { |
| + for host, hr := range m.Rollout.Hosts { |
| + r := get(host) |
| + r.tenantKnown, r.account, r.app = hr.Account != "" && hr.App != "", hr.Account, hr.App |
| + r.awake = hr.Awake && !hr.Transient |
| + r.down = hr.Attempt == status.AttemptDown |
| + r.transient = hr.Transient |
| + } |
| + } |
| + for name, reading := range m.Aliases { |
| + reading := reading |
| + if reading.Route == name { |
| + get(name).reading = &reading |
| + continue |
| + } |
| + if reading.Route != "" { |
| + r := get(reading.Route) |
| + r.aliases = append(r.aliases, name) |
| + } |
| + } |
| + for host, r := range reps { |
| + sort.Strings(r.aliases) |
| + f.byHost[host] = append(f.byHost[host], *r) |
| + } |
| + } |
| + return f |
| +} |
| + |
| +// appFacts is what the console may say about acct/app's instances on other |
| +// boxes, from one read of the box reports. remoteFacts builds it, and every |
| +// page, API answer and check that shows or decides anything about a remote |
| +// host goes through it: nothing else folds or picks box reports for a |
| +// remote host (TestRemoteFactsOneAccessor holds the package to that). |
| +type appFacts struct { |
| + acct, app string |
| + reports fleetReports |
| +} |
| + |
| +// remoteFacts is the one accessor for remote facts about acct/app. |
| +func (s *Server) remoteFacts(ctx context.Context, acct, app string) appFacts { |
| + boxes, complete := s.pageBoxReports(ctx) |
| + return appFacts{acct: acct, app: app, reports: foldFleetReports(boxes, complete, time.Now())} |
| +} |
| + |
| +// host is the one box report about rec's host that may be joined to it, or |
| +// nil. Identity is the record plus a report entry naming the same account |
| +// and app, generated after the record was created: a report naming another |
| +// tenant may predate the host changing hands, one naming no tenant could be |
| +// anyone's, and one generated before the record existed is about an earlier |
| +// owner of the hostname. Anything else is unknown, and contributes nothing: |
| +// not a version, a size, a domain, a state or a reading. Among the reports |
| +// that qualify the freshest wins, then the lower box label, so the choice is |
| +// stable; two boxes reporting one host is a move in flight. |
| +func (f appFacts) host(rec provision.Record) *hostReport { |
| + if rec.Account != f.acct || rec.App != f.app { |
| + return nil |
| + } |
| + var best *hostReport |
| + for i := range f.reports.byHost[rec.Host] { |
| + r := &f.reports.byHost[rec.Host][i] |
| + if !r.tenantKnown || r.account != f.acct || r.app != f.app || !r.at.After(rec.CreatedAt) { |
| + continue |
| + } |
| + if best == nil || r.at.After(best.at) || (r.at.Equal(best.at) && r.box < best.box) { |
| + best = r |
| + } |
| + } |
| + return best |
| +} |
| + |
| +// complete is whether every box's report was read. |
| +func (f appFacts) complete() bool { return f.reports.complete } |
| + |
| +// seen reports whether any fresh box report names host at all, whoever it |
| +// says the host belongs to: a host some box serves is not "not minted |
| +// anywhere", even when nothing about it can be joined. |
| +func (f appFacts) seen(host string) bool { return len(f.reports.byHost[host]) > 0 } |
| + |
| +// unrecorded is a host a fresh box report names as this app's (by its |
| +// rollout entry) that no record names, and the box reporting it. |
| +func (f appFacts) unrecorded(recorded map[string]bool) (host, box string, ok bool) { |
| + hosts := make([]string, 0, len(f.reports.byHost)) |
| + for h := range f.reports.byHost { |
| + hosts = append(hosts, h) |
| + } |
| + sort.Strings(hosts) |
| + for _, h := range hosts { |
| + if recorded[h] { |
| + continue |
| + } |
| + for _, r := range f.reports.byHost[h] { |
| + if r.tenantKnown && r.account == f.acct && r.app == f.app { |
| + return h, r.box, true |
| + } |
| + } |
| + } |
| + return "", "", false |
| +} |
| + |
| +// remoteRows is what Assemble needs to add the account's instances on other |
| +// boxes: a record reader and the remote facts, both scoped to the viewed |
| +// account. |
| +type remoteRows struct { |
| + // records reads app's records (pageRecords). |
| + records func(app string) ([]provision.Record, error) |
| + facts func(app string) appFacts |
| +} |
| + |
| +// remoteRoute folds one record that has no row in the console box's registry |
| +// into a RouteView and its parallel DomainView, with rep the report |
| +// appFacts.host accepted for it (or nil). |
| +// |
| +// Status: "ready" when an accepted report names the host; "pending" (Setting |
| +// up) when every box was read and none reports the host at all, which is a |
| +// record whose route has not been minted anywhere; "" otherwise. A record |
| +// placed on a customer fleet is never "pending": fleet boxes report |
| +// elsewhere, so the platform's reports cannot vouch for its absence. |
| +// |
| +// unknown: with no accepted report, the row shows the record's facts and |
| +// says "Can't tell right now" for its live state, rather than guessing |
| +// Asleep, Not responding or Serving. That includes static sites and |
| +// instances that never sleep, which the rollout report does not cover. |
| +// |
| +// No metrics: a remote row takes no CPU or memory readings and no graphs |
| +// (appResourceMetrics skips it), since no sample on any box is proven to |
| +// be this owner's. Unit and Caps are deliberately empty. Restartable is false: the browser restart door acts on the console box's |
| +// registry only. |
| +func remoteRoute(rec provision.Record, rep *hostReport, f appFacts, acct string, dns DNSTargets) (RouteView, DomainView) { |
| + kind := rec.Kind |
| + if kind == "" { |
| + kind = "instance" |
| + } |
| + ch := rec.Channel |
| + if ch == "" { |
| + ch = "stable" |
| + } |
| + _, fleetPlaced := registry.FleetPlacement(rec.Region) |
| + rv := RouteView{ |
| + Host: rec.Host, Kind: kind, Channel: ch, |
| + Hibernate: rec.HibernateOrDefault(), |
| + Account: acct, |
| + Environment: rec.Environment, |
| + Provisioned: true, |
| + remote: true, |
| + } |
| + typ := "custom" |
| + if strings.HasPrefix(ch, "canary/") { |
| + typ += " · " + ch |
| + } |
| + dv := DomainView{Domain: rec.Host, Type: typ} |
| + switch { |
| + case rep != nil: |
| + rv.Status = "ready" |
| + rv.Version = rep.version |
| + rv.box = rep.box |
| + rv.dbBytes = rep.dbBytes |
| + rv.aliases = rep.aliases |
| + switch { |
| + case rep.down: |
| + // Held down after a failed hold-mode build: the local rows' |
| + // word for an instance that will not start, "Failed". |
| + rv.Status = "failed" |
| + case rep.transient: |
| + // Starting or stopping: not healthy sleep, and not up either. |
| + rv.unknown = true |
| + default: |
| + rv.boxAwake = rep.awake |
| + } |
| + if rd := rep.reading; rd != nil { |
| + dv.DNS = rd.DNSStatus |
| + if rd.CertExpiresAt > 0 { |
| + dv.TLS = "ready · renews " + time.Unix(rd.CertExpiresAt, 0).UTC().Format("2006-01-02") |
| + } |
| + // domainView's rule: guidance only for a reading that says the |
| + // member's record is missing or wrong. No reading is not that. |
| + if rd.DNSStatus != "" && rd.DNSStatus != "pointing" && rd.DNSStatus != "unresolved" { |
| + dv.Guidance = domainGuidance(rec.Host, dns) |
| + } |
| + } |
| + case f.complete() && !fleetPlaced && !f.seen(rec.Host): |
| + rv.Status = "pending" |
| + default: |
| + rv.unknown = true |
| + } |
| + return rv, dv |
| +} |
| + |
| +// pageRecords reads acct/app's instance records for a page view, every one |
| +// of them: no cap, so no instance is ever dropped from the pages. The read |
| +// is held in the box-report cache for boxReportTTL, so a page view within |
| +// the minute makes no request for records, and every console path that |
| +// deletes a record drops it (noteRecordDeletion). A record created since |
| +// shows within the minute, as a box report does. Uncached, with the record |
| +// view armed and its latest snapshot Complete, the reads are the |
| +// snapshot's: the run and seed sweeps keep it within a pass of the bucket, |
| +// and a page view does not refresh it. Otherwise it is one LIST plus a GET |
| +// per record. With lifetimes on, each record is judged against its host's |
| +// incarnation slot, one GET each. A record that will not read is logged |
| +// and left out; one deleted since the listing is simply gone. |
| +func (s *Server) pageRecords(ctx context.Context, acct, app string) ([]provision.Record, error) { |
| + if s.cfg.Releases == nil { |
| + return nil, nil |
| + } |
| + judge := provision.JudgeFrom(ctx) |
| + k := pageRecordsKey{acct: acct, app: app, judged: judge != nil} |
| + if recs, ok := s.boxReports.heldRecords(k); ok { |
| + return slices.Clone(recs), nil |
| + } |
| + gen := s.boxReports.generation() |
| + store := s.cfg.Releases |
| + if v := s.recordView; v != nil && !s.recentlyDeleted(acct, app, time.Now()) { |
| + if sn := v.Snapshot(); sn != nil && sn.Complete { |
| + store = sn.Store(s.cfg.Releases) |
| + } |
| + } |
| + prefix := provision.RecordsPrefix(acct, app) |
| + keys, err := store.List(ctx, prefix) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var hosts []string |
| + for _, key := range keys { |
| + rest, ok := strings.CutPrefix(key, prefix) |
| + if !ok || rest == "" || strings.Contains(rest, "/") { |
| + continue |
| + } |
| + host, ok := strings.CutSuffix(rest, ".json") |
| + if !ok || host == "" { |
| + continue |
| + } |
| + hosts = append(hosts, host) |
| + } |
| + sort.Strings(hosts) |
| + recs := make([]provision.Record, 0, len(hosts)) |
| + for _, host := range hosts { |
| + rec, _, err := provision.ReadRecordJudged(ctx, store, judge, acct, app, host) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + continue |
| + case err != nil: |
| + log.Printf("console: instance record %s/%s/%s: %v", acct, app, host, err) |
| + continue |
| + } |
| + recs = append(recs, *rec) |
| + } |
| + s.boxReports.holdRecords(gen, k, slices.Clone(recs)) |
| + return recs, nil |
| +} |
| + |
| +// remoteSource builds Assemble's remote input for one page view of acct. |
| +func (s *Server) remoteSource(ctx context.Context, acct string) *remoteRows { |
| + if s.cfg.Releases == nil { |
| + return nil |
| + } |
| + return &remoteRows{ |
| + records: func(app string) ([]provision.Record, error) { |
| + rctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout) |
| + defer cancel() |
| + return s.pageRecords(rctx, acct, app) |
| + }, |
| + facts: func(app string) appFacts { return s.remoteFacts(ctx, acct, app) }, |
| + } |
| +} |
| + |
| +// assembleApps is Assemble for a page view: the console box's registry rows |
| +// plus the account's instances on other boxes. |
| +func (s *Server) assembleApps(ctx context.Context, acct string, apps []string) ([]AppView, error) { |
| + return Assemble(ctx, s.cfg.Registry, s.cfg.Releases, s.cfg.ReleasePub, acct, apps, s.dnsTargets(ctx), s.remoteSource(ctx, acct)) |
| +} |
| + |
| +// errRetireUnsettled is channelHosts' answer when no record names the |
| +// channel but the app has not settled long enough for that to mean nobody |
| +// follows it. |
| +var errRetireUnsettled = errors.New("the app's instances have not settled") |
| + |
| +// retireUnsettled is the canary-retire guard's one conservative rule for an |
| +// app with no follower by record. Box reports carry no channel, so nothing |
| +// can prove a box has left a channel; instead the retire waits until the |
| +// app has been still. It returns errRetireUnsettled when: |
| +// |
| +// - any instance or sidecar record of the app was created or changed in |
| +// the last channelSettle, or is missing from the modification-time |
| +// listing (deleted since it was read); |
| +// - any was deleted in the last channelSettle (recentRecordDeletion): |
| +// every console path that deletes a record notes the app in memory |
| +// before deleting (noteRecordDeletion: retireHostRecord, |
| +// retireClaimHostRecord, deleteRead, finishSeedOnce, the owner's purge, |
| +// the claim purge and the expiry purge), |
| +// and the console refuses for channelSettle after it starts; the audit |
| +// log is read too; |
| +// - the box reports cannot all be read; or |
| +// - a fresh box report names this account and app (its rollout entry) for |
| +// a host no record names: a route still up after its record was |
| +// deleted, or a hand route on another box, either of which could be |
| +// following the channel. |
| +// |
| +// The inventory is the records, the console box's routes (channelHosts) and |
| +// the box reports' hosts of the app, all through remoteFacts. |
| +// |
| +// Records of hosts on the console's own box count like any other: a local |
| +// route says where one copy of a host is, not that no other copy exists. |
| +// Other errors (no modification times, a failed listing) fail closed too. |
| +func (s *Server) retireUnsettled(ctx context.Context, acct, app string, keys, hosts map[string]bool) error { |
| + now := time.Now() |
| + unsettled := func(format string, a ...any) error { |
| + return fmt.Errorf("%w: "+format, append([]any{errRetireUnsettled}, a...)...) |
| + } |
| + ml, ok := s.cfg.Releases.(release.ModLister) |
| + if !ok { |
| + return errors.New("the deployment store cannot list modification times, so a recent change cannot be ruled out") |
| + } |
| + listed := map[string]bool{} |
| + for _, prefix := range []string{provision.RecordsPrefix(acct, app), provision.SidecarsPrefix(acct, app)} { |
| + objs, err := ml.ListMod(ctx, prefix) |
| + if err != nil { |
| + return fmt.Errorf("record modification times of %s/%s: %w", acct, app, err) |
| + } |
| + for _, o := range objs { |
| + if !keys[o.Key] { |
| + // Not in the follower read: created since (and so recent, |
| + // which refuses below), or a record the lifetime judge does |
| + // not vouch for any more (retired, stale), which follows |
| + // nothing once it is old. |
| + if recordKeyUnder(o.Key, prefix) && (o.Mod.IsZero() || now.Sub(o.Mod) < channelSettle) { |
| + return unsettled("%s appeared or changed during the window", o.Key) |
| + } |
| + continue |
| + } |
| + listed[o.Key] = true |
| + if o.Mod.IsZero() { |
| + return unsettled("%s has no modification time", o.Key) |
| + } |
| + if now.Sub(o.Mod) < channelSettle { |
| + return unsettled("%s changed %s ago", o.Key, now.Sub(o.Mod).Round(time.Second)) |
| + } |
| + } |
| + } |
| + for key := range keys { |
| + if !listed[key] { |
| + return unsettled("%s has no modification time (deleted since it was read)", key) |
| + } |
| + } |
| + if err := s.recentRecordDeletion(acct, app, now); err != nil { |
| + return err |
| + } |
| + facts := s.remoteFacts(ctx, acct, app) |
| + if !facts.complete() { |
| + return unsettled("not every box report could be read") |
| + } |
| + if host, box, ok := facts.unrecorded(hosts); ok { |
| + return unsettled("box %s still serves %s for this app, which no record names", box, host) |
| + } |
| + return nil |
| +} |
| + |
| +// recordKeyUnder reports whether key is a record key directly under |
| +// prefix: <prefix><name>.json, the shape the record listings read. |
| +func recordKeyUnder(key, prefix string) bool { |
| + rest, ok := strings.CutPrefix(key, prefix) |
| + if !ok || rest == "" || strings.Contains(rest, "/") { |
| + return false |
| + } |
| + name, ok := strings.CutSuffix(rest, ".json") |
| + return ok && name != "" |
| +} |
| + |
| +// recordStamps is every instance and sidecar record key of acct/app with |
| +// its modification time. The canary retire takes it before its check and |
| +// again just before deleting the pointer, and refuses on any difference: |
| +// no lock covers record writes, so this is what notices a follower |
| +// created, moved or deleted in between. |
| +func (s *Server) recordStamps(ctx context.Context, acct, app string) (map[string]time.Time, error) { |
| + out := map[string]time.Time{} |
| + if s.cfg.Releases == nil { |
| + return out, nil |
| + } |
| + ml, ok := s.cfg.Releases.(release.ModLister) |
| + if !ok { |
| + return nil, errors.New("the deployment store cannot list modification times, so a concurrent change cannot be ruled out") |
| + } |
| + for _, prefix := range []string{provision.RecordsPrefix(acct, app), provision.SidecarsPrefix(acct, app)} { |
| + objs, err := ml.ListMod(ctx, prefix) |
| + if err != nil { |
| + return nil, fmt.Errorf("record modification times of %s/%s: %w", acct, app, err) |
| + } |
| + for _, o := range objs { |
| + if recordKeyUnder(o.Key, prefix) { |
| + out[o.Key] = o.Mod |
| + } |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// retireAuditWindow is how many of an app's most recent audit rows the |
| +// deletion check reads; if all of them are inside channelSettle it cannot |
| +// see past them, and says the app has not settled. |
| +const retireAuditWindow = 500 |
| + |
| +// processStart is when this console process started. |
| +var processStart = time.Now() |
| + |
| +// noteRecordDeletion records that an instance or sidecar record of |
| +// acct/app is being deleted now (retireHostRecord calls it first). |
| +// |
| +// It also drops what the pages hold about ownership: the shared box-report |
| +// read is invalidated, and pageRecords reads this app's records from the |
| +// bucket rather than the record view's snapshot until channelSettle has |
| +// passed, so a deleted record cannot keep vouching for its tenant while |
| +// the hostname passes to someone else. |
| +func (s *Server) noteRecordDeletion(acct, app string, at time.Time) { |
| + s.deletionsMu.Lock() |
| + if s.deletions == nil { |
| + s.deletions = map[string]time.Time{} |
| + } |
| + s.deletions[acct+"/"+app] = at |
| + s.deletionsMu.Unlock() |
| + s.boxReports.invalidate() |
| +} |
| + |
| +// recentlyDeleted reports whether the console began deleting a record of |
| +// acct/app within channelSettle. |
| +func (s *Server) recentlyDeleted(acct, app string, now time.Time) bool { |
| + s.deletionsMu.Lock() |
| + defer s.deletionsMu.Unlock() |
| + at, ok := s.deletions[acct+"/"+app] |
| + return ok && now.Sub(at) < channelSettle |
| +} |
| + |
| +// recentRecordDeletion is errRetireUnsettled when an instance or sidecar of |
| +// acct/app may have been deleted within channelSettle. Every console path |
| +// that deletes a record notes it in memory before deleting; a console that started within channelSettle cannot vouch for |
| +// the time before it started, so it refuses until it has been up that |
| +// long. The audit log is read as well, for a deletion another console |
| +// process sharing this database made. |
| +func (s *Server) recentRecordDeletion(acct, app string, now time.Time) error { |
| + s.deletionsMu.Lock() |
| + at, deleted := s.deletions[acct+"/"+app] |
| + s.deletionsMu.Unlock() |
| + if deleted && now.Sub(at) < channelSettle { |
| + return fmt.Errorf("%w: a record of %s/%s was deleted %s ago", errRetireUnsettled, acct, app, now.Sub(at).Round(time.Second)) |
| + } |
| + started := s.startedAt |
| + if started.IsZero() { |
| + started = processStart |
| + } |
| + if now.Sub(started) < channelSettle { |
| + return fmt.Errorf("%w: the console started %s ago and cannot vouch for deletions before that", errRetireUnsettled, now.Sub(started).Round(time.Second)) |
| + } |
| + a, err := s.store.AccountBySqid(acct) |
| + if err != nil || a == nil { |
| + return fmt.Errorf("%w: the account's audit log cannot be read: %v", errRetireUnsettled, err) |
| + } |
| + events, err := s.store.Events(a.ID, app, retireAuditWindow) |
| + if err != nil { |
| + return fmt.Errorf("%w: the app's audit log cannot be read: %v", errRetireUnsettled, err) |
| + } |
| + for _, e := range events { |
| + if now.Sub(e.CreatedAt) >= channelSettle { |
| + return nil // newest first: nothing older can be recent |
| + } |
| + if e.Action == "instance-delete" || e.Action == "sidecar-delete" { |
| + return fmt.Errorf("%w: %s deleted %s ago", errRetireUnsettled, e.Target, now.Sub(e.CreatedAt).Round(time.Second)) |
| + } |
| + } |
| + if len(events) >= retireAuditWindow { |
| + return fmt.Errorf("%w: the audit log is too busy to rule out a recent deletion", errRetireUnsettled) |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/remoteinstances_round1_test.go b/internal/console/remoteinstances_round1_test.go| new file mode 100644 |
| index 000000000..039860939 |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_round1_test.go |
| @@ -0,0 +1,300 @@ |
| +package console |
| + |
| +// Round 1 review fixes (Astra, f2b993c3) for remoteinstances.go: each test |
| +// here failed against that tip. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// sweepAt is sweep at a chosen sample time. |
| +func sweepAt(t *testing.T, rel release.Store, box string, at time.Time, units map[string]metrics.UnitSample) { |
| + t.Helper() |
| + at = at.UTC() |
| + if err := metrics.WriteRaw(context.Background(), rel, metrics.RawChunk{ |
| + V: 1, Box: box, Hour: metrics.HourOf(at), |
| + Samples: []metrics.Sample{{At: at, Units: units}}, |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// P1: this account's record names a host, but the only box serving it says |
| +// it is another account's. That report is refused, and so must be every |
| +// reading of the host: its CPU and memory are the other tenant's. |
| +func TestRemoteMetricsRefuseRejectedReport(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + // Box B serves the host for another account (no reconcile on B: the |
| + // row is someone else's). |
| + if err := tb.regB.Upsert(registry.Route{Host: remoteHost, Kind: "instance", App: "shop", Account: "rvl", |
| + Channel: "stable", Version: "v8", Provisioned: true, Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), map[string]bool{remoteHost: true}, 4096) |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + for _, path := range []string{"/apps/shop", "/apps/shop/instances", "/apps/shop/instances/" + remoteHost} { |
| + body := tb.page(t, path) |
| + for _, bad := range []string{"66%", "7.0 MB", "v8", "4.0 KB"} { |
| + if strings.Contains(body, bad) { |
| + t.Fatalf("%s shows %q from a report naming another account:\n%s", path, bad, body) |
| + } |
| + } |
| + } |
| + row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost) |
| + if strings.Contains(row, "Running") { |
| + t.Fatalf("the refused tenant's readings made the row Running: %s", row) |
| + } |
| + if status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); status != http.StatusOK || strings.Contains(out, `"health":"Running"`) { |
| + t.Fatalf("instances list = %d %s", status, out) |
| + } |
| +} |
| + |
| +// P2: with an incomplete read of the box reports, a remote instance's state |
| +// is unknown, and every page says so rather than guessing Asleep. |
| +func TestRemoteUnknownStateRendersUnknown(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + // One box report that will not parse: the read is incomplete, and no |
| + // readable report names the host. |
| + if _, err := tb.fx.rel.Put(context.Background(), "status/boxes/broken.json", []byte("{not json"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + run := tb.page(t, "/apps/shop/instances") |
| + row := instanceRow(t, run, remoteHost) |
| + if !strings.Contains(row, "Can't tell right now") || strings.Contains(row, "Asleep") || strings.Contains(row, "Not responding") { |
| + t.Fatalf("Running row for an unknown remote instance = %s", row) |
| + } |
| + inst := tb.page(t, "/apps/shop/instances/"+remoteHost) |
| + if !strings.Contains(inst, "<dt>Health</dt><dd>Can't tell right now</dd>") || strings.Contains(inst, "wakes on the next request") { |
| + t.Fatalf("instance page for an unknown remote instance:\n%s", inst) |
| + } |
| + ov := tb.page(t, "/apps/shop") |
| + if !strings.Contains(ov, "Can't tell right now") || !strings.Contains(ov, "no data right now") || strings.Contains(ov, "no readings for 0 copies") || strings.Contains(ov, "asleep") { |
| + t.Fatalf("overview for an unknown remote instance:\n%s", ov) |
| + } |
| + if status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); status != http.StatusOK || !strings.Contains(out, `"health":"Can't tell right now"`) { |
| + t.Fatalf("instances list = %d %s", status, out) |
| + } |
| +} |
| + |
| +// P2: a report that names no tenant (an older box) gives a version, but not |
| +// the process state: a resident or static row must not read Not responding |
| +// or Serving on that evidence. |
| +func TestRemoteUnknownTenantReportHealth(t *testing.T) { |
| + now := time.Now() |
| + boxes := []status.Box{{GeneratedAt: now, Label: "b", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"r.example.com": "v2", "s.example.com": "v2"}}}} |
| + f := foldFleetReports(boxes, true, now) |
| + no := false |
| + var routes []RouteView |
| + var domains []DomainView |
| + for _, rec := range []provision.Record{ |
| + {Host: "r.example.com", App: "shop", Account: "a", Hibernate: &no, Addr: "127.0.0.1:1"}, |
| + {Host: "s.example.com", App: "shop", Account: "a", Kind: "static"}, |
| + } { |
| + rv, dv := remoteRoute(rec, factsOf(f, "a", "shop").host(rec), factsOf(f, "a", "shop"), "a", DNSTargets{}) |
| + routes, domains = append(routes, rv), append(domains, dv) |
| + } |
| + view := &AppView{Routes: routes, Domains: domains} |
| + for _, row := range assembleInstanceRows(view, &Account{Sqid: "a"}, []InstanceMetrics{}) { |
| + if row.HealthWord != "Can't tell right now" { |
| + t.Fatalf("%s health = %q on a report naming no tenant", row.Host, row.HealthWord) |
| + } |
| + } |
| + if st := assembleOverview(view, "a", []InstanceMetrics{}, nil, boxJoin{}); st.VerdictLabel != "Can't tell right now" { |
| + t.Fatalf("verdict = %q", st.VerdictLabel) |
| + } |
| +} |
| + |
| +// reportStore serves status/boxes/ with a controllable listing. |
| +type reportStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + lists int |
| + onList func() error |
| + failGet bool |
| +} |
| + |
| +func (s *reportStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + if strings.HasPrefix(prefix, "status/boxes/") { |
| + s.mu.Lock() |
| + s.lists++ |
| + fn := s.onList |
| + s.mu.Unlock() |
| + if fn != nil { |
| + if err := fn(); err != nil { |
| + return nil, err |
| + } |
| + } |
| + } |
| + return s.Store.List(ctx, prefix) |
| +} |
| + |
| +func (s *reportStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if s.failGet && strings.HasPrefix(key, "status/boxes/") { |
| + return nil, "", errors.New("boom") |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +func (s *reportStore) listCount() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.lists |
| +} |
| + |
| +func cacheServer(t *testing.T, rs *reportStore) (*Server, *time.Time) { |
| + t.Helper() |
| + clock := time.Now() |
| + s := &Server{cfg: Config{Releases: rs}} |
| + s.boxReports.now = func() time.Time { return clock } |
| + return s, &clock |
| +} |
| + |
| +// P3: a load that fails after a long wait is held for the failure TTL from |
| +// when it FINISHED, not from when it started. |
| +func TestBoxReportCacheSlowFailureIsHeld(t *testing.T) { |
| + rs := &reportStore{Store: release.NewDirStore(t.TempDir())} |
| + s, clock := cacheServer(t, rs) |
| + rs.onList = func() error { |
| + *clock = clock.Add(15 * time.Second) // the load ran to its timeout |
| + return errors.New("slow and failed") |
| + } |
| + s.pageBoxReports(context.Background()) |
| + s.pageBoxReports(context.Background()) |
| + if n := rs.listCount(); n != 1 { |
| + t.Fatalf("box report listings = %d, want 1: a just-finished failed load was treated as already expired", n) |
| + } |
| +} |
| + |
| +// P3: a read that skipped a box (complete false) is a failed read and is |
| +// held for the failure TTL only. |
| +func TestBoxReportCacheIncompleteIsShortLived(t *testing.T) { |
| + inner := release.NewDirStore(t.TempDir()) |
| + b := status.CollectBox(nil, status.Probes{MachineID: "m"}, time.Now()) |
| + if err := status.WriteBox(context.Background(), inner, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + rs := &reportStore{Store: inner, failGet: true} |
| + s, clock := cacheServer(t, rs) |
| + if _, complete := s.pageBoxReports(context.Background()); complete { |
| + t.Fatal("fixture: the read was complete") |
| + } |
| + *clock = clock.Add(boxReportFailTTL + time.Second) |
| + s.pageBoxReports(context.Background()) |
| + if n := rs.listCount(); n != 2 { |
| + t.Fatalf("box report listings = %d, want 2: an incomplete read was held as long as a good one", n) |
| + } |
| +} |
| + |
| +// P3: a viewer waiting behind a slow load can give up when its own request |
| +// is cancelled. |
| +func TestBoxReportCacheWaitIsCancellable(t *testing.T) { |
| + release1 := make(chan struct{}) |
| + started := make(chan struct{}) |
| + rs := &reportStore{Store: release.NewDirStore(t.TempDir())} |
| + rs.onList = func() error { close(started); <-release1; return nil } |
| + s, _ := cacheServer(t, rs) |
| + defer close(release1) |
| + go s.pageBoxReports(context.Background()) |
| + <-started |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + done := make(chan struct{}) |
| + go func() { s.pageBoxReports(ctx); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("a cancelled viewer stayed queued behind the slow load") |
| + } |
| +} |
| + |
| +// P4: more records than the old 500 cap. None may be dropped: the last |
| +// host (sorted) shows on the Running tab and its instance page renders. |
| +func TestRemoteRecordsNotCapped(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + const last = "zz-last.shop.example.com" |
| + for i := 0; i <= instanceListMax; i++ { |
| + host := last |
| + if i < instanceListMax { |
| + host = fmt.Sprintf("h%04d.shop.example.com", i) |
| + } |
| + if err := provision.CreateRecord(ctx, tb.fx.rel, provision.Record{Schema: 1, Host: host, Slug: strings.SplitN(host, ".", 2)[0], |
| + App: "shop", Account: tb.sqid, Pool: "shop", Region: "uk", Channel: "stable", CreatedAt: now}); err != nil { |
| + t.Fatalf("record %s: %v", host, err) |
| + } |
| + } |
| + views, err := tb.fx.srv.assembleApps(ctx, tb.sqid, []string{"shop"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := len(views[0].Routes); n != instanceListMax+1 { |
| + t.Fatalf("rows = %d, want %d", n, instanceListMax+1) |
| + } |
| + if status, _, body := get(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+"/apps/shop/instances/"+last); status != http.StatusOK { |
| + t.Fatalf("instance page for the record past the old cap = %d\n%s", status, body) |
| + } |
| +} |
| + |
| +// P1, `carlos instances list`: the accepted box reports the instance asleep |
| +// and has no sample; another box's sample of the same unit must not make |
| +// it Running. |
| +func TestRemoteInstancesListPinnedToAcceptedBox(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + sweep(t, tb.fx.rel, status.Label("box-c"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + if status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); status != http.StatusOK || !strings.Contains(out, `"health":"Asleep"`) { |
| + t.Fatalf("instances list = %d %s, want Asleep from the accepted box", status, out) |
| + } |
| + if ov := tb.page(t, "/apps/shop"); strings.Contains(ov, "66%") { |
| + t.Fatalf("overview shows another box's reading:\n%s", ov) |
| + } |
| +} |
| + |
| +// P1/P2, `carlos instances list`: an older box's report names no tenant. |
| +// Its version may show, but its readings do not join and the health is |
| +// unknown. |
| +func TestRemoteInstancesListUnknownTenant(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + routes, err := tb.regB.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b := status.CollectBox(routes, status.Probes{MachineID: "box-b", Region: "uk"}, time.Now()) // no rollout report |
| + if err := status.WriteBox(context.Background(), tb.fx.rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + if status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); status != http.StatusOK || !strings.Contains(out, `"health":"Can't tell right now"`) { |
| + t.Fatalf("instances list = %d %s", status, out) |
| + } |
| + if ov := tb.page(t, "/apps/shop"); strings.Contains(ov, "66%") { |
| + t.Fatalf("overview joined readings on a report naming no tenant:\n%s", ov) |
| + } |
| +} |
diff --git a/internal/console/remoteinstances_round2_test.go b/internal/console/remoteinstances_round2_test.go| new file mode 100644 |
| index 000000000..ae36f2a9c |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_round2_test.go |
| @@ -0,0 +1,220 @@ |
| +package console |
| + |
| +// Round 2 review fixes (Astra, 02edd585): each test here failed against |
| +// that tip. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// twoSamples writes box's chunk with an old sample of unit (another |
| +// tenant's, before the current owner existed) and a current one. |
| +func twoSamples(t *testing.T, rel release.Store, box, unit string, old, cur time.Time) { |
| + t.Helper() |
| + ctx := context.Background() |
| + // Separate hours keep each sample in its own chunk, as a real sweep would. |
| + for _, s := range []struct { |
| + at time.Time |
| + cpu float64 |
| + mem int64 |
| + }{{old, 0.90, 64 << 20}, {cur, 0.27, 3 << 20}} { |
| + at := s.at.UTC() |
| + if err := metrics.WriteRaw(ctx, rel, metrics.RawChunk{V: 1, Box: box, Hour: metrics.HourOf(at), |
| + Samples: []metrics.Sample{{At: at, Units: map[string]metrics.UnitSample{unit: {CPUFrac: p(s.cpu), MemBytes: pi64(s.mem)}}}}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +func points(spark string) int { |
| + if spark == "" { |
| + return 0 |
| + } |
| + return len(strings.Fields(spark)) |
| +} |
| + |
| +// P1, the same leak on the console's own box: an instance created now |
| +// whose hostname another tenant's unit used earlier in the window. Its |
| +// record's created_at bounds the local row's history too. (A hand route |
| +// with no record has no such start and stays unbounded, as before.) |
| +func TestLocalMetricsHistoryBoundedByRecord(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "") |
| + tb.reconcile(t, "v3") |
| + twoSamples(t, tb.fx.rel, "box-console", "carlos-exec@"+localHost, time.Now().Add(-3*time.Hour), time.Now()) |
| + views, err := tb.fx.srv.assembleApps(context.Background(), tb.sqid, []string{"shop"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, m := range tb.fx.srv.appResourceMetrics(context.Background(), &views[0], tb.account(t)) { |
| + if m.Host != localHost { |
| + continue |
| + } |
| + if n := points(m.SparkCPU); n != 1 || strings.Contains(m.SparkCPU, ",4.00") { |
| + t.Fatalf("local CPU graph carries samples from before the record (%d points): %q", n, m.SparkCPU) |
| + } |
| + return |
| + } |
| + t.Fatal("no metrics row for the local instance") |
| +} |
| + |
| +// P1: with no ownership start, no readings; a current sample older than the |
| +// ownership start is not this owner's either. |
| +func TestOwnerMetricsSinceRules(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + const host = "h.example.com" |
| + twoSamples(t, fx.rel, "box-x", "carlos-exec@"+host, time.Now().Add(-3*time.Hour), time.Now().Add(-90*time.Second)) |
| + for name, since := range map[string]time.Time{"unknown start": {}, "start after the newest sample": time.Now().Add(-time.Minute)} { |
| + fx.srv.metricsCache = metricsCache{} |
| + am, err := fx.srv.ownerAppMetricsFrom(context.Background(), []string{host}, nil, map[string]time.Time{host: since}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(am) != 1 || am[0].Reporting() || am[0].SparkCPU != "" || am[0].SparkMem != "" { |
| + t.Fatalf("%s: metrics = %+v, want none", name, am) |
| + } |
| + } |
| +} |
| + |
| +// heldReport writes box B's report with one host's rollout entry shaped by |
| +// edit. |
| +func heldReport(t *testing.T, tb *twoBoxes, edit func(*status.HostRollout)) { |
| + t.Helper() |
| + routes, err := tb.regB.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ro := &status.RolloutReport{Hosts: map[string]status.HostRollout{}} |
| + for _, rt := range routes { |
| + hr := status.HostRollout{Account: rt.Account, App: rt.App, Installed: rt.Version, Good: rt.Version} |
| + edit(&hr) |
| + ro.Hosts[rt.Host] = hr |
| + } |
| + b := status.CollectBox(routes, status.Probes{MachineID: "box-b", Region: "uk", Rollout: ro}, time.Now()) |
| + if err := status.WriteBox(context.Background(), tb.fx.rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// P2: a hibernating remote instance held down by a failed hold-mode build |
| +// is not asleep and not all good. |
| +func TestRemoteHeldDownIsUnhealthy(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + heldReport(t, tb, func(hr *status.HostRollout) { |
| + hr.Attempt, hr.AttemptBuild, hr.HeldBy, hr.Reason = status.AttemptDown, "v4", "v4", status.ReasonExit |
| + }) |
| + row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost) |
| + if !strings.Contains(row, ">Failed<") || strings.Contains(row, "Asleep") { |
| + t.Fatalf("Running row for a held-down remote instance = %s", row) |
| + } |
| + inst := tb.page(t, "/apps/shop/instances/"+remoteHost) |
| + if strings.Contains(inst, "wakes on the next request") || !strings.Contains(inst, "<dt>Health</dt><dd>Failed</dd>") { |
| + t.Fatalf("instance page for a held-down remote instance:\n%s", inst) |
| + } |
| + if ov := tb.page(t, "/apps/shop"); strings.Contains(ov, "All good") || !strings.Contains(ov, "Needs attention") { |
| + t.Fatalf("overview for a held-down remote instance:\n%s", ov) |
| + } |
| + if status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); status != http.StatusOK || !strings.Contains(out, `"health":"Failed"`) { |
| + t.Fatalf("instances list = %d %s", status, out) |
| + } |
| +} |
| + |
| +// P2: a remote instance mid-start or mid-stop (transient) is not healthy |
| +// sleep. |
| +func TestRemoteTransientIsNotAsleep(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + heldReport(t, tb, func(hr *status.HostRollout) { hr.Transient = true }) |
| + row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost) |
| + if strings.Contains(row, "Asleep") || !strings.Contains(row, "Can't tell right now") { |
| + t.Fatalf("Running row for a transient remote instance = %s", row) |
| + } |
| + if ov := tb.page(t, "/apps/shop"); strings.Contains(ov, "All good") { |
| + t.Fatalf("overview calls a transient remote instance all good:\n%s", ov) |
| + } |
| + if status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); status != http.StatusOK || strings.Contains(out, `"health":"Asleep"`) { |
| + t.Fatalf("instances list = %d %s", status, out) |
| + } |
| +} |
| + |
| +// Round 1 P2, completed: a static-only app whose remote state is unknown is |
| +// neither "All good" nor "Served", and its account-home row can't tell. |
| +func TestRemoteUnknownStaticIsNotServed(t *testing.T) { |
| + f := foldFleetReports(nil, false, time.Now()) |
| + rv, dv := remoteRoute(provision.Record{Host: "s.example.com", App: "shop", Account: "a", Kind: "static"}, nil, factsOf(f, "a", "shop"), "a", DNSTargets{}) |
| + view := &AppView{App: "shop", Routes: []RouteView{rv}, Domains: []DomainView{dv}} |
| + if st := assembleOverview(view, "a", []InstanceMetrics{}, nil, boxJoin{}); st.VerdictLabel != "Can't tell right now" || st.InstanceUnknown != 1 { |
| + t.Fatalf("static unknown overview = %q (unknown %d)", st.VerdictLabel, st.InstanceUnknown) |
| + } |
| + if row := summarize(*view, "a"); row.VerdictLabel != "Can't tell right now" { |
| + t.Fatalf("account home row = %q", row.VerdictLabel) |
| + } |
| +} |
| + |
| +// P1, `carlos instances list`: the box's newest sample of the hostname is |
| +// from before this account's record existed (a previous tenant's process). |
| +// It must not make this record Running. |
| +func TestRemoteInstancesListIgnoresPreviousTenantSample(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + before := time.Now().Add(-30 * time.Second) |
| + sweepAt(t, tb.fx.rel, status.Label("box-b"), before, map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + time.Sleep(1100 * time.Millisecond) // created_at is whole seconds |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + if status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); status != http.StatusOK || strings.Contains(out, `"health":"Running"`) { |
| + t.Fatalf("instances list = %d %s: a sample from before the record made it Running", status, out) |
| + } |
| +} |
| + |
| +// Codex round 2 (census review of d09ea830), P1: a provisioned local row |
| +// whose record cannot be read has no known ownership start, so it shows no |
| +// readings rather than the whole window. |
| +func TestLocalMetricsUnknownStartHasNoReadings(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "") |
| + tb.reconcile(t, "v3") |
| + sweepAt(t, tb.fx.rel, "box-console", time.Now(), map[string]metrics.UnitSample{"carlos-exec@" + localHost: {CPUFrac: p(0.5), MemBytes: pi64(1 << 20)}}) |
| + tb.fx.srv.cfg.Releases = remoteFailingRecordStore{tb.fx.rel, "/instances/"} |
| + views, err := tb.fx.srv.assembleApps(context.Background(), tb.sqid, []string{"shop"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, m := range tb.fx.srv.appResourceMetrics(context.Background(), &views[0], tb.account(t)) { |
| + if m.Host == localHost && m.Reporting() { |
| + t.Fatalf("a provisioned local row with no readable record showed readings: %+v", m) |
| + } |
| + } |
| +} |
| + |
| +// listModHiding drops one key from ListMod: a record deleted between its |
| +// read and the modification-time listing. |
| +type listModHiding struct { |
| + *deletableStore |
| + hide string |
| +} |
| + |
| +func (s listModHiding) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + objs, err := s.deletableStore.ListMod(ctx, prefix) |
| + var out []release.KeyMod |
| + for _, o := range objs { |
| + if o.Key != s.hide { |
| + out = append(out, o) |
| + } |
| + } |
| + return out, err |
| +} |
diff --git a/internal/console/remoteinstances_round3_test.go b/internal/console/remoteinstances_round3_test.go| new file mode 100644 |
| index 000000000..6506ec6db |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_round3_test.go |
| @@ -0,0 +1,329 @@ |
| +package console |
| + |
| +// Round 3 review fixes (Astra, 18b5884b). |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// P1: a box report with no tenant identity for the host (no rollout entry) |
| +// contributes nothing to this account's row: no version, size, domains, |
| +// certificate date or readings. The host's state is unknown. |
| +func TestRemoteUnidentifiedReportContributesNothing(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + certAt := time.Date(2027, 1, 15, 0, 0, 0, 0, time.UTC).Unix() |
| + if err := tb.regB.SetDNSStatus(remoteHost, "pointing", time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.regB.SetCertExpiresAt(remoteHost, certAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.regB.UpsertAlias(registry.RouteAlias{Alias: "www.shop-store.example", Host: remoteHost, |
| + Account: tb.sqid, App: "shop", DNSStatus: "pointing", CertExpiresAt: certAt}); err != nil { |
| + t.Fatal(err) |
| + } |
| + routes, err := tb.regB.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + aliases, err := tb.regB.ListAliases() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + b := status.CollectBox(routes, status.Probes{MachineID: "box-b", Region: "uk", Aliases: aliases, |
| + DBBytes: func(string) *int64 { n := int64(9216); return &n }}, time.Now()) // no rollout report |
| + if err := status.WriteBox(context.Background(), tb.fx.rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost) |
| + if strings.Contains(row, "v3") || strings.Contains(row, "66%") || !strings.Contains(row, "Can't tell right now") { |
| + t.Fatalf("Running row joined an unidentified report: %s", row) |
| + } |
| + for path, bad := range map[string][]string{ |
| + "/apps/shop": {"9.0 KB", "66%", "DNS & certs OK"}, |
| + "/apps/shop/instances/" + remoteHost: {"www.shop-store.example", "renews 2027-01-15", "66%"}, |
| + "/apps/shop/settings/domains": {"renews 2027-01-15"}, |
| + } { |
| + body := tb.page(t, path) |
| + for _, b := range bad { |
| + if strings.Contains(body, b) { |
| + t.Fatalf("%s shows %q from a report with no tenant identity:\n%s", path, b, body) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// Round 2's held-down fix, completed: a metrics sample from before the |
| +// failure must not count the instance as reporting. |
| +func TestRemoteHeldDownWithSampleIsNotAllGood(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + heldReport(t, tb, func(hr *status.HostRollout) { |
| + hr.Attempt, hr.AttemptBuild, hr.HeldBy, hr.Reason = status.AttemptDown, "v4", "v4", status.ReasonExit |
| + }) |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.27), MemBytes: pi64(3 << 20)}, |
| + }) |
| + if ov := tb.page(t, "/apps/shop"); strings.Contains(ov, "All good") || !strings.Contains(ov, "Needs attention") { |
| + t.Fatalf("overview for a held-down instance with a reading:\n%s", ov) |
| + } |
| +} |
| + |
| +// ageRecords backdates every instance and sidecar record of the app past |
| +// the settle window, as if nothing had changed for a while. |
| +func ageRecords(t *testing.T, tb *twoBoxes) { |
| + t.Helper() |
| + root := tb.fx.rel.(*deletableStore).root |
| + old := time.Now().Add(-channelSettle - time.Minute) |
| + for _, prefix := range []string{provision.RecordsPrefix(tb.sqid, "shop"), provision.SidecarsPrefix(tb.sqid, "shop")} { |
| + keys, err := tb.fx.rel.List(context.Background(), prefix) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, k := range keys { |
| + if err := os.Chtimes(filepath.Join(root, k), old, old); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// retireRC posts the confirmed retire of canary/rc and returns the page it |
| +// lands on. |
| +func retireRC(t *testing.T, tb *twoBoxes) string { |
| + t.Helper() |
| + status, loc, body := postForm(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+"/apps/shop/canary/retire", |
| + url.Values{"csrf": {sessionToken(t, tb.fx, tb.browser)}, "name": {"rc"}, "confirmed": {"1"}}) |
| + if status != http.StatusSeeOther { |
| + t.Fatalf("retire = %d %s", status, body) |
| + } |
| + _, _, page := get(t, tb.browser, tb.fx.ts.URL+loc) |
| + return page |
| +} |
| + |
| +func rcPointer(t *testing.T, tb *twoBoxes) bool { |
| + t.Helper() |
| + _, _, err := tb.fx.rel.Get(context.Background(), release.ChannelKey(tb.sqid, "shop", "canary/rc")) |
| + return err == nil |
| +} |
| + |
| +const notSettled = "Could not verify no hosts follow this channel — try again." |
| + |
| +// P2 #2-#4 (one rule): a remote follower is moved off canary/rc and its box |
| +// has not reconciled (B paused). No record names rc, but a record changed |
| +// within the window, so the retire is refused, whatever B's report says. |
| +// Once the app has been still for the window it goes through. |
| +func TestRetireWaitsAfterChannelChange(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v5", "canary/next") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.reconcile(t, "v4") |
| + if status, _, out := rawReq(t, http.MethodPost, instancesURL(tb.fx, tb.sqid, "shop")+"/"+remoteHost+"/channel", tb.token, |
| + `{"channel":"canary/next"}`); status != http.StatusOK { |
| + t.Fatalf("channel move = %d %s", status, out) |
| + } |
| + // B reports the host on canary/next's build even though it has not |
| + // reconciled: a build is no proof of a channel any more. |
| + if err := tb.regB.SetVersions(remoteHost, "v5", "v4"); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + if page := retireRC(t, tb); !strings.Contains(page, notSettled) || !rcPointer(t, tb) { |
| + t.Fatalf("retire right after a channel change was not refused:\n%s", page) |
| + } |
| + ageRecords(t, tb) |
| + if page := retireRC(t, tb); !strings.Contains(page, "Retired canary rc") { |
| + t.Fatalf("retire once the app was still for the window:\n%s", page) |
| + } |
| +} |
| + |
| +// P2 #3: a recently changed record of a host on the console's own box |
| +// counts too; a local route does not short-circuit a remote copy. |
| +func TestRetireWaitsAfterLocalHostChange(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v5", "canary/next") |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "canary/rc") |
| + tb.reconcile(t, "v4") |
| + if status, _, out := rawReq(t, http.MethodPost, instancesURL(tb.fx, tb.sqid, "shop")+"/"+localHost+"/channel", tb.token, |
| + `{"channel":"canary/next"}`); status != http.StatusOK { |
| + t.Fatalf("channel move = %d %s", status, out) |
| + } |
| + tb.reconcile(t, "") // the console's box converges; another copy may not have |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + if page := retireRC(t, tb); !strings.Contains(page, notSettled) || !rcPointer(t, tb) { |
| + t.Fatalf("retire right after a local host's channel change was not refused:\n%s", page) |
| + } |
| +} |
| + |
| +// P2 #5: the only remote follower's record is deleted, and its box has not |
| +// reconciled the deletion. Through the delete door, the audit log dates the |
| +// deletion; behind the console's back (a direct bucket delete), the box's |
| +// report still serving a host no record names holds the retire, until the |
| +// box drops the route. |
| +func TestRetireWaitsAfterDeletion(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.reconcile(t, "v4") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + if status, _, out := rawReq(t, http.MethodDelete, instancesURL(tb.fx, tb.sqid, "shop")+"/"+remoteHost, tb.token, ""); status != http.StatusOK { |
| + t.Fatalf("delete = %d %s", status, out) |
| + } |
| + // The audit row is best-effort: as if its write had failed. |
| + if _, err := tb.fx.st.db.Exec(`DELETE FROM audit`); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.fx.srv.boxReports.expire() |
| + hosts, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc") |
| + if !errorsIsUnsettled(err) || len(hosts) != 0 { |
| + t.Fatalf("after a delete through the door = %v %v, want unsettled", hosts, err) |
| + } |
| + if !strings.Contains(err.Error(), "deleted") { |
| + t.Fatalf("unsettled for the wrong reason: %v", err) |
| + } |
| +} |
| + |
| +func TestRetireWaitsForRouteOfDeletedRecord(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.reconcile(t, "v4") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + // Deleted behind the console's back: no audit row. |
| + if err := tb.fx.rel.Delete(context.Background(), provision.RecordKey(tb.sqid, "shop", remoteHost)); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.fx.srv.boxReports.expire() |
| + if page := retireRC(t, tb); !strings.Contains(page, notSettled) || !rcPointer(t, tb) { |
| + t.Fatalf("retire while box B still serves the deleted record's host:\n%s", page) |
| + } |
| + tb.reconcile(t, "") // B drops the route |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + if page := retireRC(t, tb); !strings.Contains(page, "Retired canary rc") { |
| + t.Fatalf("retire once B dropped the route:\n%s", page) |
| + } |
| +} |
| + |
| +// P2 #2: a box report that cannot be read refuses the retire. |
| +func TestRetireRefusedOnIncompleteReports(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + if _, err := tb.fx.rel.Put(context.Background(), "status/boxes/broken.json", []byte("{not json"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.fx.srv.boxReports.expire() |
| + if page := retireRC(t, tb); !strings.Contains(page, notSettled) || !rcPointer(t, tb) { |
| + t.Fatalf("retire with an unreadable box report:\n%s", page) |
| + } |
| + if err := tb.fx.rel.Delete(context.Background(), "status/boxes/broken.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.fx.srv.boxReports.expire() |
| + if page := retireRC(t, tb); !strings.Contains(page, "Retired canary rc") { |
| + t.Fatalf("retire with every report read and a still app:\n%s", page) |
| + } |
| +} |
| + |
| +// A record missing from the modification-time listing (deleted since it |
| +// was read) is not settled. |
| +func TestRetireRefusedOnRecordWithoutModTime(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + ds := tb.fx.rel.(*deletableStore) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + tb.fx.srv.boxReports.expire() |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); err != nil { |
| + t.Fatalf("fixture: a still app = %v", err) |
| + } |
| + tb.fx.srv.cfg.Releases = listModHiding{ds, provision.RecordKey(tb.sqid, "shop", remoteHost)} |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); !errorsIsUnsettled(err) { |
| + t.Fatalf("a record missing from the modification-time listing = %v, want unsettled", err) |
| + } |
| +} |
| + |
| +func errorsIsUnsettled(err error) bool { return errors.Is(err, errRetireUnsettled) } |
| + |
| +// Codex census review of ba69fcc1: deletion evidence that cannot fail. A |
| +// record deleted through retireHostRecord with no audit row at all (the |
| +// audit write is best-effort) still holds the retire; a console that has |
| +// just started cannot vouch for deletions before it, so it holds every |
| +// retire for the window; and a listed record with a zero modification time |
| +// is not settled. |
| +func TestRetireDeletionEvidenceCannotFail(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + tb.fx.srv.boxReports.expire() |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); err != nil { |
| + t.Fatalf("fixture: a still app = %v", err) |
| + } |
| + |
| + // Zero modification time. |
| + ds := tb.fx.rel.(*deletableStore) |
| + tb.fx.srv.cfg.Releases = zeroModStore{ds} |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); !errorsIsUnsettled(err) { |
| + t.Fatalf("a zero modification time = %v, want unsettled", err) |
| + } |
| + tb.fx.srv.cfg.Releases = ds |
| + |
| + // Just started. |
| + started := tb.fx.srv.startedAt |
| + tb.fx.srv.startedAt = time.Now().Add(-time.Minute) |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); !errorsIsUnsettled(err) { |
| + t.Fatalf("a console up for a minute = %v, want unsettled", err) |
| + } |
| + tb.fx.srv.startedAt = started |
| + |
| + // A deletion with no audit row: retireHostRecord itself, not the door. |
| + if err := tb.fx.srv.retireInstanceRecord(context.Background(), tb.sqid, "shop", localHost, "test", "", provision.RetireExpectation{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); !errorsIsUnsettled(err) || !strings.Contains(err.Error(), "deleted") { |
| + t.Fatalf("after an unaudited deletion = %v, want unsettled", err) |
| + } |
| +} |
| + |
| +// zeroModStore lists every record with a zero modification time. |
| +type zeroModStore struct{ *deletableStore } |
| + |
| +func (s zeroModStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + objs, err := s.deletableStore.ListMod(ctx, prefix) |
| + for i := range objs { |
| + objs[i].Mod = time.Time{} |
| + } |
| + return objs, err |
| +} |
diff --git a/internal/console/remoteinstances_round4_test.go b/internal/console/remoteinstances_round4_test.go| new file mode 100644 |
| index 000000000..c0470a852 |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_round4_test.go |
| @@ -0,0 +1,274 @@ |
| +package console |
| + |
| +// Round 4 review fixes (Astra, d8f11e4f). |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rollout" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +const residentHost = "always.shop.example.com" |
| + |
| +// Round 5 (by ruling): a remote instance that never sleeps is outside the |
| +// rollout report (rollout.Managed), so no report names its tenant. Its row |
| +// shows the record's facts and "Can't tell right now"; nothing of the |
| +// box's report joins: not the version, not a reading. |
| +func TestRemoteResidentInstanceIsUnknown(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + no := false |
| + if err := provision.CreateRecord(context.Background(), tb.fx.rel, provision.Record{Schema: 1, Host: residentHost, Slug: "always", |
| + App: "shop", Account: tb.sqid, Pool: "shop", Region: "uk", Channel: "stable", Hibernate: &no, CreatedAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.reconcile(t, "v3") |
| + rt, err := tb.regB.Get(residentHost) |
| + if err != nil || rt == nil { |
| + t.Fatalf("fixture: B did not mint the resident instance: %v", err) |
| + } |
| + if rollout.Managed(*rt) { |
| + t.Fatalf("fixture: the resident route is rollout-managed: %+v", rt) |
| + } |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + residentHost: {CPUFrac: p(0.27), MemBytes: pi64(3 << 20)}, |
| + }) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + row := instanceRow(t, tb.page(t, "/apps/shop/instances"), residentHost) |
| + if strings.Contains(row, "v3") || !strings.Contains(row, "Can't tell right now") || !strings.Contains(row, "stable") || strings.Contains(row, "27%") { |
| + t.Fatalf("Running row for a resident remote instance = %s", row) |
| + } |
| + if ov := tb.page(t, "/apps/shop"); strings.Contains(ov, "27%") || strings.Contains(ov, "4.0 KB") { |
| + t.Fatalf("overview joined an unidentified report:\n%s", ov) |
| + } |
| + if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK || |
| + !strings.Contains(out, `"health":"Can't tell right now"`) { |
| + t.Fatalf("instances list = %d %s", code, out) |
| + } |
| +} |
| + |
| +// P1 #1: a console deletion invalidates the ownership the pages hold. With |
| +// the record view armed and its snapshot still holding the record, the |
| +// deleted instance's row is gone from the next page view. |
| +func TestRemoteDeletionInvalidatesHeldOwnership(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + v := provision.NewRecordView(tb.fx.rel, release.NewChangeWatch(tb.fx.rel)) |
| + if err := v.Rebuild(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.fx.srv.SetRecordView(v) |
| + if run := tb.page(t, "/apps/shop/instances"); !strings.Contains(run, remoteHost) { |
| + t.Fatalf("fixture: the remote row is missing:\n%s", run) |
| + } |
| + if status, _, out := rawReq(t, http.MethodDelete, instancesURL(tb.fx, tb.sqid, "shop")+"/"+remoteHost, tb.token, ""); status != http.StatusOK { |
| + t.Fatalf("delete = %d %s", status, out) |
| + } |
| + // The snapshot is not refreshed: it still holds the record. |
| + if run := tb.page(t, "/apps/shop/instances"); strings.Contains(run, remoteHost) { |
| + t.Fatalf("a deleted record still vouches for its host through the held snapshot:\n%s", run) |
| + } |
| +} |
| + |
| +// createOnListMod creates a follower record the first time ListMod runs: |
| +// a record that appears between the follower read and the modification-time |
| +// listing. |
| +type createOnListMod struct { |
| + *deletableStore |
| + once *sync.Once |
| + create func() |
| +} |
| + |
| +func (s createOnListMod) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + s.once.Do(s.create) |
| + return s.deletableStore.ListMod(ctx, prefix) |
| +} |
| + |
| +func followerRecord(t *testing.T, tb *twoBoxes, host string) func() { |
| + return func() { |
| + if err := provision.CreateRecord(context.Background(), tb.fx.rel, provision.Record{Schema: 1, Host: host, |
| + Slug: strings.SplitN(host, ".", 2)[0], App: "shop", Account: tb.sqid, Pool: "shop", Region: "uk", |
| + Channel: "canary/rc", CreatedAt: time.Now()}); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| +} |
| + |
| +// P2 #2: a follower created between the record read and the |
| +// modification-time listing is seen by the second listing, and refuses. |
| +func TestRetireRefusesRecordCreatedBetweenListings(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + tb.fx.srv.boxReports.expire() |
| + ds := tb.fx.rel.(*deletableStore) |
| + tb.fx.srv.cfg.Releases = createOnListMod{ds, &sync.Once{}, followerRecord(t, tb, "late.shop.example.com")} |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); !errorsIsUnsettled(err) { |
| + t.Fatalf("a follower created between the listings = %v, want unsettled", err) |
| + } |
| +} |
| + |
| +// P2 #2: a follower created after the check passed, before the pointer is |
| +// deleted, refuses the retire, and the pointer survives. |
| +func TestRetireRefusesRecordCreatedBeforeDelete(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + tb.fx.srv.boxReports.expire() |
| + tb.fx.srv.retireBeforeDeleteHook = followerRecord(t, tb, "late.shop.example.com") |
| + if page := retireRC(t, tb); !strings.Contains(page, notSettled) || !rcPointer(t, tb) { |
| + t.Fatalf("retire with a follower created before the delete:\n%s", page) |
| + } |
| + // With nothing happening in between, the same retire goes through. |
| + tb.fx.srv.retireBeforeDeleteHook = nil |
| + if err := tb.fx.rel.Delete(context.Background(), provision.RecordKey(tb.sqid, "shop", "late.shop.example.com")); err != nil { |
| + t.Fatal(err) |
| + } |
| + ageRecords(t, tb) |
| + if page := retireRC(t, tb); !strings.Contains(page, "Retired canary rc") { |
| + t.Fatalf("retire with no change during the check:\n%s", page) |
| + } |
| +} |
| + |
| +// A box report generated before this account's record existed is about an |
| +// earlier owner of the hostname, whoever it names: nothing of it joins. |
| +func TestRemoteReportOlderThanRecordIgnored(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v8") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now().Add(-2*time.Minute), nil, 9216) |
| + row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost) |
| + if strings.Contains(row, "v8") { |
| + t.Fatalf("a report older than the record was joined: %s", row) |
| + } |
| + if ov := tb.page(t, "/apps/shop"); strings.Contains(ov, "9.0 KB") { |
| + t.Fatalf("overview joined a report older than the record:\n%s", ov) |
| + } |
| +} |
| + |
| +// P1 #1, `carlos instances list`: the only sample is a successor's, newer |
| +// than the report that vouched for this account; it does not make the |
| +// record Running. |
| +func TestRemoteInstancesListIgnoresSuccessorSample(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + time.Sleep(1100 * time.Millisecond) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + time.Sleep(1100 * time.Millisecond) |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK || strings.Contains(out, `"health":"Running"`) { |
| + t.Fatalf("instances list = %d %s: a successor's sample made it Running", code, out) |
| + } |
| +} |
| + |
| +// The retire inventory includes the box reports' hosts of the app: a box |
| +// whose rollout report names this app for a host no record names holds the |
| +// retire. |
| +func TestRetireRefusesUnrecordedHostOfApp(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + if err := tb.regB.Upsert(registry.Route{Host: "hand.shop.example.com", Kind: "instance", App: "shop", Account: tb.sqid, |
| + Channel: "canary/rc", Version: "v4", Provisioned: true, Hibernate: true, Status: "ready", |
| + Socket: "/run/carlos/hand.sock"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + rt, _ := tb.regB.Get("hand.shop.example.com") |
| + if !rollout.Managed(*rt) { |
| + t.Fatalf("fixture: the hand route is not rollout-managed: %+v", rt) |
| + } |
| + tb.fx.srv.boxReports.expire() |
| + if _, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); !errorsIsUnsettled(err) { |
| + t.Fatalf("a box naming this app for a host no record names = %v, want unsettled", err) |
| + } |
| +} |
| + |
| +// Codex census review of 55706243: an invalidation during a load is not |
| +// overwritten by that load's (older) result. |
| +func TestBoxReportInvalidationDuringLoad(t *testing.T) { |
| + release1 := make(chan struct{}) |
| + started := make(chan struct{}, 1) |
| + rs := &reportStore{Store: release.NewDirStore(t.TempDir())} |
| + first := true |
| + rs.onList = func() error { |
| + if first { |
| + first = false |
| + started <- struct{}{} |
| + <-release1 |
| + } |
| + return nil |
| + } |
| + s, _ := cacheServer(t, rs) |
| + done := make(chan struct{}) |
| + go func() { s.pageBoxReports(context.Background()); close(done) }() |
| + <-started |
| + s.boxReports.invalidate() |
| + close(release1) |
| + <-done |
| + s.pageBoxReports(context.Background()) |
| + if n := rs.listCount(); n != 2 { |
| + t.Fatalf("box report listings = %d, want 2: the load that began before the invalidation was held", n) |
| + } |
| +} |
| + |
| +// Codex census review of cadd9fe9: a promotion of the canary between the |
| +// check's pointer read and the delete makes the delete conflict; the retire |
| +// is refused and the newer pointer stands. |
| +func TestRetireRefusesPointerChangedDuringCheck(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + tb.fx.srv.boxReports.expire() |
| + tb.fx.srv.retireBeforeDeleteHook = func() { shipAndPromote(t, tb.fx, tb.sqid, "shop", "v5", "canary/rc") } |
| + if page := retireRC(t, tb); !strings.Contains(page, notSettled) { |
| + t.Fatalf("retire with the pointer promoted during the check:\n%s", page) |
| + } |
| + p, err := release.Channel(context.Background(), tb.fx.rel, tb.fx.pub, tb.sqid, "shop", "canary/rc") |
| + if err != nil || p == nil || p.Version != "v5" { |
| + t.Fatalf("the newer pointer did not stand: %+v %v", p, err) |
| + } |
| +} |
| + |
| +// Codex census review of 56e72aa5: the canary's pointer removed by someone |
| +// else during the check is not "restored" from this request's older bytes. |
| +func TestRetireDoesNotResurrectRemovedPointer(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "stable") |
| + tb.reconcile(t, "v3") |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + ageRecords(t, tb) |
| + tb.fx.srv.boxReports.expire() |
| + tb.fx.srv.retireBeforeDeleteHook = func() { |
| + if err := tb.fx.rel.Delete(context.Background(), release.ChannelKey(tb.sqid, "shop", "canary/rc")); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + if page := retireRC(t, tb); !strings.Contains(page, notSettled) { |
| + t.Fatalf("retire with the pointer removed during the check:\n%s", page) |
| + } |
| + if rcPointer(t, tb) { |
| + t.Fatal("a pointer removed by someone else was resurrected") |
| + } |
| +} |
diff --git a/internal/console/remoteinstances_round5_test.go b/internal/console/remoteinstances_round5_test.go| new file mode 100644 |
| index 000000000..974f061ce |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_round5_test.go |
| @@ -0,0 +1,118 @@ |
| +package console |
| + |
| +// Round 5 (Astra, 59c2cd61; by the coordinator's ruling, shrink): one |
| +// accessor for remote facts, identity from the record plus a report naming |
| +// the same tenant generated after the record, and nothing else. |
| + |
| +import ( |
| + "context" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// TestRemoteFactsOneAccessor holds the package to the one-accessor rule: |
| +// box reports are folded only by remoteFacts, their per-host map is read |
| +// only by the accessor's own methods, and the cached read is taken only by |
| +// remoteFacts and by the Overview's local-row database join (which reads |
| +// sizes for the console box's own rows, never a remote host's). A page that |
| +// joins reports for a remote host itself fails here. |
| +func TestRemoteFactsOneAccessor(t *testing.T) { |
| + allowed := map[string]map[string]bool{ |
| + "foldFleetReports": {"remoteFacts": true}, |
| + "pageBoxReports": {"remoteFacts": true, "handleApp": true}, |
| + "byHost": {"foldFleetReports": true, "host": true, "seen": true, "unrecorded": true}, |
| + } |
| + files, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fset := token.NewFileSet() |
| + for _, name := range files { |
| + if strings.HasSuffix(name, "_test.go") { |
| + continue |
| + } |
| + src, err := os.ReadFile(name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f, err := parser.ParseFile(fset, name, src, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, decl := range f.Decls { |
| + fn, ok := decl.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + var ident string |
| + switch x := n.(type) { |
| + case *ast.SelectorExpr: |
| + ident = x.Sel.Name |
| + case *ast.CallExpr: |
| + if id, ok := x.Fun.(*ast.Ident); ok { |
| + ident = id.Name |
| + } |
| + } |
| + if callers, watched := allowed[ident]; watched && !callers[fn.Name.Name] { |
| + t.Errorf("%s: %s uses %s; remote facts go through remoteFacts only", fset.Position(n.Pos()), fn.Name.Name, ident) |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// P1 #2: the instance page of a remote host whose only report is a box |
| +// that could not arm its rollout (Unavailable, no per-host entry) and that |
| +// still carries another tenant's installation shows none of it: not its |
| +// installed version, not a rollout section. |
| +func TestRemoteInstancePageTakesNothingFromUnidentifiedReport(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + routes, err := tb.regB.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i := range routes { |
| + if routes[i].Host == remoteHost { |
| + routes[i].Version = "v9-other" |
| + } |
| + } |
| + b := status.CollectBox(routes, status.Probes{MachineID: "box-b", Region: "uk", |
| + Rollout: &status.RolloutReport{Unavailable: "no-swap"}}, time.Now()) |
| + if err := status.WriteBox(context.Background(), tb.fx.rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + inst := tb.page(t, "/apps/shop/instances/"+remoteHost) |
| + if strings.Contains(inst, "v9-other") { |
| + t.Fatalf("the instance page shows another installation's version from an unidentified report:\n%s", inst) |
| + } |
| + if !strings.Contains(inst, "Can't tell right now") { |
| + t.Fatalf("the instance page does not say its state is unknown:\n%s", inst) |
| + } |
| +} |
| + |
| +// The accessor's facts are for one account and app: a record of any other, |
| +// handed to it, joins nothing, even a report naming the facts' own tenant. |
| +func TestRemoteFactsAreScopedToTheirApp(t *testing.T) { |
| + now := time.Now() |
| + boxes := []status.Box{{GeneratedAt: now, Label: "b", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v2"}, |
| + Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{"h.example.com": {Account: "a", App: "shop"}}}, |
| + }}} |
| + facts := factsOf(foldFleetReports(boxes, true, now), "a", "shop") |
| + if rep := facts.host(provision.Record{Host: "h.example.com", Account: "b", App: "shop"}); rep != nil { |
| + t.Fatalf("facts for a/shop joined a record of b/shop: %+v", rep) |
| + } |
| +} |
diff --git a/internal/console/remoteinstances_round6_test.go b/internal/console/remoteinstances_round6_test.go| new file mode 100644 |
| index 000000000..ec0a917ee |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_round6_test.go |
| @@ -0,0 +1,112 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// Astra round 6, P1 #1: remote rows take no metrics. Every box that could |
| +// hold a sample of the remote host's unit has a fresh one (its own box, the |
| +// console's box, a third box), and its own box's rollout says it is asleep. |
| +// No remote row on any page, nor `carlos instances list`, may carry a |
| +// reading, a graph or a Running word drawn from a sample. The local row on |
| +// the console's box keeps its readings. |
| +func TestRemoteRowsNeverCarrySamples(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, true) |
| + unit := "carlos-exec@" + remoteHost |
| + for _, box := range []string{status.Label("box-b"), "box-console", status.Label("box-c")} { |
| + sweep(t, tb.fx.rel, box, map[string]metrics.UnitSample{ |
| + unit: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + "carlos-exec@" + localHost: {CPUFrac: p(0.12), MemBytes: pi64(5 << 20)}, |
| + }) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) // asleep |
| + tb.fx.srv.boxReports.expire() |
| + tb.fx.srv.metricsCache = metricsCache{} |
| + |
| + views, err := tb.fx.srv.assembleApps(context.Background(), tb.sqid, []string{"shop"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + remote := map[string]bool{} |
| + for _, rt := range views[0].Routes { |
| + if rt.remote { |
| + remote[rt.Host] = true |
| + } |
| + } |
| + if !remote[remoteHost] || remote[localHost] { |
| + t.Fatalf("fixture: remote rows = %v", remote) |
| + } |
| + local := false |
| + for _, m := range tb.fx.srv.appResourceMetrics(context.Background(), &views[0], tb.account(t)) { |
| + if remote[m.Host] { |
| + t.Fatalf("a remote row carries a metrics row: %+v", m) |
| + } |
| + if m.Host == localHost && m.Reporting() && m.CPUFrac != nil { |
| + local = true |
| + } |
| + } |
| + if !local { |
| + t.Fatal("the local row lost its readings") |
| + } |
| + |
| + for _, path := range []string{"/apps/shop", "/apps/shop/instances", "/apps/shop/instances/" + remoteHost} { |
| + body := tb.page(t, path) |
| + for _, bad := range []string{"66%", "7.0 MB", "27%", "3.0 MB"} { |
| + if strings.Contains(body, bad) { |
| + t.Fatalf("%s shows a remote reading %q:\n%s", path, bad, body) |
| + } |
| + } |
| + } |
| + if row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost); strings.Contains(row, "Running") || strings.Contains(row, "<polyline") { |
| + t.Fatalf("a sample made the remote row Running or drew its graph: %s", row) |
| + } |
| + if ov := tb.page(t, "/apps/shop"); !strings.Contains(ov, "12%") { |
| + t.Fatalf("overview lost the local row's reading:\n%s", ov) |
| + } |
| + // Two records, and only the local one is Running from its sample. |
| + if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK || |
| + strings.Count(out, `"health":"Running"`) != 1 { |
| + t.Fatalf("instances list = %d %s", code, out) |
| + } |
| +} |
| + |
| +// Astra round 6, P2 #3: a page view's record read, slot reads included, is |
| +// held for the minute and no longer. Here the host's lifetime ends without |
| +// its record changing: within the minute the row is still the held read's, |
| +// and after it the next page view judges afresh and drops the row. |
| +func TestHeldRecordReadExpiresAfterTheMinute(t *testing.T) { |
| + ltClock := useLifetimesClock(t) |
| + tb := newTwoBoxes(t) |
| + turnLifetimesOn(t, tb.fx.srv, ltClock) |
| + tb.setUp(t, false) |
| + clock := time.Now() |
| + tb.fx.srv.boxReports.now = func() time.Time { return clock } |
| + if run := tb.page(t, "/apps/shop/instances"); !strings.Contains(run, remoteHost) { |
| + t.Fatalf("fixture: the remote row is missing:\n%s", run) |
| + } |
| + ctx := context.Background() |
| + slot, slotETag, err := provision.ReadHostIncarnation(ctx, tb.fx.rel, remoteHost) |
| + if err != nil || slot == nil { |
| + t.Fatalf("fixture: slot %+v %v", slot, err) |
| + } |
| + slot.State = provision.SlotRetired |
| + if _, err := provision.WriteHostIncarnation(ctx, tb.fx.rel, remoteHost, *slot, slotETag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if run := tb.page(t, "/apps/shop/instances"); !strings.Contains(run, remoteHost) { |
| + t.Fatalf("within the minute the page read records again:\n%s", run) |
| + } |
| + clock = clock.Add(boxReportTTL + time.Second) |
| + if run := tb.page(t, "/apps/shop/instances"); strings.Contains(run, remoteHost) { |
| + t.Fatalf("after the minute a retired lifetime still shows:\n%s", run) |
| + } |
| +} |
diff --git a/internal/console/remoteinstances_test.go b/internal/console/remoteinstances_test.go| new file mode 100644 |
| index 000000000..202a75339 |
| --- /dev/null |
| +++ b/internal/console/remoteinstances_test.go |
| @@ -0,0 +1,778 @@ |
| +package console |
| + |
| +// Instances on other boxes, end to end (remoteinstances.go). Two boxes and |
| +// one bucket: box A is the console's own box (the fixture's registry), box B |
| +// is a second region with its own registry. Instances are created through |
| +// the console's real create door, minted by each box's real reconcile pass, |
| +// and reported by each box's real status snapshot (status.CollectBox over |
| +// the box's own registry, written with status.WriteBox) and a metrics chunk |
| +// in the shape the box's sweep writes. The pages are driven through the real |
| +// HTTP server with a real session. |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rollout" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// expire ages the page views' shared box-report read out, as a minute |
| +// passing would. |
| +func (c *boxReportCache) expire() { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.valid = false |
| +} |
| + |
| +// twoBoxes is the fixture: the console on box A ("ie"), a second box B |
| +// ("uk"), and an account "Shop" (paul owns it) with an app "shop". |
| +type twoBoxes struct { |
| + fx *consoleFixture |
| + sqid string |
| + token string // paul's CLI token |
| + regB *registry.Registry |
| + dataB string |
| + dataA string |
| + browser *http.Client |
| +} |
| + |
| +const ( |
| + remoteHost = "eu.shop.example.com" |
| + localHost = "ie.shop.example.com" |
| +) |
| + |
| +func shopManifest(app, domain string) provision.Manifest { |
| + return provision.Manifest{Schema: 1, App: app, Domain: domain, |
| + Pool: "shop", Channel: "stable", Regions: []string{"ie", "uk"}} |
| +} |
| + |
| +func newTwoBoxes(t *testing.T) *twoBoxes { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + const acctID int64 = 5151 |
| + sqid := accountSqid(acctID) |
| + if err := fx.st.CreateAccount(acctID, sqid, "Shop", "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(acctID, "shop", "paul@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := WriteAccountManifest(ctx, fx.rel, acctID, sqid, "Shop", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(ctx, fx.rel, sqid, "shop", shopManifest("shop", "shop.example.com")); err != nil { |
| + t.Fatal(err) |
| + } |
| + shipAndPromote(t, fx, sqid, "shop", "v3", "stable") |
| + regB, err := registry.Open(filepath.Join(t.TempDir(), "registry-b.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { regB.Close() }) |
| + tb := &twoBoxes{fx: fx, sqid: sqid, regB: regB, dataA: t.TempDir(), dataB: t.TempDir()} |
| + tb.token = cliToken(t, fx, "paul@keymail.dev", "code-remote-cli") |
| + tb.browser = signInPaul(t, fx) |
| + return tb |
| +} |
| + |
| +func shipAndPromote(t *testing.T, fx *consoleFixture, sqid, app, version, channel string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + m := release.Manifest{Schema: 1, App: app, Version: version, Kind: "binary", BuiltAt: "2026-10-01T10:00:00Z", |
| + Artifacts: map[string]release.Artifact{"linux-amd64": {File: app}}} |
| + if err := release.Ship(ctx, fx.rel, sqid, m, map[string][]byte{"linux-amd64": []byte("binary " + version)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.Promote(ctx, fx.rel, fx.priv, sqid, app, channel, version); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// create runs the console's create door for host in region. |
| +func (tb *twoBoxes) create(t *testing.T, token, sqid, app, host, region, channel string) { |
| + t.Helper() |
| + body := `{"host":"` + host + `","region":"` + region + `"` |
| + if channel != "" { |
| + body += `,"channel":"` + channel + `"` |
| + } |
| + body += `}` |
| + if status, _, out := rawReq(t, http.MethodPost, instancesURL(tb.fx, sqid, app), token, body); status != http.StatusCreated { |
| + t.Fatalf("create %s in %s = %d %s", host, region, status, out) |
| + } |
| +} |
| + |
| +// reconcile runs both boxes' real reconcile passes and stamps every |
| +// provisioned route's version the way the adopt pass does. |
| +func (tb *twoBoxes) reconcile(t *testing.T, version string) { |
| + t.Helper() |
| + ctx := context.Background() |
| + regA, err := registry.Open(tb.fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, box := range []struct { |
| + reg *registry.Registry |
| + region string |
| + data string |
| + }{{regA, "ie", tb.dataA}, {tb.regB, "uk", tb.dataB}} { |
| + cfg := provision.ReconcileConfig{Region: box.region, Pools: []string{"shop"}, DataDir: box.data} |
| + if err := provision.Reconcile(ctx, tb.fx.rel, box.reg, cfg); err != nil { |
| + t.Fatalf("reconcile %s: %v", box.region, err) |
| + } |
| + routes, err := box.reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, rt := range routes { |
| + if rt.Provisioned && rt.Version == "" { |
| + if err := box.reg.SetVersions(rt.Host, version, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + } |
| +} |
| + |
| +// report writes box's status snapshot from its own registry, what the |
| +// agent's status tick does (CollectBox over the registry and its aliases). |
| +// The rollout report names the tenant of exactly the routes production's |
| +// rollout manages (rollout.Managed: never a static, a non-hibernating or a |
| +// unit-backed route). Each route gets a database size. |
| +func report(t *testing.T, rel release.Store, reg *registry.Registry, machine, region string, at time.Time, awake map[string]bool, dbBytes int64) string { |
| + t.Helper() |
| + routes, err := reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + aliases, err := reg.ListAliases() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ro := &status.RolloutReport{Hosts: map[string]status.HostRollout{}} |
| + for _, rt := range routes { |
| + if rollout.Managed(rt) { |
| + ro.Hosts[rt.Host] = status.HostRollout{Account: rt.Account, App: rt.App, Installed: rt.Version, Awake: awake[rt.Host]} |
| + } |
| + } |
| + b := status.CollectBox(routes, status.Probes{MachineID: machine, Region: region, Aliases: aliases, Rollout: ro, |
| + DBBytes: func(string) *int64 { n := dbBytes; return &n }}, at) |
| + if err := status.WriteBox(context.Background(), rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.Label |
| +} |
| + |
| +// sweep writes box's metrics chunk: one exec-child unit per host given, |
| +// sampled now (after the instances it reads were created: earlier samples |
| +// of a hostname are not its current owner's, ownerAppMetricsFrom). |
| +func sweep(t *testing.T, rel release.Store, box string, units map[string]metrics.UnitSample) { |
| + t.Helper() |
| + at := time.Now().UTC() |
| + if err := metrics.WriteRaw(context.Background(), rel, metrics.RawChunk{ |
| + V: 1, Box: box, Hour: metrics.HourOf(at), |
| + Samples: []metrics.Sample{{At: at, Units: units}}, |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (tb *twoBoxes) page(t *testing.T, path string) string { |
| + t.Helper() |
| + status, loc, body := get(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+path) |
| + if status != http.StatusOK { |
| + t.Fatalf("GET %s = %d -> %q\n%s", path, status, loc, body) |
| + } |
| + return body |
| +} |
| + |
| +// setUp creates the remote instance (and, with local, one on the console's |
| +// box too), mints, reports and sweeps. |
| +func (tb *twoBoxes) setUp(t *testing.T, local bool) { |
| + t.Helper() |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + if local { |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "") |
| + } |
| + tb.reconcile(t, "v3") |
| + // B's domains pass has checked the host and its certificate, and B |
| + // routes one custom domain to it: the readings its report carries. |
| + certAt := time.Date(2027, 1, 15, 0, 0, 0, 0, time.UTC).Unix() |
| + if err := tb.regB.SetDNSStatus(remoteHost, "pointing", time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.regB.SetCertExpiresAt(remoteHost, certAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.regB.UpsertAlias(registry.RouteAlias{Alias: "www.shop-store.example", Host: remoteHost, |
| + Account: tb.sqid, App: "shop", DNSStatus: "pointing", CertExpiresAt: certAt}); err != nil { |
| + t.Fatal(err) |
| + } |
| + regA, err := registry.Open(tb.fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // B samples the host's unit, and its rollout says the process is |
| + // awake. A remote row takes no readings: the sample is there only so |
| + // the pages can be shown never to carry it. |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.27), MemBytes: pi64(3 << 20)}, |
| + }) |
| + report(t, tb.fx.rel, regA, "box-a", "ie", time.Now(), nil, 1024) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), map[string]bool{remoteHost: true}, 4096) |
| +} |
| + |
| +// TestRemoteInstanceMintsOnlyOnItsBox pins the fixture itself: the record |
| +// becomes a route on B and not on the console's box, which is the state |
| +// every page test below relies on. |
| +func TestRemoteInstanceMintsOnlyOnItsBox(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + regA, _ := registry.Open(tb.fx.regPath) |
| + if rt, err := regA.Get(remoteHost); err != nil || rt != nil { |
| + t.Fatalf("the console's box minted the uk instance: %+v %v", rt, err) |
| + } |
| + if rt, err := tb.regB.Get(remoteHost); err != nil || rt == nil || rt.Version != "v3" { |
| + t.Fatalf("box B did not mint the uk instance: %+v %v", rt, err) |
| + } |
| +} |
| + |
| +func TestRemoteInstancePages(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + |
| + // Account home: deployed, with the instance's address. |
| + home := tb.page(t, "/") |
| + if !strings.Contains(home, remoteHost) || !strings.Contains(home, "Deployed") || strings.Contains(home, "Not deployed yet") { |
| + t.Fatalf("account home does not show the remote instance as deployed:\n%s", home) |
| + } |
| + |
| + // Overview: one instance, B's version and database size, not the empty |
| + // state, and none of B's CPU or memory readings. |
| + ov := tb.page(t, "/apps/shop") |
| + for _, bad := range []string{"No instances yet", "Not deployed yet", "nothing running yet"} { |
| + if strings.Contains(ov, bad) { |
| + t.Fatalf("overview still says %q:\n%s", bad, ov) |
| + } |
| + } |
| + for _, want := range []string{"4.0 KB", "DNS & certs OK"} { |
| + if !strings.Contains(ov, want) { |
| + t.Fatalf("overview is missing %q:\n%s", want, ov) |
| + } |
| + } |
| + for _, bad := range []string{"27%", "3.0 MB"} { |
| + if strings.Contains(ov, bad) { |
| + t.Fatalf("overview shows a remote reading %q:\n%s", bad, ov) |
| + } |
| + } |
| + |
| + // Running: the row, Running from B's rollout report, no restart button. |
| + run := tb.page(t, "/apps/shop/instances") |
| + row := instanceRow(t, run, remoteHost) |
| + if !strings.Contains(row, "Running") || !strings.Contains(row, "v3") { |
| + t.Fatalf("Running row for the remote instance = %s", row) |
| + } |
| + if strings.Contains(run, "Nothing running yet") { |
| + t.Fatalf("Running tab shows the empty state:\n%s", run) |
| + } |
| + |
| + // The instance page renders instead of a 404. |
| + inst := tb.page(t, "/apps/shop/instances/"+remoteHost) |
| + if !strings.Contains(inst, remoteHost) || !strings.Contains(inst, "www.shop-store.example") { |
| + t.Fatalf("instance page does not name its host and B's alias for it:\n%s", inst) |
| + } |
| + |
| + // Settings, Domains: the host's row with B's certificate date. |
| + set := tb.page(t, "/apps/shop/settings/domains") |
| + if !strings.Contains(set, remoteHost) || !strings.Contains(set, "renews 2027-01-15") { |
| + t.Fatalf("settings domains does not list the remote host with B's cert date:\n%s", set) |
| + } |
| + |
| + // Deployments counts it on stable at v3. |
| + dep := tb.page(t, "/apps/shop/deployments") |
| + if !strings.Contains(dep, "1 × <a href=\"/a/"+tb.sqid+"/apps/shop/releases#version-v3\"><code>v3</code>") || |
| + !strings.Contains(dep, "<td>1 <a href=\"/a/"+tb.sqid+"/apps/shop/instances?channel=stable\">") { |
| + t.Fatalf("deployments does not count the remote instance:\n%s", dep) |
| + } |
| + |
| + // Fleet tab: one app on the shared fleet. |
| + card, _, _, warn := tb.fx.srv.assembleAccountFleet(context.Background(), tb.account(t)) |
| + if card.PlatformApps != 1 || !card.PlacementKnown || warn != "" { |
| + t.Fatalf("fleet card = %+v warn %q, want 1 app on the shared fleet", card, warn) |
| + } |
| + |
| + // `carlos instances list`: the record's health comes from B, not |
| + // "Setting up". |
| + status, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, "") |
| + if status != http.StatusOK || !strings.Contains(out, `"health":"Running"`) { |
| + t.Fatalf("instances list = %d %s", status, out) |
| + } |
| +} |
| + |
| +func (tb *twoBoxes) account(t *testing.T) *Account { |
| + t.Helper() |
| + acct, err := tb.fx.st.AccountBySqid(tb.sqid) |
| + if err != nil || acct == nil { |
| + t.Fatalf("account %s: %v", tb.sqid, err) |
| + } |
| + return acct |
| +} |
| + |
| +// TestRemoteInstanceLocalRowWins: a host with a row on the console's box is |
| +// shown once, from that row, even when another box reports it too (a move |
| +// in flight). |
| +func TestRemoteInstanceLocalRowWins(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, true) |
| + // B also reports the local host, at another version: the move-in-flight |
| + // shape. The local row's version must win, once. |
| + if err := tb.regB.Upsert(registry.Route{Host: localHost, Kind: "instance", App: "shop", Account: tb.sqid, |
| + Channel: "stable", Version: "v9", Provisioned: true, Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + views, err := tb.fx.srv.assembleApps(context.Background(), tb.sqid, []string{"shop"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var hosts []string |
| + for _, rt := range views[0].Routes { |
| + hosts = append(hosts, rt.Host+"@"+rt.Version) |
| + if rt.Host == localHost && rt.remote { |
| + t.Fatalf("the local host was shown from another box's report: %+v", rt) |
| + } |
| + } |
| + if got := strings.Join(hosts, ","); got != remoteHost+"@v3,"+localHost+"@v3" { |
| + t.Fatalf("rows = %s", got) |
| + } |
| + if len(views[0].Domains) != len(views[0].Routes) { |
| + t.Fatalf("Routes and Domains are no longer parallel: %d vs %d", len(views[0].Routes), len(views[0].Domains)) |
| + } |
| +} |
| + |
| +// TestRemoteInstanceCrossAccount is the tenant boundary: another account |
| +// has an app with the same name, with an instance on the same remote box, |
| +// in the same box report and the same metrics chunk. Nothing of it may |
| +// reach this account's pages: not the host, not its CPU, memory or database |
| +// size, not a count. |
| +func TestRemoteInstanceCrossAccount(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + const rivalID int64 = 6262 |
| + rival := accountSqid(rivalID) |
| + if err := tb.fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := tb.fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := WriteAccountManifest(ctx, tb.fx.rel, rivalID, rival, "Rival", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(ctx, tb.fx.rel, rival, "shop", shopManifest("shop", "rival.example.net")); err != nil { |
| + t.Fatal(err) |
| + } |
| + bob := cliToken(t, tb.fx, "bob@keymail.dev", "code-remote-bob") |
| + tb.fx.setUser("paul@keymail.dev") |
| + const rivalHost = "uk.rival.example.net" |
| + tb.create(t, bob, rival, "shop", rivalHost, "uk", "") |
| + tb.setUp(t, false) |
| + // The sweep carries both units; B's report, after it, both tenants. |
| + sweep(t, tb.fx.rel, status.Label("box-b"), map[string]metrics.UnitSample{ |
| + "carlos-exec@" + remoteHost: {CPUFrac: p(0.27), MemBytes: pi64(3 << 20)}, |
| + "carlos-exec@" + rivalHost: {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 9216) |
| + if rt, _ := tb.regB.Get(rivalHost); rt == nil { |
| + t.Fatal("fixture: box B did not mint the rival's instance") |
| + } |
| + for _, path := range []string{"/", "/apps/shop", "/apps/shop/instances", "/apps/shop/deployments", |
| + "/apps/shop/settings", "/apps/shop/releases", "/apps/shop/logs"} { |
| + body := tb.page(t, path) |
| + for _, bad := range []string{rivalHost, "66%", "7.0 MB", "rival.example.net"} { |
| + if strings.Contains(body, bad) { |
| + t.Fatalf("%s leaked another account's %q:\n%s", path, bad, body) |
| + } |
| + } |
| + } |
| + // The overview counts one instance and B's size for this account's |
| + // host only (9216 bytes each: one host is 9.0 KB, two would be 18 KB). |
| + ov := tb.page(t, "/apps/shop") |
| + if !strings.Contains(ov, "9.0 KB") || strings.Contains(ov, "18 KB") { |
| + t.Fatalf("overview database size is not this account's alone:\n%s", ov) |
| + } |
| + if status, _, _ := get(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+"/apps/shop/instances/"+rivalHost); status != http.StatusNotFound { |
| + t.Fatalf("instance page for another account's host = %d, want 404", status) |
| + } |
| + // And the other way round: bob's pages show his host, not paul's. |
| + c, _ := signInAs(t, tb.fx, "bob@keymail.dev", "code-remote-bob-web") |
| + _, _, body := get(t, c, tb.fx.ts.URL+"/a/"+rival+"/apps/shop/instances") |
| + if !strings.Contains(body, rivalHost) || strings.Contains(body, remoteHost) || strings.Contains(body, "27%") { |
| + t.Fatalf("rival's Running tab:\n%s", body) |
| + } |
| +} |
| + |
| +// TestRemoteReportNamingAnotherTenant is R18: a fresh box report whose |
| +// rollout names another tenant for this account's host is not joined, even |
| +// though the record is this account's. |
| +func TestRemoteReportNamingAnotherTenant(t *testing.T) { |
| + now := time.Now() |
| + boxes := []status.Box{{GeneratedAt: now, Label: "b", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v7"}, |
| + RouteDBBytes: map[string]int64{"h.example.com": 77}, |
| + Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{ |
| + "h.example.com": {Account: "other", App: "shop", Awake: true}, |
| + }}, |
| + }}} |
| + f := foldFleetReports(boxes, true, now) |
| + if rep := pickFor(f, "h.example.com", "mine", "shop"); rep != nil { |
| + t.Fatalf("joined a report naming another account: %+v", rep) |
| + } |
| + if rep := pickFor(f, "h.example.com", "other", "web"); rep != nil { |
| + t.Fatalf("joined a report naming another app: %+v", rep) |
| + } |
| + if rep := pickFor(f, "h.example.com", "other", "shop"); rep == nil || rep.version != "v7" || !rep.awake { |
| + t.Fatalf("the named tenant's own report = %+v", rep) |
| + } |
| + rv, dv := remoteRoute(provision.Record{Host: "h.example.com", App: "shop", Account: "mine"}, pickFor(f, "h.example.com", "mine", "shop"), factsOf(f, "mine", "shop"), "mine", DNSTargets{}) |
| + // The host is served (by someone else), so it is not "not minted |
| + // anywhere" either: unknown, with nothing joined. |
| + if rv.Version != "" || rv.dbBytes != nil || rv.boxAwake || rv.Status != "" || !rv.unknown || dv.TLS != "" || dv.Guidance != "" { |
| + t.Fatalf("row from a refused report = %+v %+v", rv, dv) |
| + } |
| +} |
| + |
| +// TestRemoteReportStaleAndMoving: a stale box is not joined (the version is |
| +// unknown, so the page says it can't tell); with two fresh boxes reporting |
| +// one host, the report naming the tenant wins, then the freshest. |
| +func TestRemoteReportStaleAndMoving(t *testing.T) { |
| + now := time.Now() |
| + stale := status.Box{GeneratedAt: now.Add(-time.Hour), Label: "old", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v1"}}} |
| + f := foldFleetReports([]status.Box{stale}, true, now) |
| + rv, _ := remoteRoute(provision.Record{Host: "h.example.com", App: "shop", Account: "a"}, pickFor(f, "h.example.com", "a", "shop"), factsOf(f, "a", "shop"), "a", DNSTargets{}) |
| + if rv.Version != "" || rv.Status != "pending" { |
| + t.Fatalf("a stale report was joined: %+v", rv) |
| + } |
| + // Incomplete read: not "Setting up", and the overview can't tell. |
| + f = foldFleetReports([]status.Box{stale}, false, now) |
| + rv, dv := remoteRoute(provision.Record{Host: "h.example.com", App: "shop", Account: "a"}, pickFor(f, "h.example.com", "a", "shop"), factsOf(f, "a", "shop"), "a", DNSTargets{}) |
| + if rv.Status != "" { |
| + t.Fatalf("an incomplete read vouched for absence: %+v", rv) |
| + } |
| + view := &AppView{Routes: []RouteView{rv}, Domains: []DomainView{dv}} |
| + if st := assembleOverview(view, "a", []InstanceMetrics{}, nil, boxJoin{}); st.VerdictLabel != "Can't tell right now" { |
| + t.Fatalf("verdict with no fresh report = %q", st.VerdictLabel) |
| + } |
| + |
| + older := status.Box{GeneratedAt: now.Add(-2 * time.Minute), Label: "a", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v1"}, |
| + Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{"h.example.com": {Account: "a", App: "shop"}}}}} |
| + newerNoTenant := status.Box{GeneratedAt: now, Label: "b", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v2"}}} |
| + newer := status.Box{GeneratedAt: now.Add(-time.Minute), Label: "c", Metrics: &status.BoxMetrics{ |
| + RouteVersions: map[string]string{"h.example.com": "v3"}, |
| + Rollout: &status.RolloutReport{Hosts: map[string]status.HostRollout{"h.example.com": {Account: "a", App: "shop"}}}}} |
| + f = foldFleetReports([]status.Box{older, newerNoTenant, newer}, true, now) |
| + if rep := pickFor(f, "h.example.com", "a", "shop"); rep == nil || rep.version != "v3" { |
| + t.Fatalf("move in flight picked %+v, want the freshest report naming the tenant (v3)", rep) |
| + } |
| +} |
| + |
| +// TestRemoteRecordsAccountFilter: the records reader's own scoping is not |
| +// trusted alone. A record that disagrees with the viewed account or app is |
| +// never a row (the mutation target for the account filter in addRemoteRows). |
| +func TestRemoteRecordsAccountFilter(t *testing.T) { |
| + remote := &remoteRows{records: func(string) ([]provision.Record, error) { |
| + return []provision.Record{ |
| + {Host: "mine.example.com", App: "shop", Account: "a"}, |
| + {Host: "theirs.example.com", App: "shop", Account: "b"}, |
| + {Host: "sibling.example.com", App: "web", Account: "a"}, |
| + }, nil |
| + }, facts: func(app string) appFacts { return factsOf(fleetReports{complete: true}, "a", app) }} |
| + routes, domains := addRemoteRows(remote, "a", "shop", map[string]bool{}, nil, nil, DNSTargets{}) |
| + if len(routes) != 1 || routes[0].Host != "mine.example.com" || len(domains) != 1 { |
| + t.Fatalf("rows = %+v", routes) |
| + } |
| +} |
| + |
| +// TestRetireCanaryRefusedForRemoteFollower is the canary-retire safety |
| +// check: the only follower of canary/rc is an instance on box B, which the |
| +// console's own registry does not have. Retiring must be refused and the |
| +// pointer must survive. Then a record that will not read fails it closed. |
| +func TestRetireCanaryRefusedForRemoteFollower(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.reconcile(t, "v4") |
| + if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Channel != "canary/rc" { |
| + t.Fatalf("fixture: box B's follower = %+v", rt) |
| + } |
| + regA, _ := registry.Open(tb.fx.regPath) |
| + if rt, _ := regA.Get(remoteHost); rt != nil { |
| + t.Fatalf("fixture: the console's box has the follower: %+v", rt) |
| + } |
| + csrf := sessionToken(t, tb.fx, tb.browser) |
| + retire := func() (int, string, string) { |
| + return postForm(t, tb.browser, tb.fx.ts.URL+"/a/"+tb.sqid+"/apps/shop/canary/retire", |
| + url.Values{"csrf": {csrf}, "name": {"rc"}, "confirmed": {"1"}}) |
| + } |
| + status, loc, body := retire() |
| + if status != http.StatusSeeOther { |
| + t.Fatalf("retire = %d -> %q %s", status, loc, body) |
| + } |
| + _, _, page := get(t, tb.browser, tb.fx.ts.URL+loc) |
| + if !strings.Contains(page, "still has a host ("+remoteHost+") following it") { |
| + t.Fatalf("retire was not refused for the remote follower:\n%s", page) |
| + } |
| + if _, _, err := tb.fx.rel.Get(context.Background(), release.ChannelKey(tb.sqid, "shop", "canary/rc")); err != nil { |
| + t.Fatalf("the canary pointer is gone: %v", err) |
| + } |
| + |
| + // A record that will not parse could be a follower: fail closed. |
| + if _, err := tb.fx.rel.Put(context.Background(), provision.RecordKey(tb.sqid, "shop", "broken.shop.example.com"), []byte("{not json"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.fx.rel.Delete(context.Background(), provision.RecordKey(tb.sqid, "shop", remoteHost)); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, _, body = retire() |
| + if status != http.StatusInternalServerError || !strings.Contains(body, "Could not verify") { |
| + t.Fatalf("retire with an unreadable record = %d %s", status, body) |
| + } |
| + if _, _, err := tb.fx.rel.Get(context.Background(), release.ChannelKey(tb.sqid, "shop", "canary/rc")); err != nil { |
| + t.Fatalf("the canary pointer is gone after an unreadable record: %v", err) |
| + } |
| +} |
| + |
| +// TestChannelHostsCountsRemoteFollowers pins channelHosts directly: local |
| +// routes, instance records and sidecar records all count, once each. |
| +func TestChannelHostsCountsRemoteFollowers(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "canary/rc") |
| + tb.create(t, tb.token, tb.sqid, "shop", localHost, "ie", "stable") |
| + tb.reconcile(t, "v3") |
| + hosts, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc") |
| + if err != nil || len(hosts) != 1 || hosts[0] != remoteHost { |
| + t.Fatalf("canary/rc followers = %v %v, want [%s]", hosts, err, remoteHost) |
| + } |
| + hosts, err = tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "stable") |
| + if err != nil || len(hosts) != 1 || hosts[0] != localHost { |
| + t.Fatalf("stable followers = %v %v, want [%s] once", hosts, err, localHost) |
| + } |
| + // A sidecar following a canary from another region counts too. |
| + if err := provision.PutSidecarManifest(context.Background(), tb.fx.rel, tb.sqid, "shop", provision.SidecarManifest{ |
| + Schema: 1, App: "shop", Pool: "shop", Channel: "stable", Regions: []string{"ie", "uk"}, Args: []string{"worker"}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, _, out := rawReq(t, http.MethodPost, tb.fx.ts.URL+"/api/cli/apps/"+tb.sqid+"/shop/sidecars", tb.token, |
| + `{"name":"bot","region":"uk","channel":"canary/side"}`); status != http.StatusCreated { |
| + t.Fatalf("sidecar create = %d %s", status, out) |
| + } |
| + hosts, err = tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/side") |
| + if err != nil || len(hosts) != 1 || hosts[0] != provision.SidecarHost("bot", "shop", tb.sqid) { |
| + t.Fatalf("canary/side followers = %v %v, want the sidecar", hosts, err) |
| + } |
| + // A failing listing, of either family, is an error, never "nobody". |
| + live := tb.fx.srv.cfg.Releases |
| + for _, family := range []string{"/instances/", "/sidecars/"} { |
| + tb.fx.srv.cfg.Releases = remoteFailingRecordStore{live, family} |
| + if hosts, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); err == nil { |
| + t.Fatalf("channelHosts with %s failing = %v, nil error", family, hosts) |
| + } |
| + } |
| + // A store that cannot list modification times cannot rule out a |
| + // recent move off the channel: refuse rather than guess. |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v9", "canary/zz") |
| + tb.fx.srv.cfg.Releases = struct{ release.Store }{live} |
| + if hosts, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/zz"); err == nil { |
| + t.Fatalf("channelHosts without modification times = %v, nil error", hosts) |
| + } |
| + // A listed sidecar record that will not read, even one deleted between |
| + // the listing and the read, could still be running: refuse. |
| + tb.fx.srv.cfg.Releases = vanishingStore{live, provision.SidecarRecordKey(tb.sqid, "shop", "bot")} |
| + if hosts, err := tb.fx.srv.channelHosts(context.Background(), tb.sqid, "shop", "canary/rc"); err == nil { |
| + t.Fatalf("channelHosts with a sidecar record vanishing mid-read = %v, nil error", hosts) |
| + } |
| + tb.fx.srv.cfg.Releases = live |
| +} |
| + |
| +// vanishingStore lists key but answers not-found when it is read: a record |
| +// deleted between a listing and its read. |
| +type vanishingStore struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (s vanishingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == s.key { |
| + return nil, "", fmt.Errorf("vanished: %w", os.ErrNotExist) |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +// remoteFailingRecordStore fails every listing under one record family. |
| +type remoteFailingRecordStore struct { |
| + release.Store |
| + family string |
| +} |
| + |
| +func (s remoteFailingRecordStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + if strings.Contains(prefix, s.family) { |
| + return nil, fmt.Errorf("boom") |
| + } |
| + return s.Store.List(ctx, prefix) |
| +} |
| + |
| +// budgetStore counts the reads the request budget is about: box reports, |
| +// instance records and host incarnation slots. |
| +type budgetStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + boxLists, boxGets, recLists, recGets, slotGets int |
| +} |
| + |
| +func (c *budgetStore) note(key string, list bool) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + switch { |
| + case strings.HasPrefix(key, "status/boxes/") && list: |
| + c.boxLists++ |
| + case strings.HasPrefix(key, "status/boxes/"): |
| + c.boxGets++ |
| + case strings.HasPrefix(key, "apps/") && strings.Contains(key, "/instances/") && list: |
| + c.recLists++ |
| + case strings.HasPrefix(key, "apps/") && strings.Contains(key, "/instances/"): |
| + c.recGets++ |
| + case strings.HasPrefix(key, "control/host-incarnations/") && !list: |
| + c.slotGets++ |
| + } |
| +} |
| + |
| +func (c *budgetStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + c.note(prefix, true) |
| + return c.Store.List(ctx, prefix) |
| +} |
| + |
| +func (c *budgetStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + c.note(key, false) |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *budgetStore) counts() [5]int { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return [5]int{c.boxLists, c.boxGets, c.recLists, c.recGets, c.slotGets} |
| +} |
| + |
| +func (c *budgetStore) reset() { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.boxLists, c.boxGets, c.recLists, c.recGets, c.slotGets = 0, 0, 0, 0, 0 |
| +} |
| + |
| +// TestRemoteInstanceRequestBudget counts store calls per page view, with |
| +// lifetimes on, so every record read is judged against its host's slot. |
| +// Armed record view: the first Overview view reads the box reports once |
| +// (one LIST and one GET per box), no record, and the remote record's slot |
| +// once; a second view within a minute reads nothing; after the minute it |
| +// reads the reports and the slot once more. Every app tab shares the one |
| +// read. Unarmed: the records cost one LIST plus one GET per record, once a |
| +// minute like the reports. |
| +func TestRemoteInstanceRequestBudget(t *testing.T) { |
| + ltClock := useLifetimesClock(t) |
| + tb := newTwoBoxes(t) |
| + turnLifetimesOn(t, tb.fx.srv, ltClock) |
| + tb.setUp(t, false) |
| + if slot, _, err := provision.ReadHostIncarnation(context.Background(), tb.fx.rel, remoteHost); err != nil || slot == nil { |
| + t.Fatalf("fixture: the remote instance has no lifetime slot: %+v %v", slot, err) |
| + } |
| + cs := &budgetStore{Store: tb.fx.rel} |
| + tb.fx.srv.cfg.Releases = cs |
| + v := provision.NewRecordView(cs, release.NewChangeWatch(cs)) |
| + if err := v.Rebuild(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if sn := v.Snapshot(); sn == nil || !sn.Complete { |
| + t.Fatal("fixture: the record view is not Complete") |
| + } |
| + tb.fx.srv.SetRecordView(v) |
| + clock := time.Now() |
| + tb.fx.srv.boxReports.now = func() time.Time { return clock } |
| + // The DNS guidance's edge-address fold reads status/boxes/ too, on its |
| + // own edgeFoldTTL cache, and predates this change; it is not part of |
| + // this budget, so it is stubbed out of the count. |
| + tb.fx.srv.foldEdgeIPs = func(context.Context) []string { return nil } |
| + cs.reset() |
| + |
| + tb.page(t, "/apps/shop") |
| + if got := cs.counts(); got != [5]int{1, 2, 0, 0, 1} { |
| + t.Fatalf("first armed overview: box LIST/GET, record LIST/GET, slot GET = %v, want [1 2 0 0 1]", got) |
| + } |
| + cs.reset() |
| + // The pages whose only box-report read is this change's. (The Running |
| + // tab, the instance page, Settings and Releases each make reads of their |
| + // own that predate it: the region note, the rollout join, the domain |
| + // readings. They are unchanged, and the Running tab is pinned below.) |
| + for _, path := range []string{"/apps/shop", "/apps/shop/deployments", "/"} { |
| + tb.page(t, path) |
| + } |
| + if got := cs.counts(); got != [5]int{0, 0, 0, 0, 0} { |
| + t.Fatalf("views within the minute = %v, want no box, record or slot reads", got) |
| + } |
| + // The Running tab's region note reads the reports itself, through |
| + // liveEdges (appDefault), and did before this change. One read is that |
| + // note's; a second would be this change failing to share the cache. |
| + cs.reset() |
| + tb.page(t, "/apps/shop/instances") |
| + if got := cs.counts(); got != [5]int{1, 2, 0, 0, 0} { |
| + t.Fatalf("Running tab within the minute = %v, want only the region note's own [1 2 0 0 0]", got) |
| + } |
| + clock = clock.Add(boxReportTTL + time.Second) |
| + cs.reset() |
| + tb.page(t, "/apps/shop") |
| + if got := cs.counts(); got != [5]int{1, 2, 0, 0, 1} { |
| + t.Fatalf("overview after the minute = %v, want [1 2 0 0 1]", got) |
| + } |
| + |
| + // Unarmed, once the minute is up: one LIST and one GET for the app's |
| + // one record, and its slot; within the next minute, nothing. |
| + tb.fx.srv.SetRecordView(nil) |
| + clock = clock.Add(boxReportTTL + time.Second) |
| + cs.reset() |
| + tb.page(t, "/apps/shop") |
| + if got := cs.counts(); got != [5]int{1, 2, 1, 1, 1} { |
| + t.Fatalf("unarmed overview after the minute = %v, want [1 2 1 1 1]", got) |
| + } |
| + cs.reset() |
| + tb.page(t, "/apps/shop") |
| + if got := cs.counts(); got != [5]int{0, 0, 0, 0, 0} { |
| + t.Fatalf("unarmed overview within the minute = %v, want none", got) |
| + } |
| +} |
| + |
| +// factsOf and pickFor wrap folded reports in the one accessor's type, for |
| +// unit tests of the join rules. |
| +func factsOf(f fleetReports, acct, app string) appFacts { |
| + return appFacts{acct: acct, app: app, reports: f} |
| +} |
| + |
| +func pickFor(f fleetReports, host, acct, app string) *hostReport { |
| + return factsOf(f, acct, app).host(provision.Record{Host: host, Account: acct, App: app}) |
| +} |
diff --git a/internal/console/seedfinish.go b/internal/console/seedfinish.go| index 13978059d..bffc7ae1b 100644 |
| --- a/internal/console/seedfinish.go |
| +++ b/internal/console/seedfinish.go |
| @@ -105,6 +105,7 @@ func (s *Server) finishSeedOnce(ctx context.Context, sqid, app, host, seedID str |
| return nil // another finish deleted the record |
| } |
| } |
| + s.noteRecordDeletion(sqid, app, time.Now()) // the canary-retire guard's evidence, first |
| if lifetimesUnit(ctx) { |
| // Admitted on: the record retires through its tombstone, bound to |
| // the last read that saw this seed (lifetimes_retire.go). A CAS |
diff --git a/internal/console/server.go b/internal/console/server.go| index bc591dd35..37df0eaa8 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -18,6 +18,7 @@ import ( |
| "html/template" |
| "io" |
| "log" |
| + "maps" |
| "math" |
| mrand "math/rand/v2" |
| "net" |
| @@ -1233,6 +1234,22 @@ type Server struct { |
| // arms it; nil (disarmed) is every sweep walking the bucket as before |
| // the index. |
| recordView *provision.RecordView |
| + // boxReports is the page views' shared read of every box's status report |
| + // (remoteinstances.go), held for boxReportTTL so the app pages ask the |
| + // bucket at most once a minute however many people browse. |
| + boxReports boxReportCache |
| + // retireBeforeDeleteHook, when set, runs in the canary retire between |
| + // the follower check and the final record comparison. Tests only. |
| + retireBeforeDeleteHook func() |
| + // startedAt overrides when this console started (zero: the process |
| + // start, processStart; tests set it), and deletions is when it last |
| + // began deleting an instance or sidecar record of each app (acct + "/" |
| + // + app): the canary-retire guard's deletion evidence |
| + // (recentRecordDeletion). Memory, so it cannot fail to be written; the |
| + // guard does not vouch for the channelSettle before the start. |
| + startedAt time.Time |
| + deletionsMu sync.Mutex |
| + deletions map[string]time.Time |
| // viewUse is the last recordWalkStore outcome, so a switch between the |
| // view and the bucket is logged once, not on every pass. |
| viewUse atomic.Int32 |
| @@ -3415,7 +3432,7 @@ func (s *Server) handleAccountHome(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| if len(apps) > 0 { |
| - views, err := Assemble(r.Context(), s.cfg.Registry, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, apps, s.dnsTargets(r.Context())) |
| + views, err := s.assembleApps(r.Context(), acct.Sqid, apps) |
| if err != nil { |
| log.Printf("console: assemble: %v", err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read platform state. Please try again.") |
| @@ -3582,7 +3599,7 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa |
| // bucket hiccup there is deliberately non-fatal, and this is where it gets |
| // another chance. Best-effort — a page view never fails on it. |
| s.ensureAccountManifest(r.Context(), acct) |
| - views, err := Assemble(r.Context(), s.cfg.Registry, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, []string{app}, s.dnsTargets(r.Context())) |
| + views, err := s.assembleApps(r.Context(), acct.Sqid, []string{app}) |
| if err != nil || len(views) != 1 { |
| log.Printf("console: assemble %s: %v", app, err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not read platform state. Please try again.") |
| @@ -3605,8 +3622,20 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa |
| if review, all, err := s.appAccountReview(addr, acct, app); err != nil { |
| log.Printf("console: account review %s/%s: %v", acct.Sqid, app, err) |
| } else { |
| + // The review itself reads the console box's registry: it is about |
| + // local rows stamped with another account. Its two claims about the |
| + // app as a whole ("no instances", "not deploying") must also count |
| + // the account's instances on other boxes, or an app whose instances |
| + // all moved away would be told it has none. |
| + remoteOwned := 0 |
| + for _, rt := range p.Detail.Routes { |
| + if rt.remote && rt.Account == acct.Sqid { |
| + remoteOwned++ |
| + } |
| + } |
| + all = all && remoteOwned == 0 |
| p.AccountReview = review |
| - p.AccountReview.NoInstances = review.Owned == 0 && hasPublishedChannel(p.Detail.Channels) |
| + p.AccountReview.NoInstances = review.Owned == 0 && remoteOwned == 0 && hasPublishedChannel(p.Detail.Channels) |
| for _, group := range review.Groups { |
| for _, host := range group.Hosts { |
| p.Detail.Mismatched = append(p.Detail.Mismatched, MismatchedRoute{Host: host, Account: group.Account.Sqid}) |
| @@ -3691,17 +3720,32 @@ func (s *Server) appResourceMetrics(ctx context.Context, view *AppView, acct *Ac |
| hosts := make([]string, 0, len(view.Routes)) |
| hib := make(map[string]bool, len(view.Routes)) |
| unitByHost := make(map[string]string, len(view.Routes)) |
| + sinceByHost := map[string]time.Time{} |
| for _, rt := range view.Routes { |
| if rt.Account != acct.Sqid { |
| continue |
| } |
| + // An instance on another box takes no readings at all: its host |
| + // name alone is not this tenant's, since another box may serve it |
| + // for someone else, and no sample on any box is proven theirs. Its |
| + // row shows the no-data state (remoteinstances.go). |
| + if rt.remote { |
| + continue |
| + } |
| + // History starts when this owner came to have the host: samples |
| + // from a previous tenant of the same hostname are not theirs. A |
| + // local row that is provisioned or has a record is bounded |
| + // (RouteView.bounded); only a hand route with no record is not. |
| + if rt.bounded { |
| + sinceByHost[rt.Host] = rt.since |
| + } |
| hosts = append(hosts, rt.Host) |
| hib[rt.Host] = rt.Hibernate |
| if rt.Unit != "" { |
| unitByHost[rt.Host] = rt.Unit |
| } |
| } |
| - am, err := s.OwnerAppMetrics(ctx, hosts, unitByHost) |
| + am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost) |
| if err != nil { |
| log.Printf("console: app metrics %s: %v", view.App, err) |
| return nil |
| @@ -3730,9 +3774,10 @@ func (s *Server) handleApp(w http.ResponseWriter, r *http.Request) { |
| metrics := s.appResourceMetrics(r.Context(), p.Detail, acct) |
| // The Database tile's sizes are best-effort: a slow status read costs the |
| // tile its number (the em-dash), never the page. |
| - joinCtx, cancelJoin := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| - dbJoin := loadBoxJoin(joinCtx, s.cfg.Releases, time.Now()) |
| - cancelJoin() |
| + // The box reports are the page views' shared, minute-old read |
| + // (pageBoxReports), the same one Assemble joined remote rows from. |
| + boxes, _ := s.pageBoxReports(r.Context()) |
| + dbJoin := joinBoxes(boxes, time.Now()) |
| p.Overview = assembleOverview(p.Detail, acct.Sqid, metrics, versions, dbJoin) |
| // The diagram is drawn from the SAME tenant-filtered rows the Running tab |
| // renders, so the two can never disagree about which addresses exist or |
| @@ -5308,14 +5353,36 @@ func (s *Server) handleFastTrack(w http.ResponseWriter, r *http.Request) { |
| // name becomes a channel path segment and an on-box state file name. |
| var canaryNameRe = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`) |
| -// channelHosts lists the registry hosts whose routes follow app's channel, |
| -// and reports whether the registry could be read at all. The two call sites |
| -// deliberately treat that error differently: handleNewCanary's use is |
| +// channelSettle is how long after any instance or sidecar record of an app |
| +// was created, changed or deleted the canary-retire guard refuses to call |
| +// a channel unfollowed (retireUnsettled). Boxes converge record changes |
| +// within seconds of the serial bump; a box that has not done so in three |
| +// status snapshot periods is one the fleet's own staleness rule |
| +// (status.BoxStale) already treats as dark. Paul accepted the wait. |
| +const channelSettle = 15 * time.Minute |
| + |
| +// channelHosts lists the hosts that follow app's channel, and reports |
| +// whether that could be checked at all. The followers are every route in |
| +// the console box's registry of an app by this NAME (any account: |
| +// over-counting here only ever refuses a retire) and every instance and |
| +// sidecar record of acct/app that names the channel, read strictly and live |
| +// (not through the record view: a record written without its change-index |
| +// bump is missing from a snapshot until the backstop, and this is the one |
| +// reader whose "nobody" deletes something). A follower whose route is on |
| +// another box is in no registry this console can see, so without the |
| +// records a canary followed only from another region would read as |
| +// unfollowed. |
| +// |
| +// With no follower, the answer is still only "nobody" when the app has |
| +// settled (retireUnsettled): a box may still be running a host on the |
| +// channel after its record moved off it or was deleted, and box reports do |
| +// not carry a host's channel. Otherwise the error is errRetireUnsettled. |
| +// |
| +// The two call sites treat errors differently: handleNewCanary's use is |
| // cosmetic (which URL to show in a success flash) and downgrades an error to |
| -// "no hosts", but handleRetireCanary's use is load-bearing — a canary with |
| -// followers must never be deleted — so it must fail CLOSED on a registry |
| -// hiccup rather than silently reading the error as "safe to retire". |
| -func (s *Server) channelHosts(app, channel string) ([]string, error) { |
| +// "no hosts", but handleRetireCanary's use is load-bearing, a canary with |
| +// followers must never be deleted, so it fails CLOSED on every error. |
| +func (s *Server) channelHosts(ctx context.Context, acct, app, channel string) ([]string, error) { |
| reg, err := openRegistry(s.cfg.Registry) |
| if err != nil { |
| return nil, err |
| @@ -5325,12 +5392,78 @@ func (s *Server) channelHosts(app, channel string) ([]string, error) { |
| return nil, err |
| } |
| var out []string |
| + seen := map[string]bool{} |
| + add := func(host string) { |
| + if !seen[host] { |
| + seen[host] = true |
| + out = append(out, host) |
| + } |
| + } |
| for _, rt := range routes { |
| if rt.App == app && rt.Channel == channel { |
| - out = append(out, rt.Host) |
| + add(rt.Host) |
| + } |
| + } |
| + if s.cfg.Releases == nil { |
| + return out, nil |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout) |
| + defer cancel() |
| + recs, unreadable, err := s.listRecordsStrict(ctx, acct, app, instanceListMax) |
| + if err != nil { |
| + return nil, fmt.Errorf("instance records of %s/%s: %w", acct, app, err) |
| + } |
| + if len(unreadable) > 0 { |
| + return nil, fmt.Errorf("instance records of %s/%s: %d will not read", acct, app, len(unreadable)) |
| + } |
| + // keys is every record this app has now, instance and sidecar, by its |
| + // bucket key, and hosts every host they name: retireUnsettled weighs |
| + // both against the modification times and the box reports. |
| + keys := map[string]bool{} |
| + hosts := map[string]bool{} |
| + for _, rec := range recs { |
| + keys[provision.RecordKey(acct, app, rec.Host)] = true |
| + hosts[rec.Host] = true |
| + if rec.Channel == channel { |
| + add(rec.Host) |
| + } |
| + } |
| + // Sidecar records are read here rather than through |
| + // provision.ListSidecarRecordsStrict, which skips a record that vanishes |
| + // between its listing and its read. A sidecar whose record is going is |
| + // still running until its box converges, so a listed record that will |
| + // not read, for any reason, refuses the retire too. |
| + prefix := provision.SidecarsPrefix(acct, app) |
| + sideKeys, err := s.cfg.Releases.List(ctx, prefix) |
| + if err != nil { |
| + return nil, fmt.Errorf("sidecar records of %s/%s: %w", acct, app, err) |
| + } |
| + for _, key := range sideKeys { |
| + rest, ok := strings.CutPrefix(key, prefix) |
| + if !ok || rest == "" || strings.Contains(rest, "/") { |
| + continue |
| + } |
| + name, ok := strings.CutSuffix(rest, ".json") |
| + if !ok || name == "" { |
| + continue |
| + } |
| + rec, err := provision.GetSidecarRecord(ctx, s.cfg.Releases, acct, app, name) |
| + if err != nil { |
| + return nil, fmt.Errorf("sidecar record %s: %w", key, err) |
| + } |
| + keys[key] = true |
| + hosts[rec.Host] = true |
| + if rec.Channel == channel { |
| + add(rec.Host) |
| } |
| } |
| - return out, nil |
| + if len(out) > 0 { |
| + return out, nil |
| + } |
| + if err := s.retireUnsettled(ctx, acct, app, keys, hosts); err != nil { |
| + return nil, err |
| + } |
| + return nil, nil |
| } |
| // handleNewCanary creates a canary: a brand-new canary/<name> channel |
| @@ -5417,7 +5550,7 @@ func (s *Server) handleNewCanary(w http.ResponseWriter, r *http.Request) { |
| // Best-effort here: which URL to show in the success flash is cosmetic, |
| // so a registry hiccup just falls back to the generic "attach one" copy |
| // rather than failing the create that already succeeded. |
| - if hosts, _ := s.channelHosts(app, channel); len(hosts) > 0 { |
| + if hosts, _ := s.channelHosts(ctx, acct.Sqid, app, channel); len(hosts) > 0 { |
| back("ok", "Created canary "+name+" — live at https://"+hosts[0]+" serving "+version+" (test versions have no safety delay).") |
| return |
| } |
| @@ -5518,7 +5651,24 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) { |
| // A canary with followers is load-bearing: retiring its pointer would |
| // strand every host on it. Fail CLOSED on a registry error — an "I |
| // couldn't check" must never be read as "nobody follows this channel". |
| - hosts, err := s.channelHosts(app, channel) |
| + checkCtx, cancelCheck := context.WithTimeout(r.Context(), 15*time.Second) |
| + // The app's records as they stand before the check, compared again just |
| + // before the delete: no lock covers record writes, so a record created, |
| + // changed or deleted in between refuses the retire (recordStamps). |
| + before, err := s.recordStamps(checkCtx, acct.Sqid, app) |
| + var hosts []string |
| + if err == nil { |
| + hosts, err = s.channelHosts(checkCtx, acct.Sqid, app, channel) |
| + } |
| + cancelCheck() |
| + if errors.Is(err, errRetireUnsettled) { |
| + // Nobody follows the channel by any record, but the app changed too |
| + // recently (or a box still serves a host with no record) for that |
| + // to be the whole story yet. |
| + log.Printf("console: retire %s %s: %v", app, channel, err) |
| + back("err", "Could not verify no hosts follow this channel — try again.") |
| + return |
| + } |
| if err != nil { |
| log.Printf("console: retire %s %s: check followers: %v", app, channel, err) |
| s.renderMessage(w, r, http.StatusInternalServerError, "Error", |
| @@ -5532,7 +5682,8 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) { |
| ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| defer cancel() |
| key := release.ChannelKey(acct.Sqid, app, channel) |
| - if _, _, err := s.cfg.Releases.Get(ctx, key); errors.Is(err, os.ErrNotExist) { |
| + _, pointerETag, err := s.cfg.Releases.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| back("err", "No canary named "+name+" here.") |
| return |
| } else if err != nil { |
| @@ -5543,9 +5694,49 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) { |
| s.confirmRetireCanary(w, r, addr, raw, acct, role, app, name) |
| return |
| } |
| - if err := s.appMutation(ctx, acct, app, "canary-retire", func(ctx context.Context) error { |
| - return s.cfg.Releases.Delete(ctx, key) |
| - }); err != nil { |
| + err = s.appMutation(ctx, acct, app, "canary-retire", func(ctx context.Context) error { |
| + if h := s.retireBeforeDeleteHook; h != nil { |
| + h() |
| + } |
| + after, err := s.recordStamps(ctx, acct.Sqid, app) |
| + if err != nil { |
| + return err |
| + } |
| + if !maps.Equal(before, after) { |
| + return fmt.Errorf("%w: the app's records changed during the check", errRetireUnsettled) |
| + } |
| + // The pointer must still be the one read above: a promotion or a |
| + // removal meanwhile refuses. |
| + if _, cur, gerr := s.cfg.Releases.Get(ctx, key); gerr != nil || cur != pointerETag { |
| + if gerr != nil && !errors.Is(gerr, os.ErrNotExist) { |
| + return gerr |
| + } |
| + return fmt.Errorf("%w: the canary's pointer changed during the check", errRetireUnsettled) |
| + } |
| + // Delete exactly the pointer read above: a promotion since then |
| + // conflicts, and the retire is refused rather than deleting bytes |
| + // this check never saw. |
| + if err := release.DeleteIfMatch(ctx, s.cfg.Releases, key, pointerETag); err != nil { |
| + if errors.Is(err, release.ErrCASConflict) { |
| + return fmt.Errorf("%w: the canary's pointer changed during the check", errRetireUnsettled) |
| + } |
| + return err |
| + } |
| + // A record written after the comparison above and before this delete |
| + // reaches its box only after the serial bump, by which time the |
| + // pointer is gone: the same as creating an instance on a channel |
| + // nobody has promoted, which the create door allows. No restore is |
| + // attempted: the store cannot tell "deleted the revision read" from |
| + // "already gone", so putting bytes back could resurrect a pointer |
| + // someone else removed. |
| + return nil |
| + }) |
| + if errors.Is(err, errRetireUnsettled) { |
| + log.Printf("console: retire %s %s: %v", app, channel, err) |
| + back("err", "Could not verify no hosts follow this channel — try again.") |
| + return |
| + } |
| + if err != nil { |
| log.Printf("console: retire %s %s: %v", app, channel, err) |
| back("err", "Retiring the canary failed: "+err.Error()) |
| return |
| @@ -5611,11 +5802,14 @@ func summarize(v AppView, acct string) appRow { |
| } |
| deployment := observedDeployment(v.Routes, acct) |
| row := appRow{App: v.App, URL: apexHost(mine), Deployment: deployment} |
| - attention := false |
| + attention, unknown := false, false |
| for _, rt := range mine { |
| if !rt.Platform && rt.Status == "failed" { |
| attention = true |
| } |
| + // An instance on another box whose state no report vouches for |
| + // (remoteinstances.go): the row can't tell, not "Deployed". |
| + unknown = unknown || rt.unknown |
| } |
| for _, ch := range v.Channels { |
| if ch.Err == "" && strings.HasPrefix(ch.Name, "canary/") { |
| @@ -5627,6 +5821,8 @@ func summarize(v AppView, acct string) appRow { |
| row.Verdict, row.VerdictLabel = "notdeployed", "Not deployed yet" |
| case attention: |
| row.Verdict, row.VerdictLabel = "attention", "Needs attention" |
| + case unknown: |
| + row.Verdict, row.VerdictLabel = "unknown", "Can't tell right now" |
| case deployment.ReportableCount == 0: |
| row.Verdict, row.VerdictLabel = "ok", "Deployed" |
| case !deployment.HasReportedVersion(): |
diff --git a/internal/console/server_test.go b/internal/console/server_test.go| index 8dcb36e29..6aa5b3d31 100644 |
| --- a/internal/console/server_test.go |
| +++ b/internal/console/server_test.go |
| @@ -144,6 +144,9 @@ func newConsoleFixtureWith(t *testing.T, o consoleFixtureOptions) *consoleFixtur |
| } |
| // Fixture route hosts don't resolve; keep the not-reporting verdict quick. |
| srv.instances.timeout = 100 * time.Millisecond |
| + // A console that has been up a while: the canary-retire guard does not |
| + // vouch for the window before a console started (recentRecordDeletion). |
| + srv.startedAt = time.Now().Add(-24 * time.Hour) |
| // paul owns the built-in ops account (created by NewServer's backfill), |
| // which claims kass — the shape a deployment is in once the pre-accounts |
| // grants have been mapped onto memberships. |
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html| index f029121bb..3654ded31 100644 |
| --- a/internal/console/templates/app_overview.html |
| +++ b/internal/console/templates/app_overview.html |
| @@ -29,8 +29,8 @@ |
| routinely share a box. */}} |
| <a class="tile" href="{{$.Nav}}/apps/{{$.AppName}}/instances"> |
| <h2>Running</h2> |
| - <p class="tile-value">{{if eq .InstanceTotal 0}}—{{else if eq .InstanceExpected 0}}Served{{else if .MetricsUnavailable}}?{{else if eq .InstanceCounted 0}}?{{else}}{{.InstanceReporting}} of {{.InstanceCounted}}{{end}}</p> |
| - <p class="tile-detail">{{if eq .InstanceTotal 0}}nothing running yet{{else if eq .InstanceExpected 0}}static — the platform serves it, nothing to run{{else if .MetricsUnavailable}}no data right now{{else if eq .InstanceCounted 0}}no readings for {{.InstanceNoReadings}} copies — stamp their units to see health{{else}}copies reporting{{if .InstanceAsleep}} · {{.InstanceAsleep}} asleep{{end}}{{if .InstanceNoReadings}} · {{.InstanceNoReadings}} no readings{{end}}{{end}}</p> |
| + <p class="tile-value">{{if eq .InstanceTotal 0}}—{{else if and (eq .InstanceExpected 0) (eq .InstanceUnknown 0)}}Served{{else if .MetricsUnavailable}}?{{else if eq .InstanceCounted 0}}?{{else}}{{.InstanceReporting}} of {{.InstanceCounted}}{{end}}</p> |
| + <p class="tile-detail">{{if eq .InstanceTotal 0}}nothing running yet{{else if and (eq .InstanceExpected 0) (eq .InstanceUnknown 0)}}static — the platform serves it, nothing to run{{else if or .MetricsUnavailable (and (eq .InstanceCounted 0) .InstanceUnknown)}}no data right now{{else if eq .InstanceCounted 0}}no readings for {{.InstanceNoReadings}} copies — stamp their units to see health{{else}}copies reporting{{if .InstanceAsleep}} · {{.InstanceAsleep}} asleep{{end}}{{if .InstanceNoReadings}} · {{.InstanceNoReadings}} no readings{{end}}{{end}}</p> |
| </a> |
| <a class="tile" href="{{$.Nav}}/apps/{{$.AppName}}/instances"> |
| <h2>Resources</h2> |
| @@ -49,7 +49,7 @@ |
| <a class="tile" href="{{$.Nav}}/apps/{{$.AppName}}/settings/domains"> |
| <h2>Web addresses</h2> |
| <p class="tile-value">{{.DomainTotal}}</p> |
| - <p class="tile-detail">{{if eq .DomainTotal 0}}one appears after your first deploy{{else if .DomainAttention}}<span class="error">{{.DomainAttention}} need{{if eq .DomainAttention 1}}s{{end}} attention</span>{{else}}DNS & certs OK{{end}}</p> |
| + <p class="tile-detail">{{if eq .DomainTotal 0}}one appears after your first deploy{{else if .DomainAttention}}<span class="error">{{.DomainAttention}} need{{if eq .DomainAttention 1}}s{{end}} attention</span>{{else if .DomainUnknown}}no data right now{{else}}DNS & certs OK{{end}}</p> |
| </a> |
| <a class="tile" href="{{$.Nav}}/apps/{{$.AppName}}/releases"> |
| <h2>{{$.DeploymentsCopy.History}}</h2> |
diff --git a/internal/console/view.go b/internal/console/view.go| index 029945dd5..90544da62 100644 |
| --- a/internal/console/view.go |
| +++ b/internal/console/view.go |
| @@ -365,6 +365,32 @@ type RouteView struct { |
| // Provisioned mirrors registry.Route.Provisioned: minted from a bucket |
| // instance record, so the activator runs its process by construction. |
| Provisioned bool |
| + |
| + // remote marks a row built from a bucket instance record whose route is |
| + // on another box (remoteinstances.go), not from the console box's own |
| + // registry. The rest are that row's live state from the box report it |
| + // joined: which box, its database size, the custom domains it routes to |
| + // the host, and whether its rollout report says the process is awake. |
| + // All zero on a local row. |
| + remote bool |
| + box string |
| + dbBytes *int64 |
| + aliases []string |
| + boxAwake bool |
| + // unknown says the row's process state is not known (remoteRoute): |
| + // its health reads "Can't tell right now". A remote row takes no |
| + // metrics readings at all (appResourceMetrics skips it). |
| + unknown bool |
| + // since is when this local row's owner came to have the host: its |
| + // instance record's created_at (addRemoteRows). Metrics samples before |
| + // it are not this owner's (ownerAppMetricsFrom). |
| + since time.Time |
| + // bounded says since applies to this local row's readings, zero |
| + // meaning no readings at all: every local row that is provisioned or |
| + // has a record. A provisioned local row whose record could not be read |
| + // has an unknown start, so it shows nothing rather than the whole |
| + // window. Only a hand route with no record is unbounded. |
| + bounded bool |
| } |
| // humanizeCaps renders a registry.Route.Caps column for a person: the |
| @@ -550,7 +576,17 @@ func openRegistry(path string) (consoleRegistry, error) { |
| // edge addresses nor a steering hostname known). Every app in apps gets an |
| // AppView, even an empty one; per-channel failures degrade to |
| // ChannelView.Err. |
| -func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets) ([]AppView, error) { |
| +// |
| +// remote, when not nil, adds a row for every instance record of the |
| +// account's apps whose host has no row in the console box's registry |
| +// (remoteinstances.go; page views pass Server.remoteSource). A host the |
| +// registry has, under ANY account, gets no remote row: the local row is |
| +// authoritative for its host (Status, Unit, Backing, Caps, the mismatch |
| +// review), and a local row stamped to another account is the account |
| +// review's business, not a reason to show a second row. A record that |
| +// cannot be read costs that app its remote rows and nothing else. nil is |
| +// the console box's registry alone. |
| +func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets, remote *remoteRows) ([]AppView, error) { |
| reg, err := openRegistry(regPath) |
| if err != nil { |
| return nil, err |
| @@ -568,7 +604,9 @@ func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519. |
| // the server, after it knows the viewer's memberships. |
| byApp := map[string][]RouteView{} |
| domainsByApp := map[string][]DomainView{} |
| + localHosts := make(map[string]bool, len(routes)) |
| for _, rt := range routes { |
| + localHosts[rt.Host] = true |
| rtAcct := release.RouteAccount(rt) |
| if rtAcct != acct { |
| continue |
| @@ -612,6 +650,9 @@ func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519. |
| continue |
| } |
| seen[app] = true |
| + if remote != nil { |
| + byApp[app], domainsByApp[app] = addRemoteRows(remote, acct, app, localHosts, byApp[app], domainsByApp[app], dns) |
| + } |
| channels := assembleChannels(ctx, s, pub, acct, app, now) |
| pv := assembleProduction(ctx, s, pub, acct, app, channels, byApp[app], now) |
| if pv.Err == "" && !pv.On { |
| @@ -644,6 +685,65 @@ func Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519. |
| return out, nil |
| } |
| +// addRemoteRows appends a row for each of acct/app's records whose host the |
| +// console box's registry does not have, keeping Routes and Domains parallel |
| +// and in host order (assembleOverview joins them by index). |
| +// |
| +// The account check on each record is the tenant boundary and is made here |
| +// again, not trusted to the reader: a record is acct's only when it sits |
| +// under apps/<acct>/<app>/ AND says so (provision.GetRecord refuses one that |
| +// disagrees with its own path; this refuses one a reader handed over from |
| +// anywhere else). |
| +func addRemoteRows(remote *remoteRows, acct, app string, localHosts map[string]bool, routes []RouteView, domains []DomainView, dns DNSTargets) ([]RouteView, []DomainView) { |
| + ownLocal := make(map[string]int, len(routes)) |
| + for i, rt := range routes { |
| + ownLocal[rt.Host] = i |
| + // A provisioned row has a record by construction: until it is |
| + // read, its ownership start is unknown. |
| + routes[i].bounded = rt.Provisioned |
| + } |
| + facts := remote.facts(app) |
| + recs, err := remote.records(app) |
| + if err != nil { |
| + log.Printf("console: instance records %s/%s: %v", acct, app, err) |
| + return routes, domains |
| + } |
| + added := false |
| + for _, rec := range recs { |
| + if rec.Account != acct || rec.App != app || rec.Host == "" { |
| + continue |
| + } |
| + if localHosts[rec.Host] { |
| + // The host's row is the console box's own. Its record still |
| + // says when this owner came to have the hostname, which bounds |
| + // the row's metrics history: an earlier tenant of the same |
| + // hostname left samples under the same unit name. |
| + if i, ok := ownLocal[rec.Host]; ok { |
| + routes[i].since, routes[i].bounded = rec.CreatedAt, true |
| + } |
| + continue |
| + } |
| + rv, dv := remoteRoute(rec, facts.host(rec), facts, acct, dns) |
| + routes = append(routes, rv) |
| + domains = append(domains, dv) |
| + added = true |
| + } |
| + if added { |
| + idx := make([]int, len(routes)) |
| + for i := range idx { |
| + idx[i] = i |
| + } |
| + sort.SliceStable(idx, func(a, b int) bool { return routes[idx[a]].Host < routes[idx[b]].Host }) |
| + r2 := make([]RouteView, len(routes)) |
| + d2 := make([]DomainView, len(domains)) |
| + for i, j := range idx { |
| + r2[i], d2[i] = routes[j], domains[j] |
| + } |
| + routes, domains = r2, d2 |
| + } |
| + return routes, domains |
| +} |
| + |
| // assembleCanaries derives the canary list: every canary/* channel, with the |
| // hosts whose routes follow it. |
| func assembleCanaries(channels []ChannelView, routes []RouteView) []CanaryView { |
diff --git a/internal/console/view_test.go b/internal/console/view_test.go| index 6fd15ede7..d96f28eda 100644 |
| --- a/internal/console/view_test.go |
| +++ b/internal/console/view_test.go |
| @@ -180,7 +180,7 @@ func TestAssemble(t *testing.T) { |
| if err := release.SetProduction(context.Background(), store, priv, release.OpsAccount, "kass", true, "test"); err != nil { |
| t.Fatal(err) |
| } |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -236,7 +236,7 @@ func TestAssembleCanaries(t *testing.T) { |
| Status: "ready", App: "kass", Channel: "canary/x", Canary: true}); err != nil { |
| t.Fatal(err) |
| } |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -258,7 +258,7 @@ func TestAssembleCanaries(t *testing.T) { |
| func TestAssembleFiltersToGivenApps(t *testing.T) { |
| regPath, store, _, pub := buildFixtures(t) |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -276,7 +276,7 @@ func TestAssembleFiltersToGivenApps(t *testing.T) { |
| func TestAssembleEmptyAppStillListed(t *testing.T) { |
| regPath, store, _, pub := buildFixtures(t) |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"ghost", "kass"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"ghost", "kass"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -294,7 +294,7 @@ func TestAssembleDegradesBadChannel(t *testing.T) { |
| if _, err := store.Put(context.Background(), release.ChannelKey(release.OpsAccount, "kass", "beta"), []byte("not a signed pointer"), ""); err != nil { |
| t.Fatal(err) |
| } |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatalf("Assemble must not fail on a bad channel: %v", err) |
| } |
| @@ -323,7 +323,7 @@ func TestAssembleCarriesProcessOwnership(t *testing.T) { |
| Unit: "titogo@demo.service", Backing: registry.BackingUnit, Provisioned: true}); err != nil { |
| t.Fatal(err) |
| } |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"kass"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -366,7 +366,7 @@ func TestMismatchListsRoutes(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"mismatchlist"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"mismatchlist"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -403,7 +403,7 @@ func TestMismatchAllRoutes(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"mismatchall"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"mismatchall"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -433,7 +433,7 @@ func TestMismatchIgnoresPlatformRoutes(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"mismatchplatform"}, DNSTargets{}) |
| + views, err := Assemble(context.Background(), regPath, store, pub, release.OpsAccount, []string{"mismatchplatform"}, DNSTargets{}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/provision/console_remote_instances_census_test.go b/internal/provision/console_remote_instances_census_test.go| new file mode 100644 |
| index 000000000..9cc3f003c |
| --- /dev/null |
| +++ b/internal/provision/console_remote_instances_census_test.go |
| @@ -0,0 +1,76 @@ |
| +package provision |
| + |
| +// Record-write census entries for console-remote-instances (the console's |
| +// app pages show instances on other boxes), layered on |
| +// consolePerf1WriteCensusInventory (main's newest at ddf3b929). |
| +// Reviewed by the branch author; the census owner rules on #280 |
| +// (census-ruling-console-remote-instances, with the root-read card |
| +// docs/superpowers/notes/census-proposal-console-remote-instances.md). |
| +// No record write is added anywhere. |
| +// - Server.handleAppInstance: a remote row (an instance record with no |
| +// row in the console box's registry) runs none of the hostname-keyed |
| +// box joins and takes its aliases from its row (remoteFacts) instead of |
| +// the local ListAliases; its instances literal (the |
| +// list URL it links back to) is unchanged and it writes nothing: |
| +// key-site. |
| +// - Server.channelHosts (the canary-retire guard) now also lists the |
| +// app's sidecar records under SidecarsPrefix and reads each with |
| +// GetSidecarRecord, refusing on any read error, to count followers on |
| +// other boxes; it reads, never writes: key-site, like |
| +// Server.checkSidecars. |
| +// - Round 3 review: Server.channelHosts builds RecordKey for each of the |
| +// app's records, to match them against their listed modification |
| +// times; Server.retireUnsettled (replacing round 2's |
| +// unsettledFollowers) lists RecordsPrefix and SidecarsPrefix with |
| +// modification times (ListMod) and reads the console audit log and the |
| +// box reports. Neither writes anything: key-site. |
| +// - Server.deleteRead, Server.finishSeedOnce and |
| +// Server.retireClaimHostRecord, three of the console's record |
| +// deletions, each note the app in the canary-retire guard's in-memory |
| +// deletion log before deleting (noteRecordDeletion); their deletes and |
| +// classes are unchanged. Merging main (a912a342) brought the lifetimes |
| +// retirement: Server.allocCleanLocked's stale-record delete notes the |
| +// app too (class unchanged), as do retireRecordWithLifetime and |
| +// purgeAppWithLifetimes, which are not write sites of their own. |
| +// - Round 4 review: Server.recordStamps is new, listing RecordsPrefix and |
| +// SidecarsPrefix with modification times for the canary retire's |
| +// before/after comparison; Server.retireUnsettled refuses a key the |
| +// follower read did not see; Server.pageRecords reads the bucket, not |
| +// the record view, for an app the console just deleted a record of. |
| +// None writes anything: key-site. |
| +// - Server.handleRetireCanary's pointer delete is conditional on the etag |
| +// its check read; it writes no record and no other object. |
| +// - Server.pageRecords is new (round 1 review): the app pages' record |
| +// reader. It lists RecordsPrefix for the viewed account's app and reads |
| +// each record not already a local row with GetRecord, through the |
| +// record view's snapshot when armed; it writes nothing: key-site, like |
| +// Server.appInstanceCount. |
| +// - Round 6 review: Server.pageRecords holds each app's judged record |
| +// read in the box-report cache for a minute (dropped by every deletion |
| +// note) and no longer takes a skip set. Reads only: key-site. |
| +func consoleRemoteInstancesWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), consolePerf1WriteCensusInventory()...) |
| + replacements := []censusEntry{ |
| + {"internal/console/instancepage.go", "Server.handleAppInstance", "key-site", "lit:instances", "5208ae08d92c1022d7849e4ad50578460bb01b521983e09ee2f39af528a1dc55"}, |
| + {"internal/console/server.go", "Server.channelHosts", "key-site", "key:RecordKey,key:SidecarsPrefix", "05c81080b1bd975c844e031830246881397e2b1864e1dc4a27bd425c77535d99"}, |
| + {"internal/console/apiinstanceimport.go", "Server.deleteRead", "key-site", "key:RecordKey", "b0c92beff1fa7a4f7bbd86ac5c85d675ad4253801bd0bc39cea09c29e34733d3"}, |
| + {"internal/console/seedfinish.go", "Server.finishSeedOnce", "key-site", "key:RecordKey", "940dcce4011bc7eaee0884338166ef04f347a82f576dbaf858c9e8879a32911f"}, |
| + {"internal/console/lifetimes_create.go", "Server.allocCleanLocked", "key-site", "key:RecordKey", "a6f1a6c5f15fec828ab9ff64ca153d6a6b032716d628924caa925640a44f7856"}, |
| + {"internal/console/claim_retire.go", "Server.retireClaimHostRecord", "key-site", "key:claimRetireRecordKey", "3c30cfcad8f2edb3c38b7dd9e56697cd3e17ce3a7fa0e76eb815adf3dad7bd4d"}, |
| + {"internal/console/remoteinstances.go", "Server.retireUnsettled", "key-site", "key:RecordsPrefix,key:SidecarsPrefix", "c1c706feafbb7769a6b3d04e2010cd330d6196a08a4f0068dfd8c530cce8541b"}, |
| + {"internal/console/remoteinstances.go", "Server.pageRecords", "key-site", "key:RecordsPrefix", "6411bbf313cfbb77faeccf6514c907ca339ddd42ccbb90ef93cefa69f6825397"}, |
| + {"internal/console/remoteinstances.go", "Server.recordStamps", "key-site", "key:RecordsPrefix,key:SidecarsPrefix", "c38f120e5be0e8c883b6da7d86df23a5b6b495a31732732e6cbe6efe5821ff43"}, |
| + } |
| + for _, r := range replacements { |
| + found := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], found = r, true |
| + } |
| + } |
| + if !found { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index f9e152217..1fe1933c3 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := consolePerf1WriteCensusInventory() |
| + inventory := consoleRemoteInstancesWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 06a0b5abf..576c17cf5 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -50,3 +50,4 @@ plan14-root-reads-plans-6-checkout.tsv c6a920b27d3206e85ac923b308bdf287931954776 |
| plan14-root-reads-rootfs-root-image.tsv eedd10a4727f2a562495cfd8ed7cffe23c568658858198ec7c8309b5f202ab5a |
| plan14-root-reads-console-perf-1-decisions.tsv 96e1346c6555cde41545ac52913171ec4af55c443c4a62c342e2f0afb5ad505f |
| plan14-root-reads-console-perf-1.tsv da85f1ae6035c36915225c78195aac28ca6f7263d21e1dc6d20c10cfb78fc600 |
| +plan14-root-reads-console-remote-instances.tsv 129e42ead28394976233059b786097bbd42654afee5caa54f24ed17621181fe3 |
diff --git a/internal/provision/testdata/plan14-root-reads-console-remote-instances.tsv b/internal/provision/testdata/plan14-root-reads-console-remote-instances.tsv| new file mode 100644 |
| index 000000000..8f9eb0100 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-console-remote-instances.tsv |
| @@ -0,0 +1,25 @@ |
| +# Census overlay console-remote-instances, written by census-propose (#369). census-ruling-console-remote-instances, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-console-remote-instances.md. |
| +# 9 body, 2 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@legacy 81b2e175961839da32af0e32e53e0a75bfaac577f52b8b3b293f6ca55b2fbd10 internal/console/accountfleet.go Server.assembleAccountFleet legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Fleet tab: the shared-fleet app count also reads the account's own instance records (per app of the account, under its own prefix, region not a fleet placement); the registry read is unchanged. registry:Account@2350,registry:Account@4416,registry:App@2476,registry:Name@4809,registry:Region@2437,whole:Fleet@4001,whole:Fleet@4403,whole:Fleet@4517,whole:Route@2335 9e1c37cdfb0abb8bb0b864ed9fb5413c4b15e17f09b55d1d64760b83de0f8b64 |
| +@legacy 0d769027303bdf8db21b4e9940052ad823cd3837eb68adc179b8077b44f84307 internal/console/apiinstances.go Server.healthByHost legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Takes only the caller's ownership start per host (sinceByHost): readings only from samples at or after it, via ownerAppMetricsFrom. The awake set, the box pin and the until window are gone. Registry reads unchanged. registry:Backing@1178,registry:Hibernate@1112,registry:Kind@1095,registry:Provisioned@1153,registry:Status@972,registry:Unit@1169,registry:Unit@329,registry:Unit@364,whole:Route@177,whole:Route@220,whole:Route@286,whole:Route@949 cc4a0de52038d250031e4739b943a36f799e4cf7ae87a2b64312280861ba6a6e |
| +@legacy ee3d05d9ac77fa0c464c826b7fbd058ed8bf68bd45b211e7ad5ad1848d8ad862 internal/console/apiroutes.go Server.handleAPIRoutes legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Passes nil for healthByHost's ownership-start argument; nothing else. registry:Account@4604,registry:App@1646,registry:App@2104,registry:App@4543,registry:Backing@2264,registry:Canary@2402,registry:Channel@2124,registry:Environment@2149,registry:Hibernate@2223,registry:Host@1730,registry:Host@2046,registry:Host@2202,registry:Host@2358,registry:Host@4676,registry:Host@4756,registry:Kind@2061,registry:Platform@2387,registry:Prefix@4772,registry:Provisioned@2289,registry:Replication@2321,registry:Status@2173,registry:Target@4790,registry:Unit@2243,whole:Route@1635,whole:Route@1684,whole:Route@1721,whole:Route@1741,whole:Route@1861,whole:Route@1963,whole:Route@1994,whole:Route@2094,whole:Route@4667,whole:RoutePath@3609 2fc5fde5477d298cc925ecf9d3b0fbb4cda8095bd7e22df76c2e114e716b5dea |
| +@legacy e096052196bcd47b52cd721741d73c701d59e2f0d6a0a0a0cf9c4b33a1636bf1 internal/console/claim_retire.go Server.retireClaimHostRecord legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-console-remote-instances;basis=Notes the app in the console's in-memory deletion log (noteRecordDeletion, which also invalidates the pages' held box reports) before retiring a record, for the canary-retire guard; the retire itself is unchanged. file:Read@941 3c30cfcad8f2edb3c38b7dd9e56697cd3e17ce3a7fa0e76eb815adf3dad7bd4d |
| +@legacy 2c4f2defe9c0c19d0f25974cf6ddf19e1fbdf2bf5f5658e4b50447c84d4e90ef internal/console/instancepage.go Server.handleAppInstance legacy accepted-legacy accepted-legacy;rev3=merge-ruling-2;basis=Instance page adds updates view from rollout join; browser rendering remains legacy.;rev3=census-ruling-console-remote-instances;basis=A remote row (no local registry row) runs none of the hostname-keyed box joins (layout, rollout, updates): it shows only what its row brought through remoteFacts, aliases included. Local rows read layout, rollout join and ListAliases as before. file:Query@2895,registry:Account@2667,registry:Alias@2767,registry:App@2697,registry:Host@2645,whole:RouteAlias@2628 5208ae08d92c1022d7849e4ad50578460bb01b521983e09ee2f39af528a1dc55 |
| +@legacy aa852aec334f46af0b4bb16f7f81afa3d4690f0f12c6c80b2ab5cff4837367aa internal/console/metricsview.go buildUnitRows legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-console-remote-instances;basis=Each unit row also keeps its raw per-sample readings (float32 CPU, int64 memory) so an owner's graph can be redrawn from only their samples; reads nothing new. file:ReadBytes@315,file:ReadBytes@327 e7f942ea8d32626b6ead3313deec26c458a7d7c296e7120c7384dfc5f416c378 |
| +@legacy b58f31b085d67e08a0f81ba95dd47114f9849e6986cb92a0a89a4234064ff4dc internal/console/server.go Server.channelHosts legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Canary-retire guard also counts the account's instance records (ListRecordsStrict under the lifetime judge, listRecordsStrict) and sidecar records (listed, then each read with GetSidecarRecord; any read error refuses) naming the channel; with none, it refuses unless the app has settled (retireUnsettled). The registry read is as on main. Fails closed. registry:App@424,registry:Channel@441,registry:Host@472,whole:Route@410 05c81080b1bd975c844e031830246881397e2b1864e1dc4a27bd425c77535d99 |
| +@legacy 9c63018a0c60a52c55b2ef0159bc58cbf0f191e0166a53adf58feff954c6935e internal/console/templates/app_overview.html external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-console-remote-instances;basis=Running tile does not claim Served when a route's state is unknown and reads the existing 'no data right now' when every instance's state is unknown; Web addresses tile reads 'no data right now' instead of 'DNS & certs OK' for a domain with no reading; display only. file:external@0 2a112ff768c300894881b858e61465841c87810ca7cb1d98a0fe2a54155a0ca1 |
| +@legacy 6a237934bdb53b917a4638b5661576e8efb1745631770a94fad3cfede96be2ce internal/console/apiinstances.go Server.instanceHealth legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Records with no local registry row get health only from remoteFacts (a box report whose rollout entry names the record's own account and app, generated after the record was created): awake is Running, held down is Failed, transient or unidentified is Can't tell right now. No metrics readings at all and no registry.Route literal for them. Local records unchanged. registry:Account@1987,registry:Account@2007,registry:App@1948,registry:App@1964,registry:Host@839,registry:Unit@2117,registry:Unit@2159,whole:Route@1151,whole:Route@2054,whole:Route@2075,whole:Route@2861,whole:Route@3852,whole:Route@3905,whole:Route@4020,whole:Route@792,whole:Route@821,whole:Route@832,whole:Route@850 3a82f379bbfbf600c1dae99bb28efc08cb6c431d7664f9eaa69f4e51dbf80fe7 |
| +@legacy f301b79b06b835ae75c9d6f13840e5bff6aa6a26838861e9dfd805e63c51a16d internal/console/view.go Assemble legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-perf-1;basis=takes the request context instead of context.Background() and wraps the registry List in a perf db span (perf.SpanContext); the same registry and store reads, no read added;rev3=census-ruling-console-remote-instances;basis=Collects the set of local registry hosts (rt.Host) so a record host the registry has gets no remote row (its record's created_at bounds the local row's metrics history); adds rows from the account's records and remoteFacts when given a remote source. registry:App@1755,registry:App@1778,registry:App@2156,registry:App@2186,registry:Backing@2056,registry:Caps@1424,registry:Channel@999,registry:Environment@1981,registry:Hibernate@1898,registry:Host@1807,registry:Host@900,registry:Kind@1822,registry:Platform@1928,registry:Provisioned@2081,registry:Status@1839,registry:Unit@2038,registry:Version@1862,whole:Route@2131,whole:Route@2206,whole:Route@849,whole:Route@878,whole:Route@949 8a6fb8bdabe0119484db99e47a1c5a5869fb94eae9f70ad83a56499cf5212ef2 |
| +internal/console/accountfleet.go Server.assembleAccountFleet legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Fleet tab: the shared-fleet app count also reads the account's own instance records (per app of the account, under its own prefix, region not a fleet placement); the registry read is unchanged. registry:Account@2350,registry:Account@4416,registry:App@2476,registry:Name@4809,registry:Region@2437,whole:Fleet@4001,whole:Fleet@4403,whole:Fleet@4517,whole:Route@2335 9e1c37cdfb0abb8bb0b864ed9fb5413c4b15e17f09b55d1d64760b83de0f8b64 |
| +internal/console/apiinstances.go Server.healthByHost legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Takes only the caller's ownership start per host (sinceByHost): readings only from samples at or after it, via ownerAppMetricsFrom. The awake set, the box pin and the until window are gone. Registry reads unchanged. registry:Backing@1178,registry:Hibernate@1112,registry:Kind@1095,registry:Provisioned@1153,registry:Status@972,registry:Unit@1169,registry:Unit@329,registry:Unit@364,whole:Route@177,whole:Route@220,whole:Route@286,whole:Route@949 cc4a0de52038d250031e4739b943a36f799e4cf7ae87a2b64312280861ba6a6e |
| +internal/console/apiroutes.go Server.handleAPIRoutes legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Passes nil for healthByHost's ownership-start argument; nothing else. registry:Account@4604,registry:App@1646,registry:App@2104,registry:App@4543,registry:Backing@2264,registry:Canary@2402,registry:Channel@2124,registry:Environment@2149,registry:Hibernate@2223,registry:Host@1730,registry:Host@2046,registry:Host@2202,registry:Host@2358,registry:Host@4676,registry:Host@4756,registry:Kind@2061,registry:Platform@2387,registry:Prefix@4772,registry:Provisioned@2289,registry:Replication@2321,registry:Status@2173,registry:Target@4790,registry:Unit@2243,whole:Route@1635,whole:Route@1684,whole:Route@1721,whole:Route@1741,whole:Route@1861,whole:Route@1963,whole:Route@1994,whole:Route@2094,whole:Route@4667,whole:RoutePath@3609 2fc5fde5477d298cc925ecf9d3b0fbb4cda8095bd7e22df76c2e114e716b5dea |
| +internal/console/claim_retire.go Server.retireClaimHostRecord legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-console-remote-instances;basis=Notes the app in the console's in-memory deletion log (noteRecordDeletion, which also invalidates the pages' held box reports) before retiring a record, for the canary-retire guard; the retire itself is unchanged. file:Read@941 3c30cfcad8f2edb3c38b7dd9e56697cd3e17ce3a7fa0e76eb815adf3dad7bd4d |
| +internal/console/instancepage.go Server.handleAppInstance legacy accepted-legacy accepted-legacy;rev3=merge-ruling-2;basis=Instance page adds updates view from rollout join; browser rendering remains legacy.;rev3=census-ruling-console-remote-instances;basis=A remote row (no local registry row) runs none of the hostname-keyed box joins (layout, rollout, updates): it shows only what its row brought through remoteFacts, aliases included. Local rows read layout, rollout join and ListAliases as before. file:Query@2895,registry:Account@2667,registry:Alias@2767,registry:App@2697,registry:Host@2645,whole:RouteAlias@2628 5208ae08d92c1022d7849e4ad50578460bb01b521983e09ee2f39af528a1dc55 |
| +internal/console/metricsview.go buildUnitRows legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-console-remote-instances;basis=Each unit row also keeps its raw per-sample readings (float32 CPU, int64 memory) so an owner's graph can be redrawn from only their samples; reads nothing new. file:ReadBytes@315,file:ReadBytes@327 e7f942ea8d32626b6ead3313deec26c458a7d7c296e7120c7384dfc5f416c378 |
| +internal/console/metricsview.go type UnitRow diagnostic H3 schema-only;rev3=census-ruling-console-remote-instances;basis=Two unexported fields carrying those raw per-sample readings; schema only. file:ReadBytes@133 db66030c5353fee88e0826786a424e0fee88d3191004deff380d00086bef5d62 |
| +internal/console/server.go Server.channelHosts legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Canary-retire guard also counts the account's instance records (ListRecordsStrict under the lifetime judge, listRecordsStrict) and sidecar records (listed, then each read with GetSidecarRecord; any read error refuses) naming the channel; with none, it refuses unless the app has settled (retireUnsettled). The registry read is as on main. Fails closed. registry:App@424,registry:Channel@441,registry:Host@472,whole:Route@410 05c81080b1bd975c844e031830246881397e2b1864e1dc4a27bd425c77535d99 |
| +internal/console/templates/app_overview.html external legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-console-remote-instances;basis=Running tile does not claim Served when a route's state is unknown and reads the existing 'no data right now' when every instance's state is unknown; Web addresses tile reads 'no data right now' instead of 'DNS & certs OK' for a domain with no reading; display only. file:external@0 2a112ff768c300894881b858e61465841c87810ca7cb1d98a0fe2a54155a0ca1 |
| +internal/console/apiinstances.go Server.instanceHealth legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-remote-instances;basis=Records with no local registry row get health only from remoteFacts (a box report whose rollout entry names the record's own account and app, generated after the record was created): awake is Running, held down is Failed, transient or unidentified is Can't tell right now. No metrics readings at all and no registry.Route literal for them. Local records unchanged. registry:Account@1987,registry:Account@2007,registry:App@1948,registry:App@1964,registry:Host@839,registry:Unit@2117,registry:Unit@2159,whole:Route@1151,whole:Route@2054,whole:Route@2075,whole:Route@2861,whole:Route@3852,whole:Route@3905,whole:Route@4020,whole:Route@792,whole:Route@821,whole:Route@832,whole:Route@850 3a82f379bbfbf600c1dae99bb28efc08cb6c431d7664f9eaa69f4e51dbf80fe7 |
| +internal/console/view.go Assemble legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-console-perf-1;basis=takes the request context instead of context.Background() and wraps the registry List in a perf db span (perf.SpanContext); the same registry and store reads, no read added;rev3=census-ruling-console-remote-instances;basis=Collects the set of local registry hosts (rt.Host) so a record host the registry has gets no remote row (its record's created_at bounds the local row's metrics history); adds rows from the account's records and remoteFacts when given a remote source. registry:App@1755,registry:App@1778,registry:App@2156,registry:App@2186,registry:Backing@2056,registry:Caps@1424,registry:Channel@999,registry:Environment@1981,registry:Hibernate@1898,registry:Host@1807,registry:Host@900,registry:Kind@1822,registry:Platform@1928,registry:Provisioned@2081,registry:Status@1839,registry:Unit@2038,registry:Version@1862,whole:Route@2131,whole:Route@2206,whole:Route@849,whole:Route@878,whole:Route@949 8a6fb8bdabe0119484db99e47a1c5a5869fb94eae9f70ad83a56499cf5212ef2 |
| +@coverage internal/console d0f4a85c40b71c18256bfcd9549c6153cdda6faa4ceaab102cf992b7726d9784 |
| +@coverage internal/console/templates 40529ebb7f9a5526fd20eb097ca83d9de884d3003f569d66939ee8a76996a46e |