carlos / platform Public

hosts-used status door and CLI (Task 4); Task 3 review P2 applied

Task 3: Astra round 1 READY AFTER FIXES (findings committed unedited). Its
one P2: the temporary-app exemption witness now creates the site's static
record through the instance door, as carlos deploy mints it, and asserts no
mark.

Task 4 (plan 2026-10-26-nearest-region-never-reuse, #404): GET
/api/cli/system/hosts-used/status (apiSystemRoller, read-only, closed to
service credentials) answers the mode, the marks counted by listing
control/hosts-used/, and the console's pending allocations and
retirements. inflight_creates and unfinished_moves stay null until the
activation window (Task 5) can count them. carlos system hosts-used status
prints them; its lines are drafts for merge B's copy review.

Census re-proposed for the branch (body changes to runSystem and
systemVerb; envelopes ., internal/console, internal/provision).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 15f0ba08ac69ef37a2e60b8d62fc35844ca3aba1 parent 780f343
13 files changed, +334 −7
  • docs/superpowers/notes/census-proposal-nearest-region-a.md +11 −1
  • docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md +12 −0
  • internal/console/authcli.go +3 −0
  • internal/console/claim_invariant_fixtures_test.go +1 −0
  • internal/console/claim_invariant_probes_read_test.go +2 −1
  • internal/console/hostsused.go +61 −0
  • internal/console/hostsused_writers_test.go +68 −0
  • internal/console/svcroutes_test.go +5 −2
  • internal/provision/nearest_region_a_census_test.go +4 −0
  • internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv +5 −2
  • system.go +7 −1
  • system_hostsused.go +98 −0
  • system_hostsused_test.go +57 −0

CI cancelled — superseded by a newer push — run details

diff --git a/docs/superpowers/notes/census-proposal-nearest-region-a.md b/docs/superpowers/notes/census-proposal-nearest-region-a.md
index ac9bca991..3f8bc5846 100644
--- a/docs/superpowers/notes/census-proposal-nearest-region-a.md
+++ b/docs/superpowers/notes/census-proposal-nearest-region-a.md
@@ -2,10 +2,20 @@
Ruling `census-ruling-nearest-region-a`. Every change below keeps the disposition it already has, so it needs an approval, not a decision.
-Envelopes re-pinned: `internal/console`, `internal/provision`.
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `system.go` `runSystem` | body | unchanged (0) | adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added |
+| `system.go` `systemVerb` | body | unchanged (0) | adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added |
+
+Envelopes re-pinned: `.`, `internal/console`, `internal/provision`.
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:
+
+- `system.go` `runSystem`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added
+- `system.go` `systemVerb`: authority, task B,C,D,F,G,J4. Basis: rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added
+
Seal: `d1e00cfb29d88b7a8e4998b641164e539067a6e1e9e4f52524255343c0c5f9f7` → `d1e00cfb29d88b7a8e4998b641164e539067a6e1e9e4f52524255343c0c5f9f7`.
Overlay: `internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md
new file mode 100644
index 000000000..2a22e3448
--- /dev/null
+++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-a-task3-r1.md
@@ -0,0 +1,12 @@
+No P1 findings.
+
+**P2 — Task 3: temporary-site exemption witness never creates a record.** At [hostsused_writers_test.go:400](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-a-review/internal/console/hostsused_writers_test.go:400), the subtest calls `createTemporary` and immediately checks `noMarks`. That helper only registers the temporary app; it does not create its static instance record.
+
+A regression that marks temporary-site records would therefore escape this subtest. Extend it to create the temporary app’s static platform-host record through the real instance door, assert that the record exists, then assert no marks—with lifetimes both off and on.
+
+Fault family: exemption witness coverage (brief checks 5 and 8).
+
+Targeted tests could not start because the read-only sandbox prevented Go from creating its build directory under `$TMPDIR`. `git diff --check` passed. No files changed; GOCACHE remained unset.
+
+**READY AFTER FIXES**
+
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index c0a6ba816..e848133d6 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -1066,6 +1066,9 @@ func (s *Server) registerCLIRoutes() {
// Pointer digests (#253, spec §4.6): each account's emission marker and
// the channels still without digests. apiSystemRoller, like the update
// doors.
+ // The hostname history's status (nearest-region never-reuse, plan Task
+ // 4, hostsused.go): apiSystemRoller, read-only.
+ s.cliRoute("GET /api/cli/system/hosts-used/status", svcrole.Set{}, s.handleAPIHostsUsedStatus)
s.cliRoute("GET /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests)
s.cliRoute("POST /api/cli/system/pointer-digests", svcrole.Set{}, s.handleAPISystemPointerDigests)
}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 41b56db35..664eb3e2f 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -873,6 +873,7 @@ var claimFixtures = map[string]claimFixture{
"route GET /api/cli/billing/problems": claimRead("operator view of billing problems; names no app"),
"route GET /api/cli/system/antivirus": claimRead("reads the deployment scanning setting"),
"route GET /api/cli/system/geoip": claimRead("operator view of the GeoIP pointer, box heartbeats and feed status (control/geoip/, status/, edge files); writes nothing"),
+ "route GET /api/cli/system/hosts-used/status": claimRead("operator view of the hostname history: its mode, a count of control/hosts-used/ marks and the console's pending lifetime rows; writes nothing"),
"route GET /api/cli/system/jobs/{id}": claimRead("reads a system update job"),
"route GET /api/cli/system/layout": claimRead("reads the deployment layout intent"),
"route GET /api/cli/system/pointer-digests": claimRead("operator report of each account's pointer digest marker and the channels whose head has no digest; writes nothing"),
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go
index 0b5be7c63..cfee421a0 100644
--- a/internal/console/claim_invariant_probes_read_test.go
+++ b/internal/console/claim_invariant_probes_read_test.go
@@ -278,7 +278,8 @@ var claimReadProbes = map[string]claimProbe{
do: claimGetAPI("/api/cli/system/jobs/<job>"),
body: []string{`"steps"`, `"done":true`},
},
- "route GET /api/cli/system/layout": claimAPIRead(nil, "/api/cli/system/layout", `"mode":"none"`),
+ "route GET /api/cli/system/hosts-used/status": claimAPIRead(nil, "/api/cli/system/hosts-used/status", `"mode":"incomplete"`),
+ "route GET /api/cli/system/layout": claimAPIRead(nil, "/api/cli/system/layout", `"mode":"none"`),
"route GET /api/cli/system/pointer-digests": claimAPIRead(nil, "/api/cli/system/pointer-digests",
`"account":"bab"`, `"app":"kass","channel":"stable"`),
"route GET /api/cli/system/status": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.systemRelease(t, "canary", "66587fa") },
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index feda7a20d..b3fd81990 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"os"
+ "strings"
"sync"
"time"
@@ -181,3 +182,63 @@ func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarR
}
return provision.CreateSidecarRecord(ctx, s.cfg.Releases, rec)
}
+
+// hostsUsedStatus is GET /api/cli/system/hosts-used/status (plan Task 4).
+// InflightCreates and UnfinishedMoves are null until the activation window
+// (Task 5) counts them: a zero there would claim a drain this console
+// cannot see yet.
+type hostsUsedStatus struct {
+ Mode string `json:"mode"`
+ Marks int `json:"marks"`
+ InflightCreates *int `json:"inflight_creates"`
+ PendingAllocations int `json:"pending_allocations"`
+ PendingRetirements int `json:"pending_retirements"`
+ UnfinishedMoves *int `json:"unfinished_moves"`
+}
+
+// handleAPIHostsUsedStatus answers the history's mode and how many
+// hostnames it holds, counted by listing the prefix (a page per 1,000
+// keys; an operator action, never polled), with the console's pending
+// lifetime rows. apiSystemRoller, like the other system doors. It writes
+// nothing.
+func (s *Server) handleAPIHostsUsedStatus(w http.ResponseWriter, r *http.Request) {
+ if _, _, ok := s.apiSystemRoller(w, r); !ok {
+ return
+ }
+ if !s.systemBucket(w) {
+ return
+ }
+ ctx := r.Context()
+ mode, err := s.hostsMode(ctx)
+ if err != nil {
+ log.Printf("console: hosts used status: read the mode: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the hostname history's mode. Try again.")
+ return
+ }
+ keys, err := s.cfg.Releases.List(ctx, provision.HostsUsedPrefix)
+ if err != nil {
+ log.Printf("console: hosts used status: list the marks: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not list the hostname history. Try again.")
+ return
+ }
+ out := hostsUsedStatus{Mode: mode}
+ for _, k := range keys {
+ if host, ok := strings.CutSuffix(strings.TrimPrefix(k, provision.HostsUsedPrefix), ".json"); ok && provision.HostsUsedKey(host) == k {
+ out.Marks++
+ }
+ }
+ allocs, err := s.store.PendingAllocations()
+ if err != nil {
+ log.Printf("console: hosts used status: pending allocations: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the console's pending creates. Try again.")
+ return
+ }
+ rets, err := s.store.PendingRetirements()
+ if err != nil {
+ log.Printf("console: hosts used status: pending retirements: %v", err)
+ jsonError(w, http.StatusBadGateway, "could not read the console's pending deletes. Try again.")
+ return
+ }
+ out.PendingAllocations, out.PendingRetirements = len(allocs), len(rets)
+ writeJSON(w, http.StatusOK, out)
+}
diff --git a/internal/console/hostsused_writers_test.go b/internal/console/hostsused_writers_test.go
index 2d4fdfcd0..2996de63e 100644
--- a/internal/console/hostsused_writers_test.go
+++ b/internal/console/hostsused_writers_test.go
@@ -401,9 +401,28 @@ func TestExemptCreatesDoNotMark(t *testing.T) {
fx, token := temporaryFixture(t)
c := markCase{fx: fx, bucket: wrapBucket(fx)}
on(t, c)
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
if code, out := createTemporary(t, fx, token, "tmp-docs", 0); code != http.StatusOK {
t.Fatalf("temporary create = %d %v", code, out)
}
+ // Its site's first record, as carlos deploy mints it
+ // (mintPlatformHost): instances enabled, then a static create
+ // of the app's platform host through the instance door.
+ code, _, out := rawReq(t, http.MethodPut, enableURL(fx, fx.sqid, "tmp-docs"), token, `{}`)
+ if code != http.StatusOK {
+ t.Fatalf("enable = %d %s", code, out)
+ }
+ var m provision.Manifest
+ if err := json.Unmarshal([]byte(out), &m); err != nil || m.Domain == "" {
+ t.Fatalf("enable answer %s: %v", out, err)
+ }
+ host := "tmp-docs." + m.Domain
+ if code, _, out := rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "tmp-docs"), token, `{"host":"`+host+`","kind":"static"}`); code != http.StatusCreated {
+ t.Fatalf("the temporary site's static create = %d %s", code, out)
+ }
+ if _, err := provision.GetRecord(context.Background(), c.bucket.Store, fx.sqid, "tmp-docs", host); err != nil {
+ t.Fatalf("the temporary site's record: %v", err)
+ }
noMarks(t, c.bucket.Store)
})
})
@@ -521,3 +540,52 @@ func exprName(e ast.Expr) string {
}
return ""
}
+
+// ---- Task 4: the status door ----------------------------------------------
+
+const hostsUsedStatusURL = "/api/cli/system/hosts-used/status"
+
+// TestHostsUsedStatusDoor: operators only (a member gets the family's 404),
+// the mode, and the marks counted by listing; the mode and floor objects are
+// not marks. The drain counts it cannot know before Task 5 are null.
+func TestHostsUsedStatusDoor(t *testing.T) {
+ l := newLifetimesFx(t)
+ get := func(token string) (int, map[string]any) {
+ t.Helper()
+ code, _, out := rawReq(t, http.MethodGet, l.fx.ts.URL+hostsUsedStatusURL, token, "")
+ var m map[string]any
+ _ = json.Unmarshal([]byte(out), &m)
+ return code, m
+ }
+ if code, _ := get(l.member); code != http.StatusNotFound {
+ t.Fatalf("a member's status = %d, want 404", code)
+ }
+ code, st := get(l.operator)
+ if code != http.StatusOK || st["mode"] != provision.HostsModeIncomplete || st["marks"] != float64(0) {
+ t.Fatalf("empty status = %d %v", code, st)
+ }
+ for _, k := range []string{"pending_allocations", "pending_retirements"} {
+ if st[k] != float64(0) {
+ t.Fatalf("%s = %v, want 0", k, st[k])
+ }
+ }
+ for _, k := range []string{"inflight_creates", "unfinished_moves"} {
+ if v, ok := st[k]; !ok || v != nil {
+ t.Fatalf("%s = %v (present %v), want null until the activation window exists", k, v, ok)
+ }
+ }
+ for _, host := range []string{"a.shop.example.com", "b.shop.example.com"} {
+ if code, out := (ltOn{lifetimesFx: l}).create(t, host); code != http.StatusCreated {
+ t.Fatalf("create %s = %d %s", host, code, out)
+ }
+ }
+ if _, err := provision.WriteHostsFloor(context.Background(), l.fx.rel, provision.HostsFloor{Version: "v0", Commit: "c"}, ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := provision.WriteHostsMode(context.Background(), l.fx.rel, provision.HostsModeIncomplete, ""); err != nil {
+ t.Fatal(err)
+ }
+ if code, st = get(l.operator); code != http.StatusOK || st["marks"] != float64(2) {
+ t.Fatalf("status after two creates = %d %v, want two marks", code, st)
+ }
+}
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 614416b39..50e655272 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -287,6 +287,9 @@ var closedDoors = []string{
// root-signed, the same cut as the update doors.
"GET /api/cli/system/pointer-digests",
"POST /api/cli/system/pointer-digests",
+ // The hostname history's status (nearest-region never-reuse): an
+ // operator's deployment-wide view, the same cut.
+ "GET /api/cli/system/hosts-used/status",
// `carlos channels resign`: the console signs digests a person has
// confirmed. A credential never confirms on a person's behalf.
"POST /api/cli/apps/{account}/{app}/channels/resign",
@@ -1096,8 +1099,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 64 {
- t.Errorf("walked %d closed doors, want all %d (and 64 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)",
+ if seen != len(closedDoors) || seen != 65 {
+ t.Errorf("walked %d closed doors, want all %d (and 65 today: instance-token, three door-key doors, the routes door, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, and two billing problem doors)",
seen, len(closedDoors))
}
}
diff --git a/internal/provision/nearest_region_a_census_test.go b/internal/provision/nearest_region_a_census_test.go
index 44f183ba4..fca8b1e30 100644
--- a/internal/provision/nearest_region_a_census_test.go
+++ b/internal/provision/nearest_region_a_census_test.go
@@ -26,6 +26,9 @@ package provision
// - Server.createRecordWithLifetimeLocked, re-pinned: it marks a data
// kind's hostname (markForCreate) before BeginAllocation. Same
// RecordKey site: still key-site.
+// - Server.registerCLIRoutes, re-pinned: it registers GET
+// /api/cli/system/hosts-used/status (plan Task 4), a read-only operator
+// door. Same "instances" and "sidecars" literals: still key-site.
func nearestRegionAWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), regionLabelsWriteCensusInventory()...)
for _, r := range []struct{ file, unit string }{
@@ -48,6 +51,7 @@ func nearestRegionAWriteCensusInventory() []censusEntry {
replacements := []censusEntry{
{"internal/console/hostsused.go", "Server.createRecordMarked", "record-writer", "key:CreateRecord,key:RecordKey", "a6f3c61d177171b3b1100ac178e0f84dd195eb9294aee117b64264c2a09be12d"},
{"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "3df0c9053fcd071af9a371cf70413ab9ed99dedc9d3bc0bd69b1821cb2ab2b3a"},
+ {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "3da979e75340f22f309cf585720df2f9191fa91b75f3225182b95e0fab0a4812"},
{"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "c3b601f16c8ceeb03f7a9512d9c079ad2eadb5414036beeeb032fd622b587a92"},
{"internal/provision/hostsused.go", "MarkHostUsed", "nonrecord", "sel:Put", "439f9ca1443f2c815f2ddb18b4732285d236d745fb660de66dc3a175b4532fd3"},
{"internal/provision/hostsused.go", "WriteHostsFloor", "nonrecord", "sel:Put", "c10e2e2fd57470c81785df3dddd9bb33013b416ce5381e74a9657811ec6b5c79"},
diff --git a/internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv b/internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv
index 33b1a9e7d..fe9c88f67 100644
--- a/internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv
+++ b/internal/provision/testdata/plan14-root-reads-nearest-region-a.tsv
@@ -1,4 +1,7 @@
# Census overlay nearest-region-a, written by census-propose (#369). census-ruling-nearest-region-a, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-nearest-region-a.md.
-# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-@coverage internal/console 4b52473b4974b697a8d9feab09f73e5cdb7fc6f16233b236c93ad6e80f8b7acf
+# 2 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+system.go runSystem authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops the claims case (host.RunSystemClaims, deleted); every other branch unchanged; no read added;rev3=census-ruling-nearest-region-a;basis=adds the hosts-used family to the system dispatch (carlos system hosts-used status, one GET of a console door as the operator); every existing command branch unchanged; no read added 1dd5600c0af83094659c370416afcfa86ba31aa533f2f64e7f61e0384907dc5f
+system.go systemVerb authority B,C,D,F,G,J4 rev3=census-ruling-self-serve-moves-1;identity=explicit operator CLI uid 0;basis=adds the lifetimes family to the system dispatch (carlos system lifetimes cutover, a console door call as the operator); every existing command branch unchanged;rev3=census-ruling-claims-cleanup-r2;basis=claims cleanup R2: drops "claims" from the verb list, so it now falls to the unknown-verb message; no read added;rev3=census-ruling-nearest-region-a;basis=adds "hosts-used" to the verb list, routed to runSystemHostsUsedVerb; no read added cc990ab40e7157fbc365e6dfccba81eec46a8df45d95df9b7ba41330dcdf8cca
+@coverage . e4e0ab4b7b1727f47360abeeb473e603f6e008a8ea8f31dea520be3239dfd136
+@coverage internal/console 2908be992a3684de8a0b5c0a637070e22938ab3d12928dd84b5075e734d60812
@coverage internal/provision 9f7572e1933c2dcb9d3faa27480a624c1d6581a6b76af72b2c356eb89b83a375
diff --git a/system.go b/system.go
index 8e9a6c9db..c00ce01a6 100644
--- a/system.go
+++ b/system.go
@@ -51,7 +51,7 @@ func systemVerb(args []string) (verb string, rest []string, component string) {
// untouched in rest for runSystemAntivirusVerb to read.
// layout is a family too: migrate|revert|status stay in rest for
// runSystemLayout.
- case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "box", "group", "install-channel", "join", "host-env", "db-worker", "help", "-h", "--help":
+ case "files", "guard-arm", "guard-exec", "journal-migrate", "floor-allows-prev", "update", "status", "rollback", "cancel-activation", "apply", "antivirus", "layout", "geoip", "seeds-floor", "legacy-routes", "lifetimes", "hosts-used", "box", "group", "install-channel", "join", "host-env", "db-worker", "help", "-h", "--help":
return args[0], args[1:], component
}
return "", args, component
@@ -94,6 +94,8 @@ func runSystem(args []string) {
runSystemLegacyRoutesVerb(rest)
case "lifetimes":
runSystemLifetimesVerb(rest)
+ case "hosts-used":
+ runSystemHostsUsedVerb(rest)
case "box":
runSystemBoxVerb(rest)
case "group":
@@ -146,6 +148,7 @@ func systemUsage() {
carlos system seeds-floor publish --min-release <release>
carlos system legacy-routes assign --name <name> --to <account>/<app>
carlos system lifetimes cutover [--no-wait]
+ carlos system hosts-used status
carlos system box role <box> <default|legacy|platform>
carlos system box publish-record
carlos system group role <region> <default|legacy>
@@ -169,6 +172,9 @@ The platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS):
lifetimes cutover [--no-wait]
switch a console without host claims onto instance lifetimes,
once, after the old console has stopped. Waits until they are on
+ hosts-used status
+ the hostname history: its mode, how many hostnames it has
+ recorded, and the instance creates and deletes still settling
box role <box> <default|legacy|platform>
whether new instances may be placed on a box. A legacy or
platform box keeps the instances it has and takes no new ones
diff --git a/system_hostsused.go b/system_hostsused.go
new file mode 100644
index 000000000..776862681
--- /dev/null
+++ b/system_hostsused.go
@@ -0,0 +1,98 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+)
+
+// carlos system hosts-used status (nearest-region never-reuse, plan Task 4):
+// the console's hostname history, its mode and how many hostnames it has
+// recorded, with the work still settling. Ops account owners and
+// CARLOS_SYSTEM_OPERATORS. It reads and never writes.
+
+const hostsUsedStatusDoor = "/api/cli/system/hosts-used/status"
+
+// hostsUsedStatusView is what the door answers. A nil count is one the
+// console does not report yet.
+type hostsUsedStatusView struct {
+ Mode string `json:"mode"`
+ Marks int `json:"marks"`
+ InflightCreates *int `json:"inflight_creates"`
+ PendingAllocations int `json:"pending_allocations"`
+ PendingRetirements int `json:"pending_retirements"`
+ UnfinishedMoves *int `json:"unfinished_moves"`
+}
+
+type roleGet func(ctx context.Context, path string) (int, []byte, error)
+
+func systemHostsUsedStatus(ctx context.Context, get roleGet) (hostsUsedStatusView, error) {
+ status, body, err := get(ctx, hostsUsedStatusDoor)
+ if err != nil {
+ return hostsUsedStatusView{}, err
+ }
+ if status != http.StatusOK {
+ return hostsUsedStatusView{}, apiErrorFromBody(status, body)
+ }
+ var st hostsUsedStatusView
+ if err := json.Unmarshal(body, &st); err != nil {
+ return hostsUsedStatusView{}, fmt.Errorf("unreadable response: %w", err)
+ }
+ return st, nil
+}
+
+// hostsUsedModeLine says what each mode means for a create. Drafts: the
+// copy review of these lines comes with merge B.
+func hostsUsedModeLine(mode string) string {
+ switch mode {
+ case "incomplete":
+ return "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet"
+ case "activating":
+ return "mode: activating. new instances, moves and placement changes are paused"
+ case "active":
+ return "mode: active. a hostname that has held data is never created again"
+ case "invalidated":
+ return "mode: invalidated. new instances are refused until a fresh inventory completes"
+ }
+ return "mode: " + mode
+}
+
+func printHostsUsedStatus(w io.Writer, st hostsUsedStatusView) {
+ fmt.Fprintln(w, hostsUsedModeLine(st.Mode))
+ fmt.Fprintf(w, "hostnames recorded: %d\n", st.Marks)
+ if st.InflightCreates != nil {
+ fmt.Fprintf(w, "create requests in progress: %d\n", *st.InflightCreates)
+ }
+ fmt.Fprintf(w, "instance creates still settling: %d\n", st.PendingAllocations)
+ fmt.Fprintf(w, "instance deletes still settling: %d\n", st.PendingRetirements)
+ if st.UnfinishedMoves != nil {
+ fmt.Fprintf(w, "moves not finished: %d\n", *st.UnfinishedMoves)
+ }
+}
+
+// runSystemHostsUsedVerb is `carlos system hosts-used status`.
+func runSystemHostsUsedVerb(rest []string) {
+ if len(rest) == 0 || rest[0] != "status" {
+ systemUsage()
+ os.Exit(2)
+ }
+ fs := flag.NewFlagSet("system hosts-used status", flag.ExitOnError)
+ consoleFlag := consoleOption(fs, "console origin (default: the only logged-in one)")
+ fs.Parse(rest[1:])
+ if fs.NArg() != 0 {
+ fs.Usage()
+ os.Exit(2)
+ }
+ sess := requireDeployAPISession(*consoleFlag)
+ printUsing(stdout, sess)
+ st, err := systemHostsUsedStatus(context.Background(), sess.getJSON)
+ if err != nil {
+ log.Fatalf("carlos system hosts-used status: %v", err)
+ }
+ printHostsUsedStatus(stdout, st)
+}
diff --git a/system_hostsused_test.go b/system_hostsused_test.go
new file mode 100644
index 000000000..e6fdb7a99
--- /dev/null
+++ b/system_hostsused_test.go
@@ -0,0 +1,57 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "testing"
+)
+
+// TestSystemHostsUsedStatusCLI: `carlos system hosts-used status` asks the
+// status door and prints one line per field the console knows.
+func TestSystemHostsUsedStatusCLI(t *testing.T) {
+ if verb, rest, _ := systemVerb([]string{"hosts-used", "status"}); verb != "hosts-used" || len(rest) != 1 || rest[0] != "status" {
+ t.Fatalf("systemVerb = %q %q", verb, rest)
+ }
+ var asked []string
+ get := func(body string, status int) func(context.Context, string) (int, []byte, error) {
+ return func(_ context.Context, path string) (int, []byte, error) {
+ asked = append(asked, path)
+ return status, []byte(body), nil
+ }
+ }
+ st, err := systemHostsUsedStatus(context.Background(), get(`{"mode":"incomplete","marks":12,"inflight_creates":null,"pending_allocations":1,"pending_retirements":0,"unfinished_moves":null}`, http.StatusOK))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(asked) != 1 || asked[0] != "/api/cli/system/hosts-used/status" {
+ t.Fatalf("asked %v", asked)
+ }
+ var out bytes.Buffer
+ printHostsUsedStatus(&out, st)
+ want := "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet\n" +
+ "hostnames recorded: 12\n" +
+ "instance creates still settling: 1\n" +
+ "instance deletes still settling: 0\n"
+ if out.String() != want {
+ t.Fatalf("output:\n%s\nwant:\n%s", out.String(), want)
+ }
+ st, err = systemHostsUsedStatus(context.Background(), get(`{"mode":"activating","marks":3,"inflight_creates":2,"pending_allocations":0,"pending_retirements":0,"unfinished_moves":1}`, http.StatusOK))
+ if err != nil {
+ t.Fatal(err)
+ }
+ out.Reset()
+ printHostsUsedStatus(&out, st)
+ want = "mode: activating. new instances, moves and placement changes are paused\n" +
+ "hostnames recorded: 3\n" +
+ "create requests in progress: 2\n" +
+ "instance creates still settling: 0\n" +
+ "instance deletes still settling: 0\n" +
+ "moves not finished: 1\n"
+ if out.String() != want {
+ t.Fatalf("output:\n%s\nwant:\n%s", out.String(), want)
+ }
+ if _, err := systemHostsUsedStatus(context.Background(), get(`{"error":"not found"}`, http.StatusNotFound)); err == nil {
+ t.Fatal("a refusal was not an error")
+ }
+}