Task 5 round 1 fixes; the inventory: import, close-fleet, complete (Task 6)
Task 5, Astra round 1 NOT READY (findings committed unedited): - P1 drain completeness: status and complete now also count records whose seed has not ended (a copy or an upload runs after its create returned), from record state, so it survives restarts (unfinished_seeds; the CLI folds it into "instance creates still settling"). - P1 mode agreement: any failed mode write drops the held state, so the next door reads the store (a timed-out write may have landed). - P2: begin, cancel and close-fleet answer the transition, without status's record scan. Task 6 (#404): begin fixes the roster (edges files' boxes, buckets and placement codes; the fleet table's fleets, buckets and boxes) and each fleet's targets. import maps adapter listings (JSON lines or an array) with provision.HostsFromBucketListing and HostsFromBoxListing and keeps them in the control bucket. close-fleet excuses a fleet's targets. complete refuses on any C6-C11 condition, then marks every hostname from the raw records, the lifetime tables and the listings, writes the floor and switches to active with the examined regions, fleets and pools. CLI: import <file>, close-fleet <fleet>, complete; status lines A10-A13. The root-read census has three new units awaiting the owner's decision (hostsRosterNow, Store.LifetimeHosts, readListingsFile); asked on #280.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+1,829
−40
docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r1.md+26 −0internal/console/authcli.go+4 −0internal/console/claim_invariant_fixtures_test.go+18 −0internal/console/hostsused.go+6 −5internal/console/hostsused_inventory.go+530 −0internal/console/hostsused_inventory_test.go+345 −0internal/console/hostsused_listings.go+105 −0internal/console/hostsused_store.go+26 −0internal/console/hostsused_window.go+94 −18internal/console/hostsused_window_test.go+87 −0internal/console/svcroutes_test.go+5 −2internal/console/testdata/claim-routes.txt+3 −0internal/provision/hostsused.go+3 −0internal/provision/hostsused_map.go+197 −0internal/provision/hostsused_map_test.go+133 −0internal/provision/nearest_region_b_census_test.go+17 −4system_hostsused.go+132 −11system_hostsused_test.go+98 −0
CI cancelled — superseded by a newer push — run details
diff --git a/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r1.md b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r1.md| new file mode 100644 |
| index 000000000..835afa202 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/reviews/ASTRA-FINDINGS-nearest-region-b-task5-r1.md |
| @@ -0,0 +1,26 @@ |
| +Reviewed `cfe8573a5d48a2733c44055aa5c7e6ccd398d451`, Task 5, round 1 of 3. |
| + |
| +1. **P1 — Detached seed/import work escapes the drain (§3a.2).** |
| + The create admission ends at handler return in [apiinstances.go:1713](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/apiinstances.go:1713), but `createFrom` launches a detached copy at [apiinstanceseed.go:244](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/apiinstanceseed.go:244). That copy subsequently uploads data and publishes the seed. Import uploads also continue asynchronously at [apiinstanceimport.go:460](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/apiinstanceimport.go:460). Status reads only `Move`, ignoring `Seed`, at [hostsused_window.go:110](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_window.go:110). |
| + |
| + **Failure:** pause a seed copy after its 202 response, then open the window. With its allocation committed and no move present, every drain count can be zero while the copy can still upload a snapshot and publish it. The operator can start scanning before admitted work finishes. |
| + |
| + **Fix:** retain accounting through detached workers’ last writes and include unfinished seed/import state across requests and restarts. Add blocked-copy and blocked-upload witnesses through the real doors. **Fault family:** drain completeness—zero must mean no admitted creation or movement remains. |
| + |
| +2. **P1 — An ambiguous mode write preserves a permissive cache (§3a, mode transitions).** |
| + [hostsused.go:125](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused.go:125) clears cached state only for `ErrCASConflict`. Other errors retain the previous mode. The S3 adapter propagates transport errors without establishing whether the write landed at [store.go:992](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/release/store.go:992). |
| + |
| + **Failure:** `begin` successfully stores `activating`, but its response is lost or the request times out. The console retains `incomplete`, continues admitting creates and moves, and reports the cached mode until another transition or restart. |
| + |
| + **Fix:** invalidate the cached state and ETag on every uncertain write failure; refuse admissions until a successful reread resolves the mode. Test a store that commits the write and then returns a timeout. **Fault family:** persisted/process mode agreement under ambiguous writes. |
| + |
| +3. **P2 — `begin` performs the status-only record scan (Task 5 request budget).** |
| + After committing `activating`, [hostsused_window.go:187](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_window.go:187) calls `writeHostsStatus`, which invokes `unfinishedMoves` at [hostsused_window.go:80](/home/paulca/amadan.net/carlos/platform/.claude/worktrees/nearest-region-b-review/internal/console/hostsused_window.go:80). |
| + |
| + **Failure:** opening maintenance performs an `apps/` listing and a GET per record. A failed record read returns 502 even though the window opened successfully; retrying then returns C2. |
| + |
| + **Fix:** return the transition result directly from `begin`/`cancel`; reserve the drain scan for `status`. **Fault family:** transition response reliability and status-only scan budget. |
| + |
| +No files changed. Formatting and diff checks passed. Targeted tests could not start because the read-only sandbox blocked Go’s work-directory creation. `GOCACHE` remained unset; no full suites ran. |
| + |
| +**NOT READY** |
| \ No newline at end of file |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index d0f55cdaa..3ed46f59d 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1077,6 +1077,10 @@ func (s *Server) registerCLIRoutes() { |
| // The activation window (hostsused_window.go): apiSystemRoller. |
| s.cliRoute("POST /api/cli/system/hosts-used/begin", svcrole.Set{}, s.handleAPIHostsUsedBegin) |
| s.cliRoute("POST /api/cli/system/hosts-used/cancel", svcrole.Set{}, s.handleAPIHostsUsedCancel) |
| + // The inventory (hostsused_inventory.go): apiSystemRoller, window open. |
| + s.cliRoute("POST /api/cli/system/hosts-used/import", svcrole.Set{}, s.handleAPIHostsUsedImport) |
| + s.cliRoute("POST /api/cli/system/hosts-used/close-fleet", svcrole.Set{}, s.handleAPIHostsUsedCloseFleet) |
| + s.cliRoute("POST /api/cli/system/hosts-used/complete", svcrole.Set{}, s.handleAPIHostsUsedComplete) |
| 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 c1be65413..cc4abeab6 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1579,6 +1579,24 @@ var claimFixtures = map[string]claimFixture{ |
| status: http.StatusConflict, |
| msg: msgHostsClaimsOn, |
| }}, |
| + "route POST /api/cli/system/hosts-used/import": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/import", ""), |
| + status: http.StatusConflict, |
| + msg: msgHostsClaimsOn, |
| + }}, |
| + "route POST /api/cli/system/hosts-used/close-fleet": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/close-fleet", ""), |
| + status: http.StatusConflict, |
| + msg: msgHostsClaimsOn, |
| + }}, |
| + "route POST /api/cli/system/hosts-used/complete": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/complete", ""), |
| + status: http.StatusConflict, |
| + msg: msgHostsClaimsOn, |
| + }}, |
| "route POST /api/cli/system/lifetimes/cutover": {refused: &claimRefusalFixture{ |
| apps: claimRefs("bab/titogo"), |
| do: claimRefusedAPI(http.MethodPost, "/api/cli/system/lifetimes/cutover", ""), |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index a597c6c04..6ee983e24 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -109,8 +109,8 @@ func (s *Server) LoadHostsMode(ctx context.Context) { |
| // hostsTransition changes the state under the lock: next sees the current |
| // state and answers the new one, or a refusal. The new state is written on |
| -// the ETag this process holds, then held. A conflict (another writer) drops |
| -// the held state, so the next caller reads the store again. |
| +// the ETag this process holds, then held. Any failed write drops the held |
| +// state, so the next caller reads the store again. |
| func (s *Server) hostsTransition(ctx context.Context, next func(cur provision.HostsState) (provision.HostsState, *doorRefusal)) (provision.HostsState, *doorRefusal, error) { |
| s.hosts.mu.Lock() |
| defer s.hosts.mu.Unlock() |
| @@ -124,9 +124,10 @@ func (s *Server) hostsTransition(ctx context.Context, next func(cur provision.Ho |
| st.At = time.Now().UTC() |
| etag, err := provision.WriteHostsState(ctx, s.cfg.Releases, st, s.hosts.etag) |
| if err != nil { |
| - if errors.Is(err, release.ErrCASConflict) { |
| - s.hosts.state, s.hosts.etag = provision.HostsState{}, "" |
| - } |
| + // A lost race, or a write whose outcome is unknown (a timeout may |
| + // have landed): the held state may be wrong either way, so it is |
| + // dropped and the next caller reads the store (Astra Task 5 r1). |
| + s.hosts.state, s.hosts.etag = provision.HostsState{}, "" |
| return provision.HostsState{}, nil, err |
| } |
| s.hosts.state, s.hosts.etag = st, etag |
diff --git a/internal/console/hostsused_inventory.go b/internal/console/hostsused_inventory.go| new file mode 100644 |
| index 000000000..0c3bec0ad |
| --- /dev/null |
| +++ b/internal/console/hostsused_inventory.go |
| @@ -0,0 +1,530 @@ |
| +package console |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "os" |
| + "runtime/debug" |
| + "slices" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/version" |
| +) |
| + |
| +// The inventory (nearest-region never-reuse, spec §3, plan Task 6). The |
| +// window's roster is fixed at begin: every box and data bucket that may hold |
| +// a hostname's data ("box:<box>", "bucket:<bucket>", the targets that need |
| +// listings) and every region and fleet a create can be placed in |
| +// ("region:<placement code>", "fleet:<name>"). An adapter outside the core |
| +// lists each target; import maps the listings to hostnames; complete |
| +// re-checks the drain and every source, marks every hostname found, writes |
| +// the floor and switches to active. |
| + |
| +// The approved strings (docs/superpowers/notes/copy/nearest-region-never-reuse-b.md). |
| +const ( |
| + msgHostsStillSettling = "Work is still settling. Run carlos system hosts-used status until every count is 0." // C6 |
| + msgHostsRosterChanged = "The regions, fleets or boxes changed since the window opened. Cancel it and begin again." // C10 |
| +) |
| + |
| +func msgHostsNotOnRoster(target string) string { // C4 |
| + return target + " was not on the list of targets when the window opened." |
| +} |
| + |
| +func msgHostsNotAFleet(name string) string { // C5 |
| + return name + " is not a fleet on the window's list. Regions and pools can't be closed." |
| +} |
| + |
| +func msgHostsNoListing(targets []string) string { // C7 |
| + return "No listing has been imported for " + strings.Join(targets, ", ") + "." |
| +} |
| + |
| +func msgHostsListingFailed(target string) string { // C8 |
| + return "The listing of " + target + " failed. Scan it again and import it." |
| +} |
| + |
| +func msgHostsListingUnmapped(target, entry string) string { // C9 |
| + return "The listing of " + target + " has entries with no hostname, such as " + entry + "." |
| +} |
| + |
| +// unmappedSample is how many unmapped entries a listing keeps. |
| +const unmappedSample = 20 |
| + |
| +// hostsRosterNow reads the roster as it is now: the edges files (all of |
| +// them, read and parsed, or an error) and the console's fleet table. It |
| +// also answers, for each fleet, the listing targets it owns (its boxes and |
| +// its bucket), which closing it excuses. |
| +func (s *Server) hostsRosterNow(ctx context.Context) ([]string, map[string][]string, error) { |
| + snap, err := readEdgesSnapshot(ctx, s.cfg.Releases) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("list the edges files: %w", err) |
| + } |
| + if !snap.Complete { |
| + return nil, nil, errors.New("an edges file could not be read or parsed") |
| + } |
| + var roster []string |
| + for _, f := range snap.Files { |
| + roster = append(roster, "box:"+f.Box, "region:"+f.Placement) |
| + if f.DataBucket != "" { |
| + roster = append(roster, "bucket:"+f.DataBucket) |
| + } |
| + } |
| + fleetTargets := map[string][]string{} |
| + if s.cfg.Registry != "" { |
| + reg, err := openRegistry(s.cfg.Registry) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("open the registry: %w", err) |
| + } |
| + fleets, err := reg.ListFleets() |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("list the fleets: %w", err) |
| + } |
| + for _, fl := range fleets { |
| + var owned []string |
| + if fl.Bucket != "" { |
| + owned = append(owned, "bucket:"+fl.Bucket) |
| + } |
| + boxes, err := reg.ListFleetBoxes(fl.Name) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("list fleet %s's boxes: %w", fl.Name, err) |
| + } |
| + for _, b := range boxes { |
| + if b.Status != "detached" { |
| + owned = append(owned, "box:fleet/"+fl.Name+"/"+b.Label) |
| + } |
| + } |
| + fleetTargets["fleet:"+fl.Name] = sortedUnique(owned) |
| + roster = append(roster, "fleet:"+fl.Name) |
| + roster = append(roster, owned...) |
| + } |
| + } |
| + return sortedUnique(roster), fleetTargets, nil |
| +} |
| + |
| +// closedTargets is every listing target the closed fleets excuse: their |
| +// boxes and buckets, as fixed when the window opened. |
| +func closedTargets(st provision.HostsState) map[string]bool { |
| + out := map[string]bool{} |
| + for _, c := range st.Closed { |
| + for _, t := range st.FleetTargets[c] { |
| + out[t] = true |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// listingTargets is the roster's targets that need a listing. |
| +func listingTargets(roster []string) []string { |
| + var out []string |
| + for _, t := range roster { |
| + if strings.HasPrefix(t, "box:") || strings.HasPrefix(t, "bucket:") { |
| + out = append(out, t) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// requireWindow is the inventory doors' common front: an operator, a |
| +// bucket, claims and Phase 1 off, and the window open. It answers the |
| +// window's state. |
| +func (s *Server) requireWindow(w http.ResponseWriter, r *http.Request) (provision.HostsState, string, bool) { |
| + addr, _, ok := s.apiSystemRoller(w, r) |
| + if !ok { |
| + return provision.HostsState{}, "", false |
| + } |
| + if !s.systemBucket(w) { |
| + return provision.HostsState{}, "", false |
| + } |
| + if s.cfg.HostClaim || s.cfg.MovesEnabled { |
| + jsonError(w, http.StatusConflict, msgHostsClaimsOn) |
| + return provision.HostsState{}, "", false |
| + } |
| + st, err := s.hostsState(r.Context()) |
| + if err != nil { |
| + log.Printf("console: hosts used: read the mode: %v", err) |
| + jsonError(w, http.StatusBadGateway, "could not read the hostname history's mode. Try again.") |
| + return provision.HostsState{}, "", false |
| + } |
| + if st.Mode != provision.HostsModeActivating { |
| + jsonError(w, http.StatusConflict, msgHostsNoWindow) |
| + return provision.HostsState{}, "", false |
| + } |
| + return st, addr, true |
| +} |
| + |
| +// hostsImportResult is one listing's answer. |
| +type hostsImportResult struct { |
| + Target string `json:"target"` |
| + OK bool `json:"ok"` |
| + Error string `json:"error,omitempty"` |
| + Hosts int `json:"hosts"` |
| + Unmapped int `json:"unmapped"` |
| + Sample []string `json:"sample,omitempty"` |
| +} |
| + |
| +// maxListingBody bounds an import: a box listing is a few lines per |
| +// instance, a bucket listing one line per object. |
| +const maxListingBody = 512 << 20 |
| + |
| +// handleAPIHostsUsedImport is POST /api/cli/system/hosts-used/import: the |
| +// adapter's listings, one provision.TargetListing JSON value per line. Every |
| +// target must be on the window's roster, or nothing is stored. A listing |
| +// replaces any earlier one of its target. |
| +func (s *Server) handleAPIHostsUsedImport(w http.ResponseWriter, r *http.Request) { |
| + st, addr, ok := s.requireWindow(w, r) |
| + if !ok { |
| + return |
| + } |
| + onRoster := map[string]bool{} |
| + for _, t := range st.Roster { |
| + onRoster[t] = true |
| + } |
| + // JSON lines as the adapter writes them, or one JSON array of the same |
| + // values (carlos system hosts-used import). |
| + br := bufio.NewReader(http.MaxBytesReader(w, r.Body, maxListingBody)) |
| + var listings []provision.TargetListing |
| + var decoded []provision.TargetListing |
| + if first, err := peekNonSpace(br); err == nil && first == '[' { |
| + if err := json.NewDecoder(br).Decode(&decoded); err != nil { |
| + jsonError(w, http.StatusBadRequest, "could not read the listings: "+err.Error()) |
| + return |
| + } |
| + } else { |
| + dec := json.NewDecoder(br) |
| + for { |
| + var l provision.TargetListing |
| + err := dec.Decode(&l) |
| + if errors.Is(err, io.EOF) { |
| + break |
| + } |
| + if err != nil { |
| + jsonError(w, http.StatusBadRequest, "could not read the listings: "+err.Error()) |
| + return |
| + } |
| + decoded = append(decoded, l) |
| + } |
| + } |
| + for _, l := range decoded { |
| + if l.Kind != "box" && l.Kind != "bucket" { |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf("could not read the listings: %s has kind %q, want box or bucket", l.Target, l.Kind)) |
| + return |
| + } |
| + if target := l.Kind + ":" + l.Target; !onRoster[target] { |
| + jsonError(w, http.StatusConflict, msgHostsNotOnRoster(target)) |
| + return |
| + } |
| + listings = append(listings, l) |
| + } |
| + results := make([]hostsImportResult, 0, len(listings)) |
| + now := time.Now().Unix() |
| + for _, l := range listings { |
| + row := hostsListing{Target: l.Kind + ":" + l.Target, OK: l.OK, Error: l.Error, ImportedAt: now} |
| + if l.OK { |
| + var unmapped []string |
| + if l.Kind == "bucket" { |
| + row.Hosts, unmapped = provision.HostsFromBucketListing(l.Prefix, l.Entries) |
| + } else { |
| + row.Hosts, unmapped = provision.HostsFromBoxListing(l.Entries) |
| + } |
| + row.UnmappedCount = len(unmapped) |
| + if len(unmapped) > unmappedSample { |
| + unmapped = unmapped[:unmappedSample] |
| + } |
| + row.Unmapped = unmapped |
| + } |
| + if err := s.putHostsListing(r.Context(), row); err != nil { |
| + log.Printf("console: hosts used import: store %s: %v", row.Target, err) |
| + jsonError(w, http.StatusBadGateway, "could not store the listing of "+row.Target+". Try again.") |
| + return |
| + } |
| + results = append(results, hostsImportResult{Target: row.Target, OK: row.OK, Error: row.Error, |
| + Hosts: len(row.Hosts), Unmapped: row.UnmappedCount, Sample: row.Unmapped}) |
| + } |
| + log.Printf("console: hosts used: %s imported %d listing(s)", addr, len(results)) |
| + writeJSON(w, http.StatusOK, map[string]any{"results": results}) |
| +} |
| + |
| +// handleAPIHostsUsedCloseFleet is POST /api/cli/system/hosts-used/close-fleet: |
| +// a fleet on the roster that will not be scanned. Once active it takes no |
| +// data-kind create (S4). Regions cannot be closed. |
| +// peekNonSpace is the first byte that is not JSON whitespace, unread. |
| +func peekNonSpace(br *bufio.Reader) (byte, error) { |
| + for { |
| + b, err := br.Peek(1) |
| + if err != nil { |
| + return 0, err |
| + } |
| + switch b[0] { |
| + case ' ', '\t', '\r', '\n': |
| + if _, err := br.ReadByte(); err != nil { |
| + return 0, err |
| + } |
| + continue |
| + } |
| + return b[0], nil |
| + } |
| +} |
| + |
| +func (s *Server) handleAPIHostsUsedCloseFleet(w http.ResponseWriter, r *http.Request) { |
| + if _, _, ok := s.requireWindow(w, r); !ok { |
| + return |
| + } |
| + var req struct { |
| + Fleet string `json:"fleet"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + name := strings.TrimSpace(req.Fleet) |
| + next, ref, err := s.hostsTransition(r.Context(), func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| + if cur.Mode != provision.HostsModeActivating { |
| + return cur, &doorRefusal{http.StatusConflict, msgHostsNoWindow} |
| + } |
| + if !slices.Contains(cur.Roster, "fleet:"+name) { |
| + return cur, &doorRefusal{http.StatusConflict, msgHostsNotAFleet(name)} |
| + } |
| + next := cur |
| + if !slices.Contains(next.Closed, "fleet:"+name) { |
| + next.Closed = append(append([]string(nil), cur.Closed...), "fleet:"+name) |
| + sort.Strings(next.Closed) |
| + } |
| + return next, nil |
| + }) |
| + switch { |
| + case err != nil: |
| + hostsWriteFailed(w, "close-fleet", err) |
| + return |
| + case ref != nil: |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, hostsStateAnswer(next)) |
| +} |
| + |
| +// hostsSources is what complete found: each hostname with the first source |
| +// that named it, and the pools the records use. |
| +type hostsSources struct { |
| + hosts map[string]string |
| + pools map[string]bool |
| +} |
| + |
| +func (h hostsSources) add(host, source string) { |
| + if _, ok := h.hosts[host]; !ok { |
| + h.hosts[host] = source |
| + } |
| +} |
| + |
| +// recordSources is source 1 (spec §3): every raw key under apps/, whatever |
| +// its app, account or body. A body that decodes to an exempt kind is |
| +// skipped; an instance key's hostname is in the key, so an undecodable body |
| +// is still marked. A sidecar key names the sidecar, not its host, so one |
| +// whose body does not decode is unmapped. |
| +func (s *Server) recordSources(ctx context.Context, src hostsSources) (unmapped string, err error) { |
| + keys, err := s.cfg.Releases.List(ctx, "apps/") |
| + if err != nil { |
| + return "", err |
| + } |
| + for _, k := range keys { |
| + if !provision.IsRecordKey(k) { |
| + continue |
| + } |
| + raw, _, err := s.cfg.Releases.Get(ctx, k) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + return "", err |
| + } |
| + segs := strings.Split(k, "/") |
| + var body struct { |
| + Kind string `json:"kind"` |
| + Host string `json:"host"` |
| + Pool string `json:"pool"` |
| + } |
| + derr := json.Unmarshal(raw, &body) |
| + if segs[3] == "sidecars" { |
| + if derr != nil || !provision.ValidHostShape(body.Host) { |
| + return k, nil |
| + } |
| + src.add(body.Host, "records") |
| + continue |
| + } |
| + host := strings.TrimSuffix(segs[4], ".json") |
| + if derr == nil && (body.Kind == "static" || body.Kind == "service") { |
| + continue |
| + } |
| + if !provision.ValidHostShape(host) { |
| + return k, nil |
| + } |
| + src.add(host, "records") |
| + if derr == nil && body.Pool != "" { |
| + src.pools[body.Pool] = true |
| + } |
| + } |
| + return "", nil |
| +} |
| + |
| +// floorNow is this build: its version and, when the build carries it, its |
| +// commit. |
| +func floorNow() provision.HostsFloor { |
| + f := provision.HostsFloor{Version: version.Build} |
| + if bi, ok := debug.ReadBuildInfo(); ok { |
| + for _, kv := range bi.Settings { |
| + if kv.Key == "vcs.revision" { |
| + f.Commit = kv.Value |
| + } |
| + } |
| + } |
| + return f |
| +} |
| + |
| +// handleAPIHostsUsedComplete is POST /api/cli/system/hosts-used/complete. |
| +// It refuses while anything is unsettled (C6), the roster has changed |
| +// (C10), a target has no listing (C7), a listing failed (C8) or has |
| +// unmapped entries (C9), or claims or Phase 1 are on (C11). Otherwise it |
| +// marks every hostname the sources name, writes the floor, and switches to |
| +// active with the examined regions and fleets. |
| +func (s *Server) handleAPIHostsUsedComplete(w http.ResponseWriter, r *http.Request) { |
| + st, addr, ok := s.requireWindow(w, r) |
| + if !ok { |
| + return |
| + } |
| + ctx := r.Context() |
| + fail := func(what string, err error) { |
| + log.Printf("console: hosts used complete: %s: %v", what, err) |
| + jsonError(w, http.StatusBadGateway, "could not complete the hostname history: "+what+". Try again.") |
| + } |
| + // The drain, as status reads it. |
| + status, sf := s.hostsStatus(ctx) |
| + if sf != nil { |
| + fail("read the status", sf.err) |
| + return |
| + } |
| + if *status.InflightCreates != 0 || status.PendingAllocations != 0 || status.PendingRetirements != 0 || |
| + status.UnfinishedMoves == nil || *status.UnfinishedMoves != 0 || |
| + status.UnfinishedSeeds == nil || *status.UnfinishedSeeds != 0 { |
| + jsonError(w, http.StatusConflict, msgHostsStillSettling) |
| + return |
| + } |
| + roster, _, err := s.hostsRosterNow(ctx) |
| + if err != nil { |
| + fail("read the roster", err) |
| + return |
| + } |
| + if strings.Join(roster, "\n") != strings.Join(st.Roster, "\n") { |
| + jsonError(w, http.StatusConflict, msgHostsRosterChanged) |
| + return |
| + } |
| + closed := closedTargets(st) |
| + listings, err := s.hostsListings(ctx) |
| + if err != nil { |
| + fail("read the listings", err) |
| + return |
| + } |
| + var missing []string |
| + for _, t := range listingTargets(st.Roster) { |
| + if closed[t] { |
| + continue |
| + } |
| + l, ok := listings[t] |
| + switch { |
| + case !ok: |
| + missing = append(missing, t) |
| + case !l.OK: |
| + jsonError(w, http.StatusConflict, msgHostsListingFailed(t)) |
| + return |
| + case l.UnmappedCount > 0: |
| + jsonError(w, http.StatusConflict, msgHostsListingUnmapped(t, l.Unmapped[0])) |
| + return |
| + } |
| + } |
| + if len(missing) > 0 { |
| + jsonError(w, http.StatusConflict, msgHostsNoListing(missing)) |
| + return |
| + } |
| + src := hostsSources{hosts: map[string]string{}, pools: map[string]bool{}} |
| + unmapped, err := s.recordSources(ctx, src) |
| + if err != nil { |
| + fail("read the records", err) |
| + return |
| + } |
| + if unmapped != "" { |
| + jsonError(w, http.StatusConflict, msgHostsListingUnmapped("records", unmapped)) |
| + return |
| + } |
| + tableHosts, err := s.store.LifetimeHosts() |
| + if err != nil { |
| + fail("read the lifetime tables", err) |
| + return |
| + } |
| + for _, h := range tableHosts { |
| + if !provision.ValidHostShape(h) { |
| + jsonError(w, http.StatusConflict, msgHostsListingUnmapped("tables", h)) |
| + return |
| + } |
| + src.add(h, "tables") |
| + } |
| + for _, t := range listingTargets(st.Roster) { |
| + if l, ok := listings[t]; ok && !closed[t] { |
| + for _, h := range l.Hosts { |
| + src.add(h, t) |
| + } |
| + } |
| + } |
| + hosts := make([]string, 0, len(src.hosts)) |
| + for h := range src.hosts { |
| + hosts = append(hosts, h) |
| + } |
| + sort.Strings(hosts) |
| + now := time.Now().UTC() |
| + for _, h := range hosts { |
| + if _, err := provision.MarkHostUsed(ctx, s.cfg.Releases, provision.HostUse{Host: h, Kind: "inventory", Source: src.hosts[h], At: now}); err != nil { |
| + fail("mark "+h, err) |
| + return |
| + } |
| + } |
| + floor := floorNow() |
| + _, floorETag, err := provision.ReadHostsFloor(ctx, s.cfg.Releases) |
| + if err != nil { |
| + fail("read the floor", err) |
| + return |
| + } |
| + if _, err := provision.WriteHostsFloor(ctx, s.cfg.Releases, floor, floorETag); err != nil { |
| + fail("write the floor", err) |
| + return |
| + } |
| + var examined []string |
| + for _, t := range st.Roster { |
| + if (strings.HasPrefix(t, "region:") || strings.HasPrefix(t, "fleet:")) && !slices.Contains(st.Closed, t) { |
| + examined = append(examined, t) |
| + } |
| + } |
| + for p := range src.pools { |
| + examined = append(examined, "pool:"+p) |
| + } |
| + sort.Strings(examined) |
| + _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| + if cur.Mode != provision.HostsModeActivating { |
| + return cur, &doorRefusal{http.StatusConflict, msgHostsNoWindow} |
| + } |
| + return provision.HostsState{Mode: provision.HostsModeActive, Examined: examined, Closed: cur.Closed}, nil |
| + }) |
| + switch { |
| + case err != nil: |
| + hostsWriteFailed(w, "complete", err) |
| + return |
| + case ref != nil: |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + log.Printf("console: hosts used: %s completed the hostname history: %d hostname(s) from the inventory, floor %s %s", addr, len(hosts), floor.Version, floor.Commit) |
| + s.writeHostsStatus(w, ctx) |
| +} |
diff --git a/internal/console/hostsused_inventory_test.go b/internal/console/hostsused_inventory_test.go| new file mode 100644 |
| index 000000000..58a0da3aa |
| --- /dev/null |
| +++ b/internal/console/hostsused_inventory_test.go |
| @@ -0,0 +1,345 @@ |
| +package console |
| + |
| +// The inventory: import, close-fleet and complete (nearest-region never-reuse |
| +// plan, Task 6; spec §3 and §3a). Through the real doors, over a console with |
| +// one box (b1, placement ie, data bucket data-ie) in its edges files. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +const ( |
| + hostsUsedImportURL = "/api/cli/system/hosts-used/import" |
| + hostsUsedCloseFleetURL = "/api/cli/system/hosts-used/close-fleet" |
| + hostsUsedCompleteURL = "/api/cli/system/hosts-used/complete" |
| +) |
| + |
| +// putHostsEdges publishes one box's edges file. |
| +func putHostsEdges(t *testing.T, st release.Store, box, placement, bucket string) { |
| + t.Helper() |
| + body := `{"v":1,"box":"` + box + `","eip":"192.0.2.1","region":"eu-west-1","placement":"` + placement + `","data_bucket":"` + bucket + `","hosts":{}}` |
| + if _, err := st.Put(context.Background(), "control/edges/"+box+".json", []byte(body), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func invFx(t *testing.T) lifetimesFx { |
| + t.Helper() |
| + l := newLifetimesFx(t) |
| + putHostsEdges(t, l.fx.rel, "b1", "ie", "data-ie") |
| + return l |
| +} |
| + |
| +func listingLine(t *testing.T, l provision.TargetListing) string { |
| + t.Helper() |
| + if l.Entries == nil { |
| + l.Entries = []string{} |
| + } |
| + b, err := json.Marshal(l) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(b) |
| +} |
| + |
| +func importLines(t *testing.T, l lifetimesFx, lines ...string) (int, map[string]any) { |
| + t.Helper() |
| + return hostsDoor(t, l.fx, http.MethodPost, hostsUsedImportURL, l.operator, strings.Join(lines, "\n")+"\n") |
| +} |
| + |
| +// cleanImport imports a good listing for b1 and data-ie with these entries. |
| +func cleanImport(t *testing.T, l lifetimesFx, boxEntries, bucketEntries []string) { |
| + t.Helper() |
| + code, out := importLines(t, l, |
| + listingLine(t, provision.TargetListing{Target: "b1", Kind: "box", OK: true, Entries: boxEntries}), |
| + listingLine(t, provision.TargetListing{Target: "data-ie", Kind: "bucket", Prefix: "instances", OK: true, Entries: bucketEntries})) |
| + if code != http.StatusOK { |
| + t.Fatalf("import = %d %v", code, out) |
| + } |
| +} |
| + |
| +func complete(t *testing.T, l lifetimesFx) (int, map[string]any) { |
| + t.Helper() |
| + return hostsDoor(t, l.fx, http.MethodPost, hostsUsedCompleteURL, l.operator, `{}`) |
| +} |
| + |
| +func mustComplete(t *testing.T, l lifetimesFx) map[string]any { |
| + t.Helper() |
| + code, out := complete(t, l) |
| + if code != http.StatusOK || out["mode"] != provision.HostsModeActive { |
| + t.Fatalf("complete = %d %v", code, out) |
| + } |
| + return out |
| +} |
| + |
| +func marked(t *testing.T, st release.Store, host string) bool { |
| + t.Helper() |
| + used, err := provision.HostIsUsed(context.Background(), st, host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return used |
| +} |
| + |
| +func TestInventoryDoorsNeedAWindow(t *testing.T) { |
| + l := invFx(t) |
| + if code, out := importLines(t, l, listingLine(t, provision.TargetListing{Target: "b1", Kind: "box", OK: true})); code != http.StatusConflict || out["error"] != msgHostsNoWindow { |
| + t.Fatalf("import with no window = %d %v", code, out) |
| + } |
| + if code, out := complete(t, l); code != http.StatusConflict || out["error"] != msgHostsNoWindow { |
| + t.Fatalf("complete with no window = %d %v", code, out) |
| + } |
| + if code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCloseFleetURL, l.operator, `{"fleet":"f"}`); code != http.StatusConflict || out["error"] != msgHostsNoWindow { |
| + t.Fatalf("close-fleet with no window = %d %v", code, out) |
| + } |
| + for _, path := range []string{hostsUsedImportURL, hostsUsedCompleteURL, hostsUsedCloseFleetURL} { |
| + if code, _ := hostsDoor(t, l.fx, http.MethodPost, path, l.member, `{}`); code != http.StatusNotFound { |
| + t.Fatalf("a member's %s = %d, want 404", path, code) |
| + } |
| + } |
| +} |
| + |
| +func TestImportRefusesATargetOffTheRoster(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + code, out := importLines(t, l, listingLine(t, provision.TargetListing{Target: "b9", Kind: "box", OK: true})) |
| + if code != http.StatusConflict || out["error"] != "box:b9 was not on the list of targets when the window opened." { |
| + t.Fatalf("import of an unknown box = %d %v, want C4", code, out) |
| + } |
| +} |
| + |
| +func TestHistoricalOnlyNameAllowed(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + cleanImport(t, l, []string{"registry.db"}, nil) |
| + out := mustComplete(t, l) |
| + if out["marks"] != float64(0) { |
| + t.Fatalf("marks = %v, want none", out["marks"]) |
| + } |
| + if code, body := createAs(t, l, `{"host":"fresh.shop.example.com"}`); code != http.StatusCreated { |
| + t.Fatalf("a name with no data anywhere = %d %s, want 201", code, body) |
| + } |
| + st, _, err := provision.ReadHostsState(context.Background(), l.fx.rel) |
| + if err != nil || st.Mode != provision.HostsModeActive || !contains(st.Examined, "region:ie") { |
| + t.Fatalf("state = %+v %v, want active with region:ie examined", st, err) |
| + } |
| + if f, _, err := provision.ReadHostsFloor(context.Background(), l.fx.rel); err != nil || f == nil || f.Version == "" { |
| + t.Fatalf("floor = %+v %v, want written", f, err) |
| + } |
| +} |
| + |
| +func TestLocalOnlyLeftoverRefused(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + cleanImport(t, l, []string{"local.shop.example.com.db", "instances/nested.shop.example.com/nested.shop.example.com.db"}, nil) |
| + mustComplete(t, l) |
| + for _, host := range []string{"local.shop.example.com", "nested.shop.example.com"} { |
| + if code, body := createAs(t, l, `{"host":"`+host+`"}`); code != http.StatusConflict || ltErr(body) != msgHostUsed(host) { |
| + t.Fatalf("create of %s with box data = %d %s, want 409 S1", host, code, body) |
| + } |
| + } |
| +} |
| + |
| +func TestInventoryMarksOrphanSeedSnapshot(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + cleanImport(t, l, nil, []string{"seeds/orphan.shop.example.com/sd_1/snapshot.db", "instances/bucket.shop.example.com/0000/x.ltx", "moves/@lanes/uk/x"}) |
| + mustComplete(t, l) |
| + for _, host := range []string{"orphan.shop.example.com", "bucket.shop.example.com"} { |
| + if !marked(t, l.fx.rel, host) { |
| + t.Fatalf("%s is not marked", host) |
| + } |
| + } |
| +} |
| + |
| +// TestInventoryMarksRawRecordKeys: source 1 reads raw record keys, whatever |
| +// their app, account or body; only a body that decodes to an exempt kind |
| +// is skipped. |
| +func TestInventoryMarksRawRecordKeys(t *testing.T) { |
| + l := invFx(t) |
| + ctx := context.Background() |
| + put := func(key, body string) { |
| + t.Helper() |
| + if _, err := l.fx.rel.Put(ctx, key, []byte(body), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + rec := func(acct, app, host, kind string) string { |
| + b, _ := json.Marshal(provision.Record{Schema: 1, Host: host, App: app, Account: acct, Channel: "stable", Kind: kind, CreatedAt: time.Now().UTC()}) |
| + return string(b) |
| + } |
| + put(provision.RecordKey("bab", "trashed", "t.example.com"), rec("bab", "trashed", "t.example.com", "")) |
| + put(provision.RecordKey("zzz", "gone", "o.example.com"), rec("zzz", "gone", "o.example.com", "")) |
| + put(provision.RecordKey("bab", ltApp, "m.shop.example.com"), "{not json") |
| + put(provision.RecordKey("bab", ltApp, "s.shop.example.com"), rec("bab", ltApp, "s.shop.example.com", "static")) |
| + put(provision.RecordKey("bab", ltApp, "v.shop.example.com"), rec("bab", ltApp, "v.shop.example.com", "service")) |
| + sc, _ := json.Marshal(provision.SidecarRecord{Schema: 1, Name: "bot", Host: "bot.shop.bab.sidecar.internal", App: ltApp, Account: "bab", Channel: "stable", CreatedAt: time.Now().UTC()}) |
| + put(provision.SidecarRecordKey("bab", ltApp, "bot"), string(sc)) |
| + begin(t, l) |
| + cleanImport(t, l, nil, nil) |
| + mustComplete(t, l) |
| + for host, want := range map[string]bool{ |
| + "t.example.com": true, "o.example.com": true, "m.shop.example.com": true, "bot.shop.bab.sidecar.internal": true, |
| + "s.shop.example.com": false, "v.shop.example.com": false, |
| + } { |
| + if got := marked(t, l.fx.rel, host); got != want { |
| + t.Errorf("%s marked = %v, want %v", host, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestCompleteRefusesUndecodableSidecar(t *testing.T) { |
| + l := invFx(t) |
| + if _, err := l.fx.rel.Put(context.Background(), provision.SidecarRecordKey("bab", ltApp, "bot"), []byte("{not json"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + begin(t, l) |
| + cleanImport(t, l, nil, nil) |
| + code, out := complete(t, l) |
| + if code != http.StatusConflict || !strings.HasPrefix(str(t, out, "error"), "The listing of records has entries with no hostname, such as apps/bab/shop/sidecars/bot.json") { |
| + t.Fatalf("complete over an undecodable sidecar = %d %v, want C9", code, out) |
| + } |
| +} |
| + |
| +func TestCompleteRefusesMissingListing(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + code, out := importLines(t, l, listingLine(t, provision.TargetListing{Target: "b1", Kind: "box", OK: true})) |
| + if code != http.StatusOK { |
| + t.Fatalf("import = %d %v", code, out) |
| + } |
| + if code, out := complete(t, l); code != http.StatusConflict || out["error"] != "No listing has been imported for bucket:data-ie." { |
| + t.Fatalf("complete without the bucket = %d %v, want C7", code, out) |
| + } |
| + if st := statusOf(t, l); st["listings"] != float64(1) || st["targets"] != float64(2) || !contains(strs(st["not_imported"]), "bucket:data-ie") { |
| + t.Fatalf("status = %v", st) |
| + } |
| +} |
| + |
| +func TestCompleteRefusesFailedSource(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + code, out := importLines(t, l, |
| + listingLine(t, provision.TargetListing{Target: "b1", Kind: "box", OK: false, Error: "ssm: timed out"}), |
| + listingLine(t, provision.TargetListing{Target: "data-ie", Kind: "bucket", Prefix: "instances", OK: true})) |
| + if code != http.StatusOK { |
| + t.Fatalf("import = %d %v", code, out) |
| + } |
| + if code, out := complete(t, l); code != http.StatusConflict || out["error"] != "The listing of box:b1 failed. Scan it again and import it." { |
| + t.Fatalf("complete with a failed listing = %d %v, want C8", code, out) |
| + } |
| +} |
| + |
| +func TestCompleteRefusesUnmappable(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + cleanImport(t, l, []string{".offline-moves/Bad.Host/x"}, nil) |
| + if code, out := complete(t, l); code != http.StatusConflict || out["error"] != "The listing of box:b1 has entries with no hostname, such as .offline-moves/Bad.Host." { |
| + t.Fatalf("complete with an unmapped entry = %d %v, want C9", code, out) |
| + } |
| +} |
| + |
| +func TestCompleteRefusesRosterChange(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + putHostsEdges(t, l.fx.rel, "b2", "uk", "data-uk") |
| + cleanImport(t, l, nil, nil) |
| + if code, out := complete(t, l); code != http.StatusConflict || out["error"] != msgHostsRosterChanged { |
| + t.Fatalf("complete after a roster change = %d %v, want C10", code, out) |
| + } |
| +} |
| + |
| +func TestCompleteRefusesClaimsOrPhase1(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + cleanImport(t, l, nil, nil) |
| + l.fx.srv.cfg.MovesEnabled = true |
| + if code, out := complete(t, l); code != http.StatusConflict || out["error"] != msgHostsClaimsOn { |
| + t.Fatalf("complete with Phase 1 on = %d %v, want C11", code, out) |
| + } |
| + l.fx.srv.cfg.MovesEnabled = false |
| + mustComplete(t, l) |
| +} |
| + |
| +// TestCompleteRefusesPendingAllocationAnyVersion (Astra round 3 on the |
| +// spec): a marked allocation whose record write failed holds complete until |
| +// recovery ends it, even when the scan finds its host's data. |
| +func TestCompleteRefusesPendingAllocationAnyVersion(t *testing.T) { |
| + lt := newLtOn(t) |
| + putHostsEdges(t, lt.fx.rel, "b1", "ie", "data-ie") |
| + const host = "pending.shop.example.com" |
| + lt.pendingCreate(t, host, "record") |
| + l := lt.lifetimesFx |
| + begin(t, l) |
| + cleanImport(t, l, nil, []string{"instances/" + host + "/0000/x.ltx"}) |
| + if code, out := complete(t, l); code != http.StatusConflict || out["error"] != msgHostsStillSettling { |
| + t.Fatalf("complete with an allocation pending = %d %v, want C6", code, out) |
| + } |
| + recoverOn(t, l.fx.srv) |
| + mustComplete(t, l) |
| +} |
| + |
| +func TestCloseFleet(t *testing.T) { |
| + l := invFx(t) |
| + reg := openTestReg(t, l.fx) |
| + if _, err := reg.CreateFleet(registry.Fleet{Name: "fx", Account: "bab", Bucket: "fx-data"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.AddFleetBox(registry.FleetBox{Fleet: "fx", Label: "bx1", TokenHash: strings.Repeat("a", 64)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + begin(t, l) |
| + if code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCloseFleetURL, l.operator, `{"fleet":"ie"}`); code != http.StatusConflict || out["error"] != "ie is not a fleet on the window's list. Regions and pools can't be closed." { |
| + t.Fatalf("close a region = %d %v, want C5", code, out) |
| + } |
| + cleanImport(t, l, nil, nil) |
| + if code, out := complete(t, l); code != http.StatusConflict || !strings.HasPrefix(str(t, out, "error"), "No listing has been imported for ") { |
| + t.Fatalf("complete with the fleet unscanned = %d %v, want C7", code, out) |
| + } |
| + if code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCloseFleetURL, l.operator, `{"fleet":"fx"}`); code != http.StatusOK || !contains(strs(out["closed"]), "fleet:fx") { |
| + t.Fatalf("close-fleet = %d %v", code, out) |
| + } |
| + mustComplete(t, l) |
| + st, _, err := provision.ReadHostsState(context.Background(), l.fx.rel) |
| + if err != nil || !contains(st.Closed, "fleet:fx") || contains(st.Examined, "fleet:fx") { |
| + t.Fatalf("state = %+v %v, want fx closed and not examined", st, err) |
| + } |
| +} |
| + |
| +// strs is a JSON array of strings. |
| +func strs(v any) []string { |
| + a, _ := v.([]any) |
| + var out []string |
| + for _, x := range a { |
| + if s, ok := x.(string); ok { |
| + out = append(out, s) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// TestImportTakesAJSONArray: carlos system hosts-used import posts the |
| +// file's listings as one array; the door reads it as it reads lines. |
| +func TestImportTakesAJSONArray(t *testing.T) { |
| + l := invFx(t) |
| + begin(t, l) |
| + body := "[" + listingLine(t, provision.TargetListing{Target: "b1", Kind: "box", OK: true, Entries: []string{"x.shop.example.com.db"}}) + "," + |
| + listingLine(t, provision.TargetListing{Target: "data-ie", Kind: "bucket", Prefix: "instances", OK: true}) + "]" |
| + code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedImportURL, l.operator, body) |
| + if code != http.StatusOK || len(out["results"].([]any)) != 2 { |
| + t.Fatalf("array import = %d %v", code, out) |
| + } |
| + mustComplete(t, l) |
| + if !marked(t, l.fx.rel, "x.shop.example.com") { |
| + t.Fatal("the array's box listing was not marked") |
| + } |
| +} |
diff --git a/internal/console/hostsused_listings.go b/internal/console/hostsused_listings.go| new file mode 100644 |
| index 000000000..056271faf |
| --- /dev/null |
| +++ b/internal/console/hostsused_listings.go |
| @@ -0,0 +1,105 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/url" |
| + "os" |
| + "sort" |
| + "strings" |
| +) |
| + |
| +// The window's imported listings live in the control bucket beside the |
| +// history, one object per roster target, so a console database restore |
| +// cannot drop them mid-window and they need no table of their own. |
| +const hostsListingsPrefix = "control/hosts-used-window/" |
| + |
| +// hostsListing is one imported listing: a roster target, "box:<box>" or |
| +// "bucket:<bucket>", with what its listing mapped to. |
| +type hostsListing struct { |
| + Target string `json:"target"` |
| + OK bool `json:"ok"` |
| + Error string `json:"error,omitempty"` |
| + Hosts []string `json:"hosts"` |
| + Unmapped []string `json:"unmapped"` // a sample |
| + UnmappedCount int `json:"unmapped_count"` |
| + ImportedAt int64 `json:"imported_at"` |
| +} |
| + |
| +func hostsListingKey(target string) string { |
| + return hostsListingsPrefix + url.PathEscape(target) + ".json" |
| +} |
| + |
| +// putHostsListing stores l, replacing any earlier listing of its target. |
| +func (s *Server) putHostsListing(ctx context.Context, l hostsListing) error { |
| + body, err := json.Marshal(l) |
| + if err != nil { |
| + return err |
| + } |
| + key := hostsListingKey(l.Target) |
| + _, etag, err := s.cfg.Releases.Get(ctx, key) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + etag = "" |
| + case err != nil: |
| + return err |
| + } |
| + _, err = s.cfg.Releases.Put(ctx, key, body, etag) |
| + return err |
| +} |
| + |
| +// hostsListings is every stored listing by target. |
| +func (s *Server) hostsListings(ctx context.Context) (map[string]hostsListing, error) { |
| + keys, err := s.cfg.Releases.List(ctx, hostsListingsPrefix) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out := map[string]hostsListing{} |
| + for _, k := range keys { |
| + raw, _, err := s.cfg.Releases.Get(ctx, k) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + var l hostsListing |
| + if err := json.Unmarshal(raw, &l); err != nil || hostsListingKey(l.Target) != k { |
| + return nil, fmt.Errorf("listing %s does not decode to its own target", k) |
| + } |
| + out[l.Target] = l |
| + } |
| + return out, nil |
| +} |
| + |
| +// clearHostsListings forgets every listing: a new window starts empty. |
| +func (s *Server) clearHostsListings(ctx context.Context) error { |
| + keys, err := s.cfg.Releases.List(ctx, hostsListingsPrefix) |
| + if err != nil { |
| + return err |
| + } |
| + for _, k := range keys { |
| + if strings.HasPrefix(k, hostsListingsPrefix) { |
| + if err := s.cfg.Releases.Delete(ctx, k); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// sortedUnique is xs sorted, without repeats. |
| +func sortedUnique(xs []string) []string { |
| + set := map[string]bool{} |
| + for _, x := range xs { |
| + set[x] = true |
| + } |
| + out := make([]string, 0, len(set)) |
| + for x := range set { |
| + out = append(out, x) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
diff --git a/internal/console/hostsused_store.go b/internal/console/hostsused_store.go| new file mode 100644 |
| index 000000000..810bd8318 |
| --- /dev/null |
| +++ b/internal/console/hostsused_store.go |
| @@ -0,0 +1,26 @@ |
| +package console |
| + |
| +import "sort" |
| + |
| +// LifetimeHosts is every hostname any lifetime row names, in any state and |
| +// from any console version (nearest-region never-reuse spec §3 source 4): |
| +// host_allocations, record_retirements and record_migrations. |
| +func (s *Store) LifetimeHosts() ([]string, error) { |
| + rows, err := s.db.Query(`SELECT host FROM host_allocations UNION SELECT host FROM record_retirements UNION SELECT host FROM record_migrations`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var h string |
| + if err := rows.Scan(&h); err != nil { |
| + return nil, err |
| + } |
| + if h != "" { |
| + out = append(out, h) |
| + } |
| + } |
| + sort.Strings(out) |
| + return out, rows.Err() |
| +} |
diff --git a/internal/console/hostsused_window.go b/internal/console/hostsused_window.go| index ce1f9b5bf..8e82f9fbc 100644 |
| --- a/internal/console/hostsused_window.go |
| +++ b/internal/console/hostsused_window.go |
| @@ -10,6 +10,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/seeds" |
| ) |
| // The activation window (nearest-region never-reuse, spec §3a, plan Task 5) |
| @@ -36,6 +37,19 @@ type hostsUsedStatus struct { |
| PendingAllocations int `json:"pending_allocations"` |
| PendingRetirements int `json:"pending_retirements"` |
| UnfinishedMoves *int `json:"unfinished_moves"` |
| + // UnfinishedSeeds is the records whose seed (a copy or an import) has |
| + // not ended, while the window is open: the copy and the upload run |
| + // after their create's handler has returned. |
| + UnfinishedSeeds *int `json:"unfinished_seeds,omitempty"` |
| + // While the window is open: how many of the roster's targets that need |
| + // a listing (closed fleets' excused) have one, and which have not. |
| + Listings *int `json:"listings,omitempty"` |
| + Targets *int `json:"targets,omitempty"` |
| + NotImported []string `json:"not_imported,omitempty"` |
| + // Closed is the closed fleets, in any mode. |
| + Closed []string `json:"closed,omitempty"` |
| + // Floor is the history's floor, once complete has written it. |
| + Floor *provision.HostsFloor `json:"floor,omitempty"` |
| } |
| // hostsStatusFailure is a status read that failed: the log line's cause |
| @@ -77,25 +91,60 @@ func (s *Server) hostsStatus(ctx context.Context) (hostsUsedStatus, *hostsStatus |
| } |
| out.PendingAllocations, out.PendingRetirements = len(allocs), len(rets) |
| if st.Mode == provision.HostsModeActivating { |
| - n, err := s.unfinishedMoves(ctx) |
| + moves, seeding, err := s.unfinishedWork(ctx) |
| if err != nil { |
| return hostsUsedStatus{}, &hostsStatusFailure{"could not read the instance records. Try again.", err} |
| } |
| - out.UnfinishedMoves = &n |
| + out.UnfinishedMoves, out.UnfinishedSeeds = &moves, &seeding |
| + closed := closedTargets(st) |
| + listings, err := s.hostsListings(ctx) |
| + if err != nil { |
| + return hostsUsedStatus{}, &hostsStatusFailure{"could not read the listings. Try again.", err} |
| + } |
| + have, want := 0, 0 |
| + for _, t := range listingTargets(st.Roster) { |
| + if closed[t] { |
| + continue |
| + } |
| + want++ |
| + if _, ok := listings[t]; ok { |
| + have++ |
| + } else { |
| + out.NotImported = append(out.NotImported, t) |
| + } |
| + } |
| + out.Listings, out.Targets = &have, &want |
| } |
| + out.Closed = st.Closed |
| + floor, _, err := provision.ReadHostsFloor(ctx, s.cfg.Releases) |
| + if err != nil { |
| + return hostsUsedStatus{}, &hostsStatusFailure{"could not read the hostname history's floor. Try again.", err} |
| + } |
| + out.Floor = floor |
| return out, nil |
| } |
| -// unfinishedMoves counts the records under apps/ whose move has not ended: |
| -// Move is present only between a move's start and its terminal flip |
| -// (provision.Record.Move). A record body that does not decode drives no |
| -// move and is logged, not counted. |
| -func (s *Server) unfinishedMoves(ctx context.Context) (int, error) { |
| +// seedEnded is a seed state after which nothing more is copied or |
| +// uploaded for it. |
| +func seedEnded(state string) bool { |
| + switch state { |
| + case seeds.StateCommitted, seeds.StateRefused, seeds.StateAborted, seeds.StateRolledBack: |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// unfinishedWork counts the records under apps/ whose move has not ended |
| +// (Move is present only between a move's start and its terminal flip) and |
| +// whose seed has not ended (a copy or an import still running after its |
| +// create returned). Both are record state, so the counts survive a console |
| +// restart. A record body that does not decode drives neither and is |
| +// logged, not counted. |
| +func (s *Server) unfinishedWork(ctx context.Context) (moves, seeding int, err error) { |
| keys, err := s.cfg.Releases.List(ctx, "apps/") |
| if err != nil { |
| - return 0, err |
| + return 0, 0, err |
| } |
| - n := 0 |
| for _, k := range keys { |
| if !provision.IsRecordKey(k) { |
| continue |
| @@ -105,20 +154,32 @@ func (s *Server) unfinishedMoves(ctx context.Context) (int, error) { |
| if errors.Is(err, os.ErrNotExist) { |
| continue // deleted since the listing |
| } |
| - return 0, err |
| + return 0, 0, err |
| } |
| var body struct { |
| Move json.RawMessage `json:"move"` |
| + Seed *struct { |
| + State string `json:"state"` |
| + } `json:"seed"` |
| } |
| if err := json.Unmarshal(raw, &body); err != nil { |
| - log.Printf("console: hosts used: %s does not decode, so it drives no move: %v", k, err) |
| + log.Printf("console: hosts used: %s does not decode, so it drives no move or seed: %v", k, err) |
| continue |
| } |
| if len(body.Move) > 0 && string(body.Move) != "null" { |
| - n++ |
| + moves++ |
| + } |
| + if body.Seed != nil && !seedEnded(body.Seed.State) { |
| + seeding++ |
| } |
| } |
| - return n, nil |
| + return moves, seeding, nil |
| +} |
| + |
| +// hostsStateAnswer is what begin, cancel and close-fleet answer: the state |
| +// the transition wrote, without status's record scan. |
| +func hostsStateAnswer(st provision.HostsState) hostsUsedStatus { |
| + return hostsUsedStatus{Mode: st.Mode, Closed: st.Closed} |
| } |
| func (s *Server) writeHostsStatus(w http.ResponseWriter, ctx context.Context) { |
| @@ -166,14 +227,29 @@ func (s *Server) handleAPIHostsUsedBegin(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| ctx := r.Context() |
| - _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| + // The roster is fixed now (spec §3): complete refuses if it changes. |
| + roster, fleetTargets, err := s.hostsRosterNow(ctx) |
| + if err != nil { |
| + log.Printf("console: hosts used begin: read the roster: %v", err) |
| + jsonError(w, http.StatusBadGateway, "could not read the regions, fleets and boxes. Try again.") |
| + return |
| + } |
| + if cur, err := s.hostsMode(ctx); err == nil && cur != provision.HostsModeActivating && cur != provision.HostsModeActive { |
| + // A new window starts with no listings. |
| + if err := s.clearHostsListings(ctx); err != nil { |
| + log.Printf("console: hosts used begin: clear the listings: %v", err) |
| + jsonError(w, http.StatusBadGateway, "could not clear the last window's listings. Try again.") |
| + return |
| + } |
| + } |
| + next, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| switch cur.Mode { |
| case provision.HostsModeActive: |
| return cur, &doorRefusal{http.StatusConflict, msgHostsAlreadyComplete} |
| case provision.HostsModeActivating: |
| return cur, &doorRefusal{http.StatusConflict, msgHostsWindowOpen} |
| } |
| - return provision.HostsState{Mode: provision.HostsModeActivating, From: cur.Mode}, nil |
| + return provision.HostsState{Mode: provision.HostsModeActivating, From: cur.Mode, Roster: roster, FleetTargets: fleetTargets}, nil |
| }) |
| switch { |
| case err != nil: |
| @@ -184,7 +260,7 @@ func (s *Server) handleAPIHostsUsedBegin(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| log.Printf("console: hosts used: %s opened the maintenance window", addr) |
| - s.writeHostsStatus(w, ctx) |
| + writeJSON(w, http.StatusOK, hostsStateAnswer(next)) |
| } |
| // handleAPIHostsUsedCancel is POST /api/cli/system/hosts-used/cancel: close |
| @@ -205,7 +281,7 @@ func (s *Server) handleAPIHostsUsedCancel(w http.ResponseWriter, r *http.Request |
| return |
| } |
| ctx := r.Context() |
| - _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| + next, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| if cur.Mode != provision.HostsModeActivating { |
| return cur, &doorRefusal{http.StatusConflict, msgHostsNoWindow} |
| } |
| @@ -224,5 +300,5 @@ func (s *Server) handleAPIHostsUsedCancel(w http.ResponseWriter, r *http.Request |
| return |
| } |
| log.Printf("console: hosts used: %s closed the maintenance window", addr) |
| - s.writeHostsStatus(w, ctx) |
| + writeJSON(w, http.StatusOK, hostsStateAnswer(next)) |
| } |
diff --git a/internal/console/hostsused_window_test.go b/internal/console/hostsused_window_test.go| index f6375346d..93c03959b 100644 |
| --- a/internal/console/hostsused_window_test.go |
| +++ b/internal/console/hostsused_window_test.go |
| @@ -8,11 +8,14 @@ package console |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "net/http" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| ) |
| const ( |
| @@ -227,3 +230,87 @@ func TestCancelReturnsToIncomplete(t *testing.T) { |
| t.Fatalf("begin when active = %d %v, want 409 C1", code, st) |
| } |
| } |
| + |
| +// TestDrainWaitsForUnfinishedSeed (Astra Task 5 r1, P1 1): a seed's copy or |
| +// upload continues after its create's handler returns, so a record whose |
| +// seed has not ended keeps unfinished_seeds above 0, and complete refuses. |
| +func TestDrainWaitsForUnfinishedSeed(t *testing.T) { |
| + for _, state := range []string{seeds.StateReserving, seeds.StateAwaitingUpload, seeds.StateUploaded, seeds.StateReady, seeds.StatePlaced} { |
| + t.Run(state, func(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + const host = "seeding.shop.example.com" |
| + rec := provision.Record{Schema: 1, Host: host, Slug: "seeding", App: ltApp, Account: "bab", Channel: "stable", |
| + CreatedAt: time.Now().UTC(), Seed: &provision.SeedSource{ID: "sd_abcdefghijklmnopqrstuvwxyz", Kind: seeds.KindReplica, State: state}} |
| + if err := provision.CreateRecord(context.Background(), l.fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + begin(t, l) |
| + if st := statusOf(t, l); st["unfinished_seeds"] != float64(1) { |
| + t.Fatalf("unfinished_seeds = %v, want 1", st["unfinished_seeds"]) |
| + } |
| + if code, out := hostsDoor(t, l.fx, http.MethodPost, "/api/cli/system/hosts-used/complete", l.operator, `{}`); code != http.StatusConflict || out["error"] != msgHostsStillSettling { |
| + t.Fatalf("complete with a seed unfinished = %d %v, want C6", code, out) |
| + } |
| + // The seed ends (a fixture write: seed states change only through |
| + // the seed transitions). |
| + key := provision.RecordKey("bab", ltApp, host) |
| + _, etag, err := l.fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec.Seed.State = seeds.StateCommitted |
| + body, _ := json.Marshal(rec) |
| + if _, err := l.fx.rel.Put(context.Background(), key, body, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if st := statusOf(t, l); st["unfinished_seeds"] != float64(0) { |
| + t.Fatalf("unfinished_seeds once committed = %v, want 0", st["unfinished_seeds"]) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// landsThenFails commits a Put of key, then reports an error: the answer a |
| +// timed-out write gives. |
| +type landsThenFails struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (s landsThenFails) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + tag, err := s.Store.Put(ctx, key, body, ifMatch) |
| + if err == nil && key == s.key { |
| + return "", errors.New("the bucket did not answer in time") |
| + } |
| + return tag, err |
| +} |
| + |
| +// TestAmbiguousModeWriteRereads (Astra Task 5 r1, P1 2): a mode write whose |
| +// outcome is unknown drops the process's copy, so the next door reads the |
| +// store and sees the window the write opened. |
| +func TestAmbiguousModeWriteRereads(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + l.fx.srv.cfg.Releases = landsThenFails{Store: l.fx.rel, key: provision.HostsModeKey} |
| + if code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedBeginURL, l.operator, `{}`); code != http.StatusBadGateway { |
| + t.Fatalf("begin whose write timed out = %d %v, want 502", code, out) |
| + } |
| + if code, out := createAs(t, l, `{"host":"after.shop.example.com"}`); code != http.StatusServiceUnavailable || ltErr(out) != msgHostsActivating { |
| + t.Fatalf("create after an ambiguous begin = %d %s, want 503 S8", code, out) |
| + } |
| +} |
| + |
| +// TestBeginAnswersWithoutTheRecordScan (Astra Task 5 r1, P2): begin and |
| +// cancel answer the transition; only status reads every record. |
| +func TestBeginAnswersWithoutTheRecordScan(t *testing.T) { |
| + l := newLifetimesFx(t) |
| + bucket := <Store{Store: l.fx.rel} |
| + l.fx.srv.cfg.Releases = bucket |
| + if err := provision.CreateRecord(context.Background(), l.fx.rel, provision.Record{Schema: 1, Host: "x.shop.example.com", Slug: "x", App: ltApp, Account: "bab", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + begin(t, l) |
| + hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`) |
| + if ops := bucket.opsOf(provision.RecordKey("bab", ltApp, "x.shop.example.com")); len(ops) != 0 { |
| + t.Fatalf("begin and cancel read the record: %v", ops) |
| + } |
| +} |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 9e6b20a4a..1395b442a 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -296,6 +296,9 @@ var closedDoors = []string{ |
| "GET /api/cli/system/hosts-used/status", |
| "POST /api/cli/system/hosts-used/begin", |
| "POST /api/cli/system/hosts-used/cancel", |
| + "POST /api/cli/system/hosts-used/import", |
| + "POST /api/cli/system/hosts-used/close-fleet", |
| + "POST /api/cli/system/hosts-used/complete", |
| // `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", |
| @@ -1105,8 +1108,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 69 { |
| - t.Errorf("walked %d closed doors, want all %d (and 69 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, two app region 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 and its two window 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 != 72 { |
| + t.Errorf("walked %d closed doors, want all %d (and 72 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, two app region 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 and its five window doors, 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/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index af22e6caa..40151fcd6 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -269,6 +269,9 @@ route POST /api/cli/system/antivirus |
| route POST /api/cli/system/antivirus/rotate-webhook-key |
| route POST /api/cli/system/hosts-used/begin |
| route POST /api/cli/system/hosts-used/cancel |
| +route POST /api/cli/system/hosts-used/close-fleet |
| +route POST /api/cli/system/hosts-used/complete |
| +route POST /api/cli/system/hosts-used/import |
| route POST /api/cli/system/layout |
| route POST /api/cli/system/legacy-routes |
| route POST /api/cli/system/lifetimes/cutover |
diff --git a/internal/provision/hostsused.go b/internal/provision/hostsused.go| index 492e3d013..d719b47c8 100644 |
| --- a/internal/provision/hostsused.go |
| +++ b/internal/provision/hostsused.go |
| @@ -137,6 +137,9 @@ type HostsState struct { |
| // ("region:<code>", "pool:<name>", "fleet:<name>"). A data-kind create |
| // anywhere else is refused once active. |
| Examined []string `json:"examined,omitempty"` |
| + // FleetTargets is, for each fleet on the roster, the listing targets |
| + // it owns (its boxes and its bucket), which closing it excuses. |
| + FleetTargets map[string][]string `json:"fleet_targets,omitempty"` |
| // Closed is the fleets closed instead of scanned ("fleet:<name>"), |
| // which take no data-kind create. |
| Closed []string `json:"closed,omitempty"` |
diff --git a/internal/provision/hostsused_map.go b/internal/provision/hostsused_map.go| new file mode 100644 |
| index 000000000..d4d2d632f |
| --- /dev/null |
| +++ b/internal/provision/hostsused_map.go |
| @@ -0,0 +1,197 @@ |
| +package provision |
| + |
| +import ( |
| + "sort" |
| + "strings" |
| +) |
| + |
| +// The inventory's listing-to-hostname mapping (nearest-region never-reuse, |
| +// spec §3 sources 2 and 3, plan Task 6). Pure: an adapter lists a data |
| +// bucket's current objects or a box's data directory, and these functions |
| +// say which hostnames that data belongs to. Nothing is normalised: a name |
| +// ValidHostShape refuses (uppercase, a trailing dot, an empty label) maps to |
| +// no hostname. An entry that should name a hostname and does not is |
| +// returned unmapped, and the inventory refuses to complete while any |
| +// remains. Each result is sorted and has no duplicates. |
| + |
| +// HostsFromBucketListing maps a data bucket's object keys: |
| +// <replicaPrefix>/<host>/..., moves/<host>/..., moves/@offline/<host>/... |
| +// and seeds/<host>/.... moves/@lanes/... is no hostname's data and is |
| +// skipped. Any other key is unmapped. replicaPrefix is the box's configured |
| +// prefix (activator.Config.Prefix); "" puts replicas at the bucket's top |
| +// level, where any key outside moves/ and seeds/ is a replica. |
| +func HostsFromBucketListing(replicaPrefix string, keys []string) (hosts, unmapped []string) { |
| + rp := strings.Trim(replicaPrefix, "/") |
| + hs, um := map[string]bool{}, map[string]bool{} |
| + for _, key := range keys { |
| + host, ok, skip := bucketKeyHost(rp, key) |
| + switch { |
| + case skip: |
| + case ok: |
| + hs[host] = true |
| + default: |
| + um[key] = true |
| + } |
| + } |
| + return sortedKeys(hs), sortedKeys(um) |
| +} |
| + |
| +func bucketKeyHost(rp, key string) (host string, ok, skip bool) { |
| + segAfter := func(prefix string) (string, bool) { |
| + rest, found := strings.CutPrefix(key, prefix) |
| + if !found { |
| + return "", false |
| + } |
| + seg, _, _ := strings.Cut(rest, "/") |
| + return seg, true |
| + } |
| + if strings.HasPrefix(key, "moves/@lanes/") { |
| + return "", false, true |
| + } |
| + if seg, found := segAfter("moves/@offline/"); found { |
| + return seg, ValidHostShape(seg), false |
| + } |
| + if seg, found := segAfter("moves/"); found { |
| + return seg, ValidHostShape(seg), false |
| + } |
| + if seg, found := segAfter("seeds/"); found { |
| + return seg, ValidHostShape(seg), false |
| + } |
| + if rp == "" { |
| + seg, _, _ := strings.Cut(key, "/") |
| + return seg, ValidHostShape(seg), false |
| + } |
| + if seg, found := segAfter(rp + "/"); found { |
| + return seg, ValidHostShape(seg), false |
| + } |
| + return "", false, false |
| +} |
| + |
| +// boxPlatformSuffixes are the platform's per-host flat file shapes, longest |
| +// first (internal/layout's fixedSuffixes). |
| +var boxPlatformSuffixes = []string{".db.corrupt", ".config.env", "-sidecar.env", ".db-wal", ".db-shm", ".db", ".env"} |
| + |
| +// hostLike is a name that can be a served hostname: a valid shape with a |
| +// dot in it, so the box's own files (registry.db, litestream.env, static/) |
| +// are nobody's. |
| +func hostLike(x string) bool { return strings.Contains(x, ".") && ValidHostShape(x) } |
| + |
| +// HostsFromBoxListing maps a box's data directory listing, paths relative |
| +// to the data directory (find <dir> -maxdepth 3). Flat top-level names are |
| +// a host's when they are the host itself or the host plus a "." or "-" and |
| +// more (<host>.db, <host>-blobs, .activator-<host>.db-litestream): every |
| +// host-like prefix ending at such a boundary is marked, because an app may |
| +// name its files from its database path. A name with one of the platform's |
| +// own suffixes is read exactly (registry.db is the box's). instances/<id>/ |
| +// and .instances/<id>/ map to <id>, or for a hashed id ("_" + prefix + |
| +// hash, InstanceID) to the full host a file inside names; a hashed id with |
| +// none is unmapped. .offline-moves/<host>/ maps to <host>. Other top-level |
| +// names that are not host-like are the box's own and are skipped. |
| +func HostsFromBoxListing(paths []string) (hosts, unmapped []string) { |
| + hs, um := map[string]bool{}, map[string]bool{} |
| + hashed := map[string][]string{} // "<root>/<id>" -> inner names |
| + for _, p := range paths { |
| + p = strings.TrimSuffix(strings.TrimPrefix(p, "./"), "/") |
| + if p == "" || p == "." { |
| + continue |
| + } |
| + segs := strings.Split(p, "/") |
| + switch segs[0] { |
| + case "instances", ".instances": |
| + if len(segs) < 2 { |
| + continue |
| + } |
| + id := segs[1] |
| + if strings.HasPrefix(id, "_") { |
| + dir := segs[0] + "/" + id |
| + if _, seen := hashed[dir]; !seen { |
| + hashed[dir] = nil |
| + } |
| + if len(segs) >= 3 { |
| + hashed[dir] = append(hashed[dir], segs[2]) |
| + } |
| + continue |
| + } |
| + if ValidHostShape(id) { |
| + hs[id] = true |
| + } else { |
| + um[segs[0]+"/"+id] = true |
| + } |
| + case ".offline-moves": |
| + if len(segs) < 2 { |
| + continue |
| + } |
| + if ValidHostShape(segs[1]) { |
| + hs[segs[1]] = true |
| + } else { |
| + um[segs[0]+"/"+segs[1]] = true |
| + } |
| + default: |
| + for _, h := range flatNameHosts(segs[0]) { |
| + hs[h] = true |
| + } |
| + } |
| + } |
| + for dir, names := range hashed { |
| + _, id, _ := strings.Cut(dir, "/") |
| + found := false |
| + for _, name := range names { |
| + for _, h := range flatNameHosts(name) { |
| + if InstanceID(h) == id { |
| + hs[h] = true |
| + found = true |
| + } |
| + } |
| + } |
| + if !found { |
| + um[dir] = true |
| + } |
| + } |
| + return sortedKeys(hs), sortedKeys(um) |
| +} |
| + |
| +// flatNameHosts is every host a flat name may belong to. |
| +func flatNameHosts(name string) []string { |
| + name = strings.TrimPrefix(name, ".activator-") |
| + for _, suffix := range boxPlatformSuffixes { |
| + if x, ok := strings.CutSuffix(name, suffix); ok && x != "" { |
| + if hostLike(x) { |
| + return []string{x} |
| + } |
| + return nil |
| + } |
| + } |
| + var out []string |
| + for i := len(name); i > 0; i-- { |
| + if i < len(name) && name[i] != '.' && name[i] != '-' { |
| + continue |
| + } |
| + if x := name[:i]; hostLike(x) { |
| + out = append(out, x) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func sortedKeys(m map[string]bool) []string { |
| + out := make([]string, 0, len(m)) |
| + for k := range m { |
| + out = append(out, k) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +// TargetListing is one roster target's listing, one JSON line of the |
| +// adapter's output (plan Task 6). Kind is "bucket" (Target is the bucket, |
| +// Prefix the boxes' configured replica prefix, Entries its object keys) or |
| +// "box" (Target is the box, Entries the data directory's paths). A listing |
| +// that did not complete has OK false and says why in Error. |
| +type TargetListing struct { |
| + Target string `json:"target"` |
| + Kind string `json:"kind"` |
| + Prefix string `json:"prefix,omitempty"` |
| + OK bool `json:"ok"` |
| + Error string `json:"error,omitempty"` |
| + Entries []string `json:"entries"` |
| +} |
diff --git a/internal/provision/hostsused_map_test.go b/internal/provision/hostsused_map_test.go| new file mode 100644 |
| index 000000000..9ed147682 |
| --- /dev/null |
| +++ b/internal/provision/hostsused_map_test.go |
| @@ -0,0 +1,133 @@ |
| +package provision |
| + |
| +import ( |
| + "reflect" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The inventory's listing-to-hostname mapping (nearest-region never-reuse |
| +// plan, Task 6; spec §3 sources 2 and 3). |
| + |
| +func TestBucketListingSuffixHostsStayDistinct(t *testing.T) { |
| + hosts, unmapped := HostsFromBucketListing("instances", []string{ |
| + "instances/app.example.co/0000/0000000000000001-0000000000000001.ltx", |
| + "instances/app.example.com/0000/0000000000000001-0000000000000001.ltx", |
| + "moves/app.example.co/mv_x/0000/a.ltx", |
| + }) |
| + if !reflect.DeepEqual(hosts, []string{"app.example.co", "app.example.com"}) || len(unmapped) != 0 { |
| + t.Fatalf("hosts %v unmapped %v", hosts, unmapped) |
| + } |
| +} |
| + |
| +func TestBucketListingRoots(t *testing.T) { |
| + hosts, unmapped := HostsFromBucketListing("data/replicas", []string{ |
| + "data/replicas/a.example.com/0000/x.ltx", |
| + "moves/b.example.com/mv_1/0000/x.ltx", |
| + "moves/@offline/c.example.com/mv_2/files.sealed", |
| + "moves/@lanes/uk/whatever", |
| + "seeds/d.example.com/sd_1/snapshot.db", |
| + "instances/e.example.com/0000/x.ltx", // not under the configured prefix |
| + "moves/@other/f.example.com/x", |
| + "seeds/", |
| + }) |
| + if want := []string{"a.example.com", "b.example.com", "c.example.com", "d.example.com"}; !reflect.DeepEqual(hosts, want) { |
| + t.Fatalf("hosts = %v, want %v", hosts, want) |
| + } |
| + if want := []string{"instances/e.example.com/0000/x.ltx", "moves/@other/f.example.com/x", "seeds/"}; !reflect.DeepEqual(unmapped, want) { |
| + t.Fatalf("unmapped = %v, want %v", unmapped, want) |
| + } |
| +} |
| + |
| +// TestListingHostNormalisation: nothing is normalised. A name |
| +// controlname.ValidHostShape refuses (uppercase, a trailing dot, an empty |
| +// label) maps to no hostname and is reported unmapped. |
| +func TestListingHostNormalisation(t *testing.T) { |
| + hosts, unmapped := HostsFromBucketListing("instances", []string{ |
| + "instances/Shop.example.com/0000/x.ltx", |
| + "instances/shop.example.com./0000/x.ltx", |
| + "instances/shop..example.com/0000/x.ltx", |
| + "seeds/SHOP.EXAMPLE.COM/sd/snapshot.db", |
| + }) |
| + if len(hosts) != 0 || len(unmapped) != 4 { |
| + t.Fatalf("hosts %v unmapped %v", hosts, unmapped) |
| + } |
| + hosts, unmapped = HostsFromBoxListing([]string{".offline-moves/Shop.example.com/x", "instances/shop.example.com./x.db"}) |
| + if len(hosts) != 0 || len(unmapped) != 2 { |
| + t.Fatalf("box: hosts %v unmapped %v", hosts, unmapped) |
| + } |
| +} |
| + |
| +func TestBoxListingShapes(t *testing.T) { |
| + hosts, unmapped := HostsFromBoxListing([]string{ |
| + ".", |
| + "registry.db", |
| + "litestream.env", |
| + "static", |
| + "static/site.example.com/index.html", |
| + "a.example.com.db", |
| + "a.example.com.db-wal", |
| + ".activator-b.example.com.db-litestream", |
| + "c.example.com.env", |
| + "d.example.com", |
| + "d.example.com/instance.key", |
| + "e.example.com-blobs", |
| + "instances", |
| + "instances/f.example.com", |
| + "instances/f.example.com/f.example.com.db", |
| + ".instances/g.example.com/g.example.com.db", |
| + ".offline-moves/h.example.com/mv_1/files.tar", |
| + }) |
| + // Hazard-complete: every host whose data is listed is marked. A flat |
| + // name may also mark shorter host-like prefixes (d.example for |
| + // d.example.com): over-marking is the accepted cost (spec §1). |
| + got := map[string]bool{} |
| + for _, h := range hosts { |
| + got[h] = true |
| + } |
| + for _, h := range []string{"a.example.com", "b.example.com", "c.example.com", "d.example.com", "e.example.com", "f.example.com", "g.example.com", "h.example.com"} { |
| + if !got[h] { |
| + t.Errorf("%s is not marked (hosts %v)", h, hosts) |
| + } |
| + } |
| + // The box's own files and static sites are nobody's. |
| + for _, h := range []string{"registry", "registry.db", "litestream", "litestream.env", "static", "site.example.com"} { |
| + if got[h] { |
| + t.Errorf("%s was marked", h) |
| + } |
| + } |
| + if len(unmapped) != 0 { |
| + t.Fatalf("unmapped %v", unmapped) |
| + } |
| +} |
| + |
| +func TestHashedInstanceDirMapsByInnerFile(t *testing.T) { |
| + long := strings.Repeat("a", 40) + ".example.com" |
| + id := InstanceID(long) |
| + if !strings.HasPrefix(id, "_") { |
| + t.Fatalf("fixture: %q is not hashed", id) |
| + } |
| + hosts, unmapped := HostsFromBoxListing([]string{ |
| + "instances/" + id, |
| + "instances/" + id + "/" + long + ".db", |
| + "instances/" + id + "/" + long + ".db-wal", |
| + }) |
| + if !reflect.DeepEqual(hosts, []string{long}) || len(unmapped) != 0 { |
| + t.Fatalf("hosts %v unmapped %v", hosts, unmapped) |
| + } |
| +} |
| + |
| +func TestHashedInstanceDirWithoutHostIsUnmapped(t *testing.T) { |
| + long := strings.Repeat("b", 40) + ".example.com" |
| + id := InstanceID(long) |
| + other := strings.Repeat("c", 40) + ".example.com" |
| + hosts, unmapped := HostsFromBoxListing([]string{ |
| + "instances/" + id, |
| + "instances/" + id + "/blobs", |
| + "instances/" + id + "/" + other + ".db", // a host that does not hash to this id |
| + ".instances/_zzz", |
| + }) |
| + if len(hosts) != 0 || !reflect.DeepEqual(unmapped, []string{".instances/_zzz", "instances/" + id}) { |
| + t.Fatalf("hosts %v unmapped %v", hosts, unmapped) |
| + } |
| +} |
diff --git a/internal/provision/nearest_region_b_census_test.go b/internal/provision/nearest_region_b_census_test.go| index 43aa893af..b28234ecb 100644 |
| --- a/internal/provision/nearest_region_b_census_test.go |
| +++ b/internal/provision/nearest_region_b_census_test.go |
| @@ -9,12 +9,22 @@ package provision |
| // - WriteHostsState (provision), new: the one Put of control/hosts-used/@mode, |
| // the state with its window facts. No record key or body: nonrecord. |
| // WriteHostsMode now writes through it and leaves the inventory. |
| -// - Server.unfinishedMoves (console), new: lists apps/ and reads each |
| -// record key (IsRecordKey) to count moves not ended. Reads only: key-site. |
| +// - Server.unfinishedWork (console), new: lists apps/ and reads each |
| +// record key (IsRecordKey) to count moves and seeds not ended. Reads |
| +// only: key-site. |
| +// - Server.recordSources (console), new: the inventory's source 1, lists |
| +// apps/ and reads each record key (IsRecordKey; "sidecars" names the |
| +// sidecar key shape) to collect hostnames. Reads only: key-site. |
| +// - HostsFromBoxListing (provision), new: pure mapping of a box's |
| +// data-directory listing; "instances" is the nested layout's directory |
| +// name, not a record path. No store: key-site. |
| // - Server.handleAPIInstanceMoveRequest, Server.placeAppTarget, re-pinned: |
| // each admits through the hostname history (admitMoveOrPlace) before |
| // anything else and is refused while the window is open. Their write |
| // sites are unchanged: still record-writer. |
| +// - Server.putHostsListing (console), new: Puts one imported listing at |
| +// control/hosts-used-window/<target>.json, on the ETag it read. No |
| +// record key or body: nonrecord. |
| // - Server.registerCLIRoutes, re-pinned: the window's doors. Same |
| // literals: still key-site. |
| func nearestRegionBWriteCensusInventory() []censusEntry { |
| @@ -36,10 +46,13 @@ func nearestRegionBWriteCensusInventory() []censusEntry { |
| } |
| replacements := []censusEntry{ |
| {"internal/provision/hostsused.go", "WriteHostsState", "nonrecord", "sel:Put", "5f1b95198e45dedc9715d73a57bfa57cb1305d364895cd981375e0ed3610c8da"}, |
| - {"internal/console/hostsused_window.go", "Server.unfinishedMoves", "key-site", "key:IsRecordKey", "797c355d9aa71c432fc3953673198df46fb1f3d3597ac65390c2e71af2344428"}, |
| + {"internal/console/hostsused_window.go", "Server.unfinishedWork", "key-site", "key:IsRecordKey", "6c89085fd6cdefd720c3aa25390ae989526a30a2aaca72fdfe78b3fc3b270cd2"}, |
| + {"internal/console/hostsused_listings.go", "Server.putHostsListing", "nonrecord", "sel:Put", "b522337e4d3d9b674e53a433e3173565625abf43649f0e1c86772113faa1449f"}, |
| + {"internal/console/hostsused_inventory.go", "Server.recordSources", "key-site", "key:IsRecordKey,lit:sidecars", "ee553f689bcecd89c2feb9fa99d91e64e5a660bf1eeb5047b754c31858b5c2ac"}, |
| + {"internal/provision/hostsused_map.go", "HostsFromBoxListing", "key-site", "lit:instances", "ba7e6529c3820e3bc16dd215734cc6521cea12bd0ba0ab540ffeba888b550f69"}, |
| {"internal/console/apiinstancemove.go", "Server.handleAPIInstanceMoveRequest", "record-writer", "key:SetRecordMove,lit:instances", "7366c131cf6643449687eac2e56e55b5b55c51434b00123c339bb66067f3d413"}, |
| {"internal/console/fleets.go", "Server.placeAppTarget", "record-writer", "key:RecordsPrefix,key:SetRecordRegion", "e9fe8c1b6cddba8902c269f2358ab3394edbb78d8fe9cab57c3ba5918d1e29e0"}, |
| - {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "a2c16f07a2b685cf6de7a90e1b1ad9a07224d2a76245a9dd1c9bca508ccbff8e"}, |
| + {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "7916f9029b545af12934863b35e00db8e92d65debc84c3cc54002e41d9944ba8"}, |
| } |
| for _, r := range replacements { |
| found := false |
diff --git a/system_hostsused.go b/system_hostsused.go| index 31eada3ae..0675788ab 100644 |
| --- a/system_hostsused.go |
| +++ b/system_hostsused.go |
| @@ -1,14 +1,17 @@ |
| package main |
| import ( |
| + "bytes" |
| "context" |
| "encoding/json" |
| + "errors" |
| "flag" |
| "fmt" |
| "io" |
| "log" |
| "net/http" |
| "os" |
| + "strings" |
| ) |
| // carlos system hosts-used status (nearest-region never-reuse, plan Task 4): |
| @@ -21,12 +24,21 @@ 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"` |
| + 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"` |
| + UnfinishedSeeds *int `json:"unfinished_seeds"` |
| + Listings *int `json:"listings"` |
| + Targets *int `json:"targets"` |
| + NotImported []string `json:"not_imported"` |
| + Closed []string `json:"closed"` |
| + Floor *struct { |
| + Version string `json:"version"` |
| + Commit string `json:"commit"` |
| + } `json:"floor"` |
| } |
| type roleGet func(ctx context.Context, path string) (int, []byte, error) |
| @@ -68,11 +80,32 @@ func printHostsUsedStatus(w io.Writer, st hostsUsedStatusView) { |
| if st.InflightCreates != nil { |
| fmt.Fprintf(w, "create and placement requests in progress: %d\n", *st.InflightCreates) |
| } |
| - fmt.Fprintf(w, "instance creates still settling: %d\n", st.PendingAllocations) |
| + // A seed's copy or upload is a create still settling too. |
| + settling := st.PendingAllocations |
| + if st.UnfinishedSeeds != nil { |
| + settling += *st.UnfinishedSeeds |
| + } |
| + fmt.Fprintf(w, "instance creates still settling: %d\n", settling) |
| 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) |
| } |
| + if st.Listings != nil && st.Targets != nil { |
| + fmt.Fprintf(w, "listings imported: %d of %d\n", *st.Listings, *st.Targets) |
| + } |
| + if len(st.NotImported) > 0 { |
| + fmt.Fprintf(w, "not imported yet: %s\n", strings.Join(st.NotImported, ", ")) |
| + } |
| + if len(st.Closed) > 0 { |
| + names := make([]string, len(st.Closed)) |
| + for i, c := range st.Closed { |
| + names[i] = strings.TrimPrefix(c, "fleet:") |
| + } |
| + fmt.Fprintf(w, "closed fleets: %s\n", strings.Join(names, ", ")) |
| + } |
| + if st.Floor != nil { |
| + fmt.Fprintf(w, "floor: %s (%s)\n", st.Floor.Version, st.Floor.Commit) |
| + } |
| } |
| // systemHostsUsedPost calls one of the window's POST doors, which answer |
| @@ -110,6 +143,71 @@ func printHostsUsedCancel(w io.Writer, st hostsUsedStatusView) { |
| fmt.Fprintln(w, hostsUsedModeLine(st.Mode)) |
| } |
| +// hostsImportResult is one listing's answer from the import door. |
| +type hostsImportResult struct { |
| + Target string `json:"target"` |
| + OK bool `json:"ok"` |
| + Error string `json:"error"` |
| + Hosts int `json:"hosts"` |
| + Unmapped int `json:"unmapped"` |
| + Sample []string `json:"sample"` |
| +} |
| + |
| +// readListingsFile reads the adapter's output: one JSON value per line. |
| +func readListingsFile(path string) ([]json.RawMessage, error) { |
| + b, err := os.ReadFile(path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(b)) |
| + var out []json.RawMessage |
| + for { |
| + var v json.RawMessage |
| + if err := dec.Decode(&v); errors.Is(err, io.EOF) { |
| + return out, nil |
| + } else if err != nil { |
| + return nil, fmt.Errorf("%s: %w", path, err) |
| + } |
| + out = append(out, v) |
| + } |
| +} |
| + |
| +// systemHostsUsedImport posts the listings to the import door. |
| +func systemHostsUsedImport(ctx context.Context, post rolePost, listings []json.RawMessage) ([]hostsImportResult, error) { |
| + status, raw, err := post(ctx, "/api/cli/system/hosts-used/import", listings) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if status != http.StatusOK { |
| + return nil, apiErrorFromBody(status, raw) |
| + } |
| + var out struct { |
| + Results []hostsImportResult `json:"results"` |
| + } |
| + if err := json.Unmarshal(raw, &out); err != nil { |
| + return nil, fmt.Errorf("unreadable response: %w", err) |
| + } |
| + return out.Results, nil |
| +} |
| + |
| +// printHostsImport is import's output (B4-B6), one line per target. |
| +func printHostsImport(w io.Writer, results []hostsImportResult) { |
| + for _, r := range results { |
| + switch { |
| + case !r.OK: |
| + fmt.Fprintf(w, "%s: the listing failed: %s\n", r.Target, r.Error) |
| + case r.Unmapped > 0: |
| + entry := "" |
| + if len(r.Sample) > 0 { |
| + entry = r.Sample[0] |
| + } |
| + fmt.Fprintf(w, "%s: %d entries have no hostname, such as %s\n", r.Target, r.Unmapped, entry) |
| + default: |
| + fmt.Fprintf(w, "%s: %d hostnames\n", r.Target, r.Hosts) |
| + } |
| + } |
| +} |
| + |
| // runSystemHostsUsedVerb is `carlos system hosts-used <verb>`. |
| func runSystemHostsUsedVerb(rest []string) { |
| if len(rest) == 0 { |
| @@ -117,8 +215,11 @@ func runSystemHostsUsedVerb(rest []string) { |
| os.Exit(2) |
| } |
| verb := rest[0] |
| + args := 0 |
| switch verb { |
| - case "status", "begin", "cancel": |
| + case "status", "begin", "cancel", "complete": |
| + case "import", "close-fleet": |
| + args = 1 |
| default: |
| systemUsage() |
| os.Exit(2) |
| @@ -126,18 +227,34 @@ func runSystemHostsUsedVerb(rest []string) { |
| fs := flag.NewFlagSet("system hosts-used "+verb, flag.ExitOnError) |
| consoleFlag := consoleOption(fs, "console origin (default: the only logged-in one)") |
| fs.Parse(rest[1:]) |
| - if fs.NArg() != 0 { |
| + if fs.NArg() != args { |
| fs.Usage() |
| os.Exit(2) |
| } |
| + var listings []json.RawMessage |
| + if verb == "import" { |
| + var err error |
| + if listings, err = readListingsFile(fs.Arg(0)); err != nil { |
| + log.Fatalf("carlos system hosts-used import: %v", err) |
| + } |
| + } |
| sess := requireDeployAPISession(*consoleFlag) |
| printUsing(stdout, sess) |
| ctx := context.Background() |
| var st hostsUsedStatusView |
| var err error |
| - if verb == "status" { |
| + switch verb { |
| + case "status": |
| st, err = systemHostsUsedStatus(ctx, sess.getJSON) |
| - } else { |
| + case "import": |
| + var results []hostsImportResult |
| + if results, err = systemHostsUsedImport(ctx, sess.postJSON, listings); err == nil { |
| + printHostsImport(stdout, results) |
| + return |
| + } |
| + case "close-fleet": |
| + st, err = systemHostsUsedPost(ctx, sess.postJSON, verb, map[string]string{"fleet": fs.Arg(0)}) |
| + default: |
| st, err = systemHostsUsedPost(ctx, sess.postJSON, verb, map[string]string{}) |
| } |
| if err != nil { |
| @@ -150,5 +267,9 @@ func runSystemHostsUsedVerb(rest []string) { |
| printHostsUsedBegin(stdout, st) |
| case "cancel": |
| printHostsUsedCancel(stdout, st) |
| + case "close-fleet": |
| + fmt.Fprintf(stdout, "fleet %s is closed. new instances can't be placed on it\n", fs.Arg(0)) |
| + case "complete": |
| + fmt.Fprintf(stdout, "the hostname history is complete. %d hostnames recorded\n", st.Marks) |
| } |
| } |
diff --git a/system_hostsused_test.go b/system_hostsused_test.go| index a1f7d7b76..827f4b8ae 100644 |
| --- a/system_hostsused_test.go |
| +++ b/system_hostsused_test.go |
| @@ -3,6 +3,7 @@ package main |
| import ( |
| "bytes" |
| "context" |
| + "io" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| @@ -189,3 +190,100 @@ func TestSystemHostsUsedWindowVerbsThroughTheBinary(t *testing.T) { |
| t.Fatalf("asked %v", asked) |
| } |
| } |
| + |
| +func TestHostsUsedStatusWindowLines(t *testing.T) { |
| + var out bytes.Buffer |
| + two, three, one := 2, 3, 1 |
| + printHostsUsedStatus(&out, hostsUsedStatusView{Mode: "activating", Marks: 4, InflightCreates: &one, PendingAllocations: 1, |
| + UnfinishedSeeds: &two, UnfinishedMoves: &one, Listings: &two, Targets: &three, NotImported: []string{"box:b2"}, |
| + Closed: []string{"fleet:fx"}}) |
| + want := "mode: activating. new instances, moves and placement changes are paused\n" + |
| + "hostnames recorded: 4\n" + |
| + "create and placement requests in progress: 1\n" + |
| + "instance creates still settling: 3\n" + |
| + "instance deletes still settling: 0\n" + |
| + "moves not finished: 1\n" + |
| + "listings imported: 2 of 3\n" + |
| + "not imported yet: box:b2\n" + |
| + "closed fleets: fx\n" |
| + if out.String() != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", out.String(), want) |
| + } |
| + out.Reset() |
| + printHostsImport(&out, []hostsImportResult{ |
| + {Target: "box:b1", OK: true, Hosts: 3}, |
| + {Target: "box:b2", OK: false, Error: "ssm: timed out"}, |
| + {Target: "bucket:d", OK: true, Hosts: 1, Unmapped: 2, Sample: []string{"seeds/"}}, |
| + }) |
| + want = "box:b1: 3 hostnames\nbox:b2: the listing failed: ssm: timed out\nbucket:d: 2 entries have no hostname, such as seeds/\n" |
| + if out.String() != want { |
| + t.Fatalf("import output:\n%s\nwant:\n%s", out.String(), want) |
| + } |
| +} |
| + |
| +// TestSystemHostsUsedInventoryVerbsThroughTheBinary: import posts the |
| +// file's listings, close-fleet the fleet, complete nothing; each prints its |
| +// approved line. |
| +func TestSystemHostsUsedInventoryVerbsThroughTheBinary(t *testing.T) { |
| + bin := buildCarlos(t) |
| + var mu sync.Mutex |
| + bodies := map[string]string{} |
| + mux := http.NewServeMux() |
| + record := func(name string) func(http.ResponseWriter, *http.Request) []byte { |
| + return func(w http.ResponseWriter, r *http.Request) []byte { |
| + b, _ := io.ReadAll(r.Body) |
| + mu.Lock() |
| + bodies[name] = string(b) |
| + mu.Unlock() |
| + w.Header().Set("Content-Type", "application/json") |
| + return b |
| + } |
| + } |
| + mux.HandleFunc("POST /api/cli/system/hosts-used/import", func(w http.ResponseWriter, r *http.Request) { |
| + record("import")(w, r) |
| + w.Write([]byte(`{"results":[{"target":"box:b1","ok":true,"hosts":2,"unmapped":0}]}`)) |
| + }) |
| + mux.HandleFunc("POST /api/cli/system/hosts-used/close-fleet", func(w http.ResponseWriter, r *http.Request) { |
| + record("close-fleet")(w, r) |
| + w.Write([]byte(`{"mode":"activating","closed":["fleet:fx"]}`)) |
| + }) |
| + mux.HandleFunc("POST /api/cli/system/hosts-used/complete", func(w http.ResponseWriter, r *http.Request) { |
| + record("complete")(w, r) |
| + w.Write([]byte(`{"mode":"active","marks":12}`)) |
| + }) |
| + ts := httptest.NewServer(mux) |
| + t.Cleanup(ts.Close) |
| + dir := t.TempDir() |
| + credPath := filepath.Join(dir, "credentials") |
| + if err := os.WriteFile(credPath, []byte(`{"version":1,"credentials":[{"console":"`+ts.URL+`","address":"paul@keymail.dev","token":"tok"}]}`), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + listing := filepath.Join(dir, "scan.jsonl") |
| + if err := os.WriteFile(listing, []byte(`{"target":"b1","kind":"box","ok":true,"entries":["a.example.com.db"]}`+"\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + run := func(args ...string) string { |
| + cmd := exec.Command(bin, append([]string{"system", "hosts-used"}, args...)...) |
| + cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+credPath) |
| + cmd.Dir = t.TempDir() |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("%v: %v\n%s", args, err, out) |
| + } |
| + return string(out) |
| + } |
| + if out := run("import", listing); !strings.Contains(out, "box:b1: 2 hostnames\n") { |
| + t.Fatalf("import printed:\n%s", out) |
| + } |
| + if out := run("close-fleet", "fx"); !strings.Contains(out, "fleet fx is closed. new instances can't be placed on it\n") { |
| + t.Fatalf("close-fleet printed:\n%s", out) |
| + } |
| + if out := run("complete"); !strings.Contains(out, "the hostname history is complete. 12 hostnames recorded\n") { |
| + t.Fatalf("complete printed:\n%s", out) |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if !strings.Contains(bodies["import"], `"entries":["a.example.com.db"]`) || bodies["close-fleet"] != `{"fleet":"fx"}` { |
| + t.Fatalf("bodies = %v", bodies) |
| + } |
| +} |