Rework merge B to offline activation (Paul's cut on #404)
The live window is gone: no begin/cancel, no activating mode, no drain counts, no in-process seed-worker counter, no online invalidate door. - console hosts-used roster | activate | invalidate (the console binary, on the console's box, console stopped). console serve holds an exclusive flock on <CONSOLE_DB>.serve.lock for its life; activate and invalidate take it or refuse (N1), and a second console refuses to start (N8). activate reads the console database directly and refuses on pending lifetime rows (N3), unfinished moves or seeds (N4), a roster changed since it was taken, target names and each region's and fleet's targets (N5), a listing off the roster (N6), a non-fleet closed (N7), a missing, failed or unmappable listing (C7-C9), or claims or Phase 1 (C11); then marks, writes the floor and active (B8). invalidate is the operator's, offline (C12, D4, B9). - The console runs the start-up check before serving a data-kind create; until it passes, data-kind creates get S5 and the region switch is off. A breach this process finds latches invalidated under the admission lock before it pages (Task 7 r2's P1). - Kept: merge A's marking, S1-S4, recovery marking, apps place's S3 cut, accounts migrate never writing a data-kind record once the history exists (absent S6, identical: no write, different: refused), the floor read before the registry opens. - carlos system hosts-used is status alone (A1, A3-A5, A12, A13). - README, spec §3b and the plan's rework paragraph; the approved rework copy appended to nearest-region-never-reuse-b.md.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
48 files changed,
+1,668
−2,769
README.md+34 −32accounts.go+12 −18accounts_hostsused.go+44 −10accounts_record_sequence_test.go+36 −12cmd/console/hostsused.go+152 −0cmd/console/main.go+15 −1cmd/console/servelock_test.go+66 −0cmd/console/servelock_unix.go+33 −0cmd/console/servelock_windows.go+16 −0docs/superpowers/notes/census-proposal-nearest-region-b.md+3 −7docs/superpowers/notes/copy/nearest-region-never-reuse-b.md+69 −0docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md+4 −0docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md+4 −0internal/console/apiinstanceimport.go+4 −5internal/console/apiinstancemove.go+0 −18internal/console/apiinstancemove_offline.go+0 −18internal/console/apiinstances.go+3 −6internal/console/apiinstanceseed.go+3 −3internal/console/apisidecars.go+3 −5internal/console/authcli.go+0 −9internal/console/claim_invariant_fixtures_test.go+1 −37internal/console/claim_invariant_test.go+0 −2internal/console/fleets.go+0 −8internal/console/hostsused.go+131 −203internal/console/hostsused_activate.go+468 −0internal/console/hostsused_activate_test.go+351 −0internal/console/hostsused_active_test.go+6 −1internal/console/hostsused_inventory.go+0 −540internal/console/hostsused_inventory_test.go+0 −406internal/console/hostsused_listings.go+0 −109internal/console/hostsused_status.go+57 −0internal/console/hostsused_tripwire.go+24 −69internal/console/hostsused_tripwire_test.go+37 −23internal/console/hostsused_window.go+0 −311internal/console/hostsused_window_test.go+0 −419internal/console/hostsused_writers_test.go+6 −7internal/console/regioncandidates.go+1 −1internal/console/svcroutes_test.go+2 −8internal/console/testdata/claim-authority-sites.txt+1 −0internal/console/testdata/claim-routes.txt+0 −6internal/provision/hostsused.go+12 −19internal/provision/hostsused_test.go+4 −4internal/provision/nearest_region_b_census_test.go+30 −55internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv+4 −7system.go+1 −7system_hostsused.go+18 −194system_hostsused_test.go+12 −188
CI passed — run details
diff --git a/README.md b/README.md| index 6d8f241ee..01ac8bcff 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -341,41 +341,43 @@ the same name would read it. The console keeps a history of every hostname |
| that may hold data, under `control/hosts-used/`, and refuses to create one |
| again. Static sites and services hold no data and are not recorded. |
| -The history has four modes, which `carlos system hosts-used status` shows: |
| +The history has three modes. `carlos system hosts-used status` shows the |
| +current mode: |
| -- incomplete, from the release until the history is completed. New |
| - hostnames are recorded and nothing is refused. App regions stay off. |
| -- activating, while the maintenance window below is open. New instances, |
| - moves and placement changes are paused. |
| +- incomplete, from when this release is installed until the history is |
| + completed. New hostnames are recorded and nothing is refused. App |
| + regions stay off. |
| - active. A recorded hostname is refused everywhere, and app regions can |
| be turned on. |
| - invalidated, when the console finds a record the history does not |
| cover, or an operator invalidates it. New instances are refused until |
| - the window is run again. |
| - |
| -**Completing the history.** Complete it once per deployment, starting in |
| -dev. It needs a maintenance window. Announce it because new instances, |
| -moves and placement changes are refused while it is open. |
| - |
| -1. Run `carlos system hosts-used begin`. The console fixes its list of |
| - regions, pools, fleets and boxes from this moment. |
| -2. Run `carlos system hosts-used status` until every count is 0. Work |
| - admitted before the window finishes on its own. |
| -3. Scan every target on the list with `scripts/hosts-used-scan-aws.sh` |
| - (in infra) and run `carlos system hosts-used import <file>`. Every |
| - target needs a listing that imports successfully. |
| -4. A fleet that cannot be scanned can be closed instead, with |
| - `carlos system hosts-used close-fleet <fleet>`. A closed fleet takes no |
| - new instances. Regions and pools cannot be closed. |
| -5. Run `carlos system hosts-used complete`. It refuses while anything is |
| - unsettled, unscanned or unreadable, and reports the problem. On success |
| - the mode is active and the floor is written. |
| -6. Or run `carlos system hosts-used cancel` at any point. Nothing is lost: |
| - the hostnames recorded so far stay recorded. |
| - |
| -Two limits. A deployment runs one console process; a second console would |
| -not see the first one's mode. And a region, pool or fleet added after |
| -completion takes no new instances until its own listing is imported. |
| + the history is completed again. |
| + |
| +**Completing the history.** Complete the history once per deployment, |
| +starting in dev, on the console's box with the console stopped. Announce |
| +the work: nothing can be created, changed or deleted through the console |
| +while it is stopped. |
| + |
| +1. Stop the console. |
| +2. Run `console hosts-used roster -o roster.json`. It lists every box and |
| + bucket the regions and fleets use. |
| +3. Scan every target on the roster with `scripts/hosts-used-scan-aws.sh` |
| + (in infra). |
| +4. Run `console hosts-used activate -roster roster.json -listings |
| + scan.jsonl`. A fleet that cannot be scanned can be closed instead, with |
| + `-close-fleet <fleet>`. A closed fleet takes no new instances. Regions |
| + cannot be closed. It refuses while the console is running, while |
| + anything is still settling or any target is unscanned or unreadable, or |
| + when the roster has changed since it was taken, and reports the problem. |
| + On success the mode is active and the floor is written. |
| +5. Start the console. Before it serves a new instance it checks that the |
| + history covers every record. Until that check passes, new instances |
| + are refused and app regions stay off. |
| + |
| +There are two limits. A deployment runs one console process: `console |
| +serve` holds a lock beside its database, and a second process refuses to |
| +start. A region or fleet added after completion takes no new instances |
| +until the history is completed again. |
| **The history's floor.** Completing writes the floor to |
| `control/hosts-used/@floor`. The floor is the release that completed the |
| @@ -386,8 +388,8 @@ the floor, and `carlos accounts migrate` refuses to run below it. |
| **Restores.** Restoring the console's database alone is safe. A restore of |
| the control bucket must keep every object under `control/hosts-used/`. If |
| -any objects may have been dropped, run `carlos system hosts-used |
| -invalidate` and complete the history again. |
| +any objects may have been dropped, stop the console, run `console |
| +hosts-used invalidate`, and complete the history again. |
| **Turning app regions on.** In order: |
diff --git a/accounts.go b/accounts.go| index 02e1a2feb..b3b41134d 100644 |
| --- a/accounts.go |
| +++ b/accounts.go |
| @@ -338,6 +338,14 @@ func runAccountsMigrate(args []string) { |
| if !release.ValidAccount(*to) { |
| log.Fatalf("accounts migrate: %q is not an account sqid", *to) |
| } |
| + // The hostname history (accounts_hostsused.go): the floor before any |
| + // write (opening the registry migrates its schema), and the mode every |
| + // record copy is checked against. |
| + histStore := openStore() |
| + history, err := readMigrationHistoryNow(context.Background(), histStore) |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| r, err := registry.Open(*regPath) |
| if err != nil { |
| log.Fatal(err) |
| @@ -354,7 +362,7 @@ func runAccountsMigrate(args []string) { |
| dst := release.AppPrefix(*to, *app) |
| ctx := context.Background() |
| - store := openStore() |
| + store := histStore |
| // Where the app's objects are RIGHT NOW. This is the whole hazard of the |
| // verb, so it is resolved the way the runtime resolves them and not by |
| @@ -363,12 +371,6 @@ func runAccountsMigrate(args []string) { |
| if err := validateMigrationRecords(ctx, store, plan); err != nil { |
| log.Fatal(err) |
| } |
| - // The hostname history (accounts_hostsused.go): the floor before any |
| - // write, and the mode every record copy is checked against. |
| - history, err := readMigrationHistoryNow(ctx, store) |
| - if err != nil { |
| - log.Fatal(err) |
| - } |
| if len(plan) == 0 { |
| mutedf(os.Stdout, "nothing under %s — nothing to copy\n", release.AppPrefix(srcAcct, *app)) |
| } |
| @@ -433,19 +435,11 @@ func runAccountsMigrate(args []string) { |
| } |
| continue |
| } |
| - if err := history.beforeRecord(ctx, store, c.to, body); err != nil { |
| + copied, err := copyMigrationRecord(ctx, store, history, c.to, body) |
| + if err != nil { |
| log.Fatal(err) |
| } |
| - if _, err := putMigrationObject(ctx, store, c.to, body); err != nil { |
| - cur, _, gerr := store.Get(ctx, c.to) |
| - if gerr != nil { |
| - log.Fatalf("accounts migrate: write %s: %v", c.to, err) |
| - } |
| - if string(cur) != string(body) { |
| - log.Fatalf("accounts migrate: %s already exists with different content — refusing to\n"+ |
| - "overwrite an immutable release object. Nothing has been deleted; work out which\n"+ |
| - "of the two is the real %s before going further.", c.to, *app) |
| - } |
| + if !copied { |
| mutedf(os.Stdout, "already copied %s -> %s\n", c.from, c.to) |
| continue |
| } |
diff --git a/accounts_hostsused.go b/accounts_hostsused.go| index b9ccdc7a4..f3d188239 100644 |
| --- a/accounts_hostsused.go |
| +++ b/accounts_hostsused.go |
| @@ -97,12 +97,18 @@ func migrationRecordHost(key string, body []byte) (host string, data, ok bool) { |
| return host, true, true |
| } |
| +// errAlreadyCopied is a data-kind record whose identical copy is already at |
| +// its destination once the history exists: nothing is written. |
| +var errAlreadyCopied = errors.New("already copied") |
| + |
| // beforeRecord is the check before a record key is copied to key. Exempt |
| -// kinds and other objects pass. Before the window opens, a data kind's |
| -// hostname is marked create-only (a mark already there passes). From the |
| -// window on, a data-kind record is never created at an absent destination |
| -// (S6); a present one is left to the create-only copy, which reports an |
| -// identical one as already copied and refuses a different one. |
| +// kinds and other objects pass. Before the history is active, a data kind's |
| +// hostname is marked create-only (a mark already there passes) and the copy |
| +// goes ahead. Once the history exists (active or invalidated) the verb never |
| +// writes a data-kind record: an absent destination is S6, an identical one |
| +// is errAlreadyCopied, and a different one is left to the verb's own |
| +// refusal, which also writes nothing. No write follows a check that could |
| +// go stale, so a record deleted meanwhile is never recreated. |
| func (h *migrationHistory) beforeRecord(ctx context.Context, store release.Store, key string, body []byte) error { |
| if !provision.IsRecordKey(key) { |
| return nil |
| @@ -112,17 +118,21 @@ func (h *migrationHistory) beforeRecord(ctx context.Context, store release.Store |
| return nil |
| } |
| if h.mode != provision.HostsModeIncomplete { |
| - // A present destination is the copy's own business: identical is |
| - // "already copied", different is the verb's own refusal. |
| - _, _, err := store.Get(ctx, key) |
| - if errors.Is(err, os.ErrNotExist) { |
| + cur, _, err := store.Get(ctx, key) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| name := host |
| if !ok { |
| name = key |
| } |
| return errors.New(name + ": not migrated. Its destination record is gone, and recreating it would reuse a hostname that held data.") |
| + case err != nil: |
| + return err |
| + case string(cur) == string(body): |
| + return errAlreadyCopied |
| } |
| - return err |
| + return fmt.Errorf("accounts migrate: %s already exists with different content — refusing to\n"+ |
| + "overwrite it. Nothing has been deleted; work out which of the two is the real one before going further.", key) |
| } |
| if !ok { |
| return fmt.Errorf("accounts migrate: %s names no hostname, so its copy cannot be recorded", key) |
| @@ -130,3 +140,27 @@ func (h *migrationHistory) beforeRecord(ctx context.Context, store release.Store |
| _, err := provision.MarkHostUsed(ctx, store, provision.HostUse{Host: host, Kind: "instance", Source: "accounts migrate", At: time.Now().UTC()}) |
| return err |
| } |
| + |
| +// copyMigrationRecord is the verb's step for one non-pointer object: the |
| +// history's check, then the create-only copy. copied is false for an object |
| +// already at its destination with the same bytes. |
| +func copyMigrationRecord(ctx context.Context, store release.Store, h *migrationHistory, key string, body []byte) (copied bool, err error) { |
| + if err := h.beforeRecord(ctx, store, key, body); errors.Is(err, errAlreadyCopied) { |
| + return false, nil |
| + } else if err != nil { |
| + return false, err |
| + } |
| + if _, err := putMigrationObject(ctx, store, key, body); err != nil { |
| + cur, _, gerr := store.Get(ctx, key) |
| + if gerr != nil { |
| + return false, fmt.Errorf("accounts migrate: write %s: %w", key, err) |
| + } |
| + if string(cur) != string(body) { |
| + return false, fmt.Errorf("accounts migrate: %s already exists with different content — refusing to\n"+ |
| + "overwrite an immutable release object. Nothing has been deleted; work out which\n"+ |
| + "of the two is the real one before going further.", key) |
| + } |
| + return false, nil |
| + } |
| + return true, nil |
| +} |
diff --git a/accounts_record_sequence_test.go b/accounts_record_sequence_test.go| index aa1a83e62..ea7f5582c 100644 |
| --- a/accounts_record_sequence_test.go |
| +++ b/accounts_record_sequence_test.go |
| @@ -5,6 +5,8 @@ import ( |
| "context" |
| "errors" |
| "os" |
| + "path/filepath" |
| + "strings" |
| "testing" |
| "github.com/carlosframework/platform/internal/provision" |
| @@ -135,7 +137,8 @@ func setHistory(t *testing.T, store release.Store, mode string) { |
| } |
| } |
| -// migrateOne is the verb's record step: the history's check, then the copy. |
| +// migrateOne is the verb's record step (copyMigrationRecord), with the |
| +// history read as the verb reads it. |
| func migrateOne(t *testing.T, store release.Store, key string, body []byte) error { |
| t.Helper() |
| ctx := context.Background() |
| @@ -143,10 +146,7 @@ func migrateOne(t *testing.T, store release.Store, key string, body []byte) erro |
| if err != nil { |
| return err |
| } |
| - if err := h.beforeRecord(ctx, store, key, body); err != nil { |
| - return err |
| - } |
| - _, err = putMigrationObject(ctx, store, key, body) |
| + _, err = copyMigrationRecord(ctx, store, h, key, body) |
| return err |
| } |
| @@ -179,19 +179,43 @@ func TestMigrateRefusesResurrection(t *testing.T) { |
| } |
| func TestMigrateIdenticalDestinationPasses(t *testing.T) { |
| - store := release.NewDirStore(t.TempDir()) |
| + inner := release.NewDirStore(t.TempDir()) |
| key := provision.RecordKey("cac", "app", "shop.example.com") |
| body := migrateRecordBody("shop.example.com", "", false) |
| - if err := migrateOne(t, store, key, body); err != nil { |
| + if err := migrateOne(t, inner, key, body); err != nil { |
| t.Fatal(err) |
| } |
| - setHistory(t, store, provision.HostsModeActive) |
| - h, err := readMigrationHistory(context.Background(), store, "v9.9.9", "") |
| - if err != nil { |
| + setHistory(t, inner, provision.HostsModeActive) |
| + store := &orderStore{Store: inner} |
| + if err := migrateOne(t, store, key, body); err != nil { |
| + t.Fatalf("an identical present destination = %v, want it to pass", err) |
| + } |
| + // Once the history exists, a data-kind record is never written: a |
| + // delete between the check and a write could not resurrect it. |
| + if len(store.puts) != 0 { |
| + t.Fatalf("puts once active = %v, want none", store.puts) |
| + } |
| + if err := migrateOne(t, store, key, migrateRecordBody("shop.example.com", "", true)); err == nil || !strings.Contains(err.Error(), "already exists with different content") { |
| + t.Fatalf("a different present destination = %v, want the verb's refusal", err) |
| + } |
| +} |
| + |
| +// TestMigrateFloorPrecedesTheRegistry: below the floor the verb refuses |
| +// before it opens (and so migrates) the registry. |
| +func TestMigrateFloorPrecedesTheRegistry(t *testing.T) { |
| + bin := buildCarlos(t) |
| + dir := t.TempDir() |
| + bucket := filepath.Join(dir, "bucket") |
| + if _, err := provision.WriteHostsFloor(context.Background(), release.NewDirStore(bucket), provision.HostsFloor{Version: "v999.0.0", Commit: "x"}, ""); err != nil { |
| t.Fatal(err) |
| } |
| - if err := h.beforeRecord(context.Background(), store, key, body); err != nil { |
| - t.Fatalf("an identical present destination = %v, want it to pass", err) |
| + reg := filepath.Join(dir, "registry.db") |
| + out, err := runCarlosEnv(t, bin, []string{"accounts", "migrate", "-registry", reg, "-app", "shop", "-to", "cac"}, "CARLOS_DEPLOYMENT_DIR="+bucket) |
| + if err == nil || !strings.Contains(out, "this carlos is older than the hostname history's floor, v999.0.0. update carlos, then run it again.") { |
| + t.Fatalf("migrate below the floor: %v\n%s", err, out) |
| + } |
| + if _, err := os.Stat(reg); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the registry was created before the refusal: %v", err) |
| } |
| } |
diff --git a/cmd/console/hostsused.go b/cmd/console/hostsused.go| new file mode 100644 |
| index 000000000..afa77c455 |
| --- /dev/null |
| +++ b/cmd/console/hostsused.go |
| @@ -0,0 +1,152 @@ |
| +package main |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "log" |
| + "os" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/moves" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// console hosts-used roster | activate | invalidate (nearest-region |
| +// never-reuse; Paul's cut on #404): the hostname history is made active, and |
| +// invalidated by an operator, offline, on the console's box with the |
| +// console stopped. activate and invalidate take the console's serve lock |
| +// (servelock_*.go) for their whole run, which `console serve` holds while |
| +// it serves, so they refuse while it runs and it cannot start under them. |
| + |
| +// The approved rework strings (nearest-region-never-reuse-b.md, the rework list). |
| +const ( |
| + msgConsoleRunning = "the console is running. stop it, then run this again" // N1 |
| + msgServeLockHeld = "another console, or a hosts-used command, holds %s. stop it, then start the console" // N8 |
| + msgRosterWritten = "roster written to %s: %d targets to scan" // N2 |
| + msgActivated = "the hostname history is complete. %d hostnames recorded" // B8 |
| + msgInvalidated = "the hostname history is invalidated. new instances are refused until a fresh inventory completes" // B9 |
| +) |
| + |
| +// multiFlag is a repeatable string flag. |
| +type multiFlag []string |
| + |
| +func (m *multiFlag) String() string { return strings.Join(*m, ",") } |
| +func (m *multiFlag) Set(v string) error { *m = append(*m, v); return nil } |
| + |
| +func hostsActivationFromEnv() console.HostsActivation { |
| + return console.HostsActivation{ |
| + DB: openConsoleDB(), |
| + Releases: openStore(nil), |
| + Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"), |
| + HostClaim: hostClaimEnabled(os.Getenv), |
| + MovesEnabled: moves.Enabled(os.Getenv), |
| + } |
| +} |
| + |
| +// holdServeLock proves the console is stopped, or exits. |
| +func holdServeLock() *os.File { |
| + f, err := takeServeLock(envOr("CONSOLE_DB", "/data/console/console.db")) |
| + if errors.Is(err, errServeLockHeld) { |
| + log.Fatal(msgConsoleRunning) |
| + } |
| + if err != nil { |
| + log.Fatalf("console hosts-used: take the serve lock: %v", err) |
| + } |
| + return f |
| +} |
| + |
| +// readListings reads the adapter's output: one TargetListing per line. |
| +func readListings(r io.Reader) ([]provision.TargetListing, error) { |
| + dec := json.NewDecoder(bufio.NewReader(r)) |
| + var out []provision.TargetListing |
| + for { |
| + var l provision.TargetListing |
| + if err := dec.Decode(&l); errors.Is(err, io.EOF) { |
| + return out, nil |
| + } else if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, l) |
| + } |
| +} |
| + |
| +func runHostsUsed(args []string) { |
| + if len(args) == 0 { |
| + usage() |
| + } |
| + ctx := context.Background() |
| + switch args[0] { |
| + case "roster": |
| + fs := flag.NewFlagSet("hosts-used roster", flag.ExitOnError) |
| + out := fs.String("o", "", "the roster file to write") |
| + fs.Parse(args[1:]) |
| + if *out == "" || fs.NArg() != 0 { |
| + usage() |
| + } |
| + a := console.HostsActivation{Releases: openStore(nil), Registry: envOr("CARLOS_REGISTRY", "/data/registry.db")} |
| + r, err := a.Roster(ctx) |
| + if err != nil { |
| + log.Fatalf("console hosts-used roster: %v", err) |
| + } |
| + b, err := json.MarshalIndent(r, "", " ") |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| + if err := os.WriteFile(*out, append(b, '\n'), 0o600); err != nil { |
| + log.Fatalf("console hosts-used roster: %v", err) |
| + } |
| + fmt.Printf(msgRosterWritten+"\n", *out, len(r.Targets)) |
| + case "activate": |
| + fs := flag.NewFlagSet("hosts-used activate", flag.ExitOnError) |
| + rosterPath := fs.String("roster", "", "the roster file the scan covered") |
| + listingsPath := fs.String("listings", "", "the scan output") |
| + var closeFleets multiFlag |
| + fs.Var(&closeFleets, "close-fleet", "a fleet to close instead of scanning (repeatable)") |
| + fs.Parse(args[1:]) |
| + if *rosterPath == "" || *listingsPath == "" || fs.NArg() != 0 { |
| + usage() |
| + } |
| + lock := holdServeLock() |
| + defer lock.Close() |
| + rb, err := os.ReadFile(*rosterPath) |
| + if err != nil { |
| + log.Fatalf("console hosts-used activate: %v", err) |
| + } |
| + var roster console.HostsRoster |
| + if err := json.Unmarshal(rb, &roster); err != nil { |
| + log.Fatalf("console hosts-used activate: %s: %v", *rosterPath, err) |
| + } |
| + lf, err := os.Open(*listingsPath) |
| + if err != nil { |
| + log.Fatalf("console hosts-used activate: %v", err) |
| + } |
| + listings, err := readListings(lf) |
| + lf.Close() |
| + if err != nil { |
| + log.Fatalf("console hosts-used activate: %s: %v", *listingsPath, err) |
| + } |
| + n, err := hostsActivationFromEnv().Activate(ctx, roster, listings, closeFleets) |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| + fmt.Printf(msgActivated+"\n", n) |
| + case "invalidate": |
| + if len(args) != 1 { |
| + usage() |
| + } |
| + lock := holdServeLock() |
| + defer lock.Close() |
| + if err := hostsActivationFromEnv().Invalidate(ctx); err != nil { |
| + log.Fatal(err) |
| + } |
| + fmt.Println(msgInvalidated) |
| + default: |
| + usage() |
| + } |
| +} |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index af33302af..94ed457f0 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -209,6 +209,8 @@ func main() { |
| runMember(os.Args[2:]) |
| case "migrate-app": |
| migrateApp(os.Args[2:]) |
| + case "hosts-used": |
| + runHostsUsed(os.Args[2:]) |
| case "owners": |
| st := openConsoleDB() |
| owners, err := st.Owners() |
| @@ -231,7 +233,8 @@ func main() { |
| func usage() { |
| log.Fatal("usage: console serve | grant [-operator] <address> [<app>] | revoke [-operator] <address> [<app>] | owners | " + |
| "member -add|-remove <address> <account-sqid> [-role owner|member] | member -list <account-sqid> | " + |
| - "migrate-app -app <app> -to <sqid> [-from <sqid>]") |
| + "migrate-app -app <app> -to <sqid> [-from <sqid>] | " + |
| + "hosts-used roster -o <file> | hosts-used activate -roster <file> -listings <file> [-close-fleet <fleet>]... | hosts-used invalidate") |
| } |
| // migrateApp completes the second half of `carlos accounts migrate`: that |
| @@ -305,6 +308,17 @@ func migrateApp(args []string) { |
| } |
| func serve() { |
| + // The serve lock (servelock_*.go), held for the life of the process: |
| + // the offline hosts-used verbs need the console stopped, and refuse |
| + // while this is held; a second console on this database refuses here. |
| + switch lock, err := takeServeLock(envOr("CONSOLE_DB", "/data/console/console.db")); { |
| + case errors.Is(err, errServeLockHeld): |
| + log.Fatalf(msgServeLockHeld, envOr("CONSOLE_DB", "/data/console/console.db")+".serve.lock") |
| + case err != nil: |
| + log.Printf("console: the serve lock: %v (serving without it)", err) |
| + default: |
| + defer lock.Close() |
| + } |
| origin := strings.TrimSuffix(os.Getenv("CONSOLE_ORIGIN"), "/") |
| if origin == "" { |
| log.Fatal("set CONSOLE_ORIGIN (e.g. https://platform.carlosframework.com)") |
diff --git a/cmd/console/servelock_test.go b/cmd/console/servelock_test.go| new file mode 100644 |
| index 000000000..cc426c3fb |
| --- /dev/null |
| +++ b/cmd/console/servelock_test.go |
| @@ -0,0 +1,66 @@ |
| +//go:build !windows |
| + |
| +package main |
| + |
| +import ( |
| + "errors" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The serve lock is exclusive across processes: a second taker is refused |
| +// while the first holds it, and gets it once the first has gone. |
| +func TestServeLockIsExclusive(t *testing.T) { |
| + db := filepath.Join(t.TempDir(), "console.db") |
| + first, err := takeServeLock(db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Another process (flock locks belong to the open file, so a second |
| + // open in this process is refused just the same). |
| + if _, err := takeServeLock(db); !errors.Is(err, errServeLockHeld) { |
| + t.Fatalf("a second take = %v, want held", err) |
| + } |
| + if out, err := exec.Command("flock", "-n", db+".serve.lock", "true").CombinedOutput(); err == nil { |
| + t.Fatalf("another process took the lock: %s", out) |
| + } else if strings.Contains(err.Error(), "executable file not found") { |
| + t.Log("no flock(1) here; the in-process check stands") |
| + } |
| + first.Close() |
| + again, err := takeServeLock(db) |
| + if err != nil { |
| + t.Fatalf("the lock after release = %v", err) |
| + } |
| + again.Close() |
| +} |
| + |
| +// TestHostsUsedVerbsNeedTheConsoleStopped: the built binary's invalidate |
| +// refuses while the serve lock is held (a running console), and reaches the |
| +// history once it is free. |
| +func TestHostsUsedVerbsNeedTheConsoleStopped(t *testing.T) { |
| + dir := t.TempDir() |
| + bin := filepath.Join(dir, "console") |
| + if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil { |
| + t.Fatalf("build: %v\n%s", err, out) |
| + } |
| + db := filepath.Join(dir, "console.db") |
| + run := func() string { |
| + cmd := exec.Command(bin, "hosts-used", "invalidate") |
| + cmd.Env = []string{"CONSOLE_DB=" + db, "CARLOS_DEPLOYMENT_DIR=" + filepath.Join(dir, "bucket"), "CARLOS_REGISTRY=" + filepath.Join(dir, "registry.db"), "HOME=" + dir} |
| + out, _ := cmd.CombinedOutput() |
| + return string(out) |
| + } |
| + lock, err := takeServeLock(db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if out := run(); !strings.Contains(out, "the console is running. stop it, then run this again") { |
| + t.Fatalf("invalidate with the console running printed:\n%s", out) |
| + } |
| + lock.Close() |
| + if out := run(); !strings.Contains(out, "The hostname history is not active, so there is nothing to invalidate.") { |
| + t.Fatalf("invalidate with the console stopped printed:\n%s", out) |
| + } |
| +} |
diff --git a/cmd/console/servelock_unix.go b/cmd/console/servelock_unix.go| new file mode 100644 |
| index 000000000..8512f63f3 |
| --- /dev/null |
| +++ b/cmd/console/servelock_unix.go |
| @@ -0,0 +1,33 @@ |
| +//go:build !windows |
| + |
| +package main |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "syscall" |
| +) |
| + |
| +// errServeLockHeld is a lock another process holds: a serving console, or |
| +// an offline hosts-used verb. |
| +var errServeLockHeld = errors.New("held") |
| + |
| +// takeServeLock takes the console's serve lock, <db>.serve.lock, exclusive |
| +// and without waiting, and holds it for the life of the process (the kernel |
| +// drops it when the process exits, so it is never stale). `console serve` |
| +// holds it while it serves; the offline hosts-used verbs take it to prove |
| +// the console is stopped. |
| +func takeServeLock(db string) (*os.File, error) { |
| + f, err := os.OpenFile(db+".serve.lock", os.O_CREATE|os.O_RDWR, 0o600) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| + f.Close() |
| + if errors.Is(err, syscall.EWOULDBLOCK) { |
| + return nil, errServeLockHeld |
| + } |
| + return nil, err |
| + } |
| + return f, nil |
| +} |
diff --git a/cmd/console/servelock_windows.go b/cmd/console/servelock_windows.go| new file mode 100644 |
| index 000000000..1fe3fad25 |
| --- /dev/null |
| +++ b/cmd/console/servelock_windows.go |
| @@ -0,0 +1,16 @@ |
| +//go:build windows |
| + |
| +package main |
| + |
| +import ( |
| + "errors" |
| + "os" |
| +) |
| + |
| +var errServeLockHeld = errors.New("held") |
| + |
| +// takeServeLock has no implementation on Windows, where the console is not |
| +// deployed: serving goes on without it, and the offline verbs refuse. |
| +func takeServeLock(db string) (*os.File, error) { |
| + return nil, errors.New("the serve lock is not supported on Windows") |
| +} |
diff --git a/docs/superpowers/notes/census-proposal-nearest-region-b.md b/docs/superpowers/notes/census-proposal-nearest-region-b.md| index 604b87fe1..af9e3bd8c 100644 |
| --- a/docs/superpowers/notes/census-proposal-nearest-region-b.md |
| +++ b/docs/superpowers/notes/census-proposal-nearest-region-b.md |
| @@ -1,10 +1,10 @@ |
| # Census approval: nearest-region-b |
| -Ruling `census-ruling-nearest-region-b`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| +Ruling `census-ruling-nearest-region-b`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| -| `accounts.go` `runAccountsMigrate` | body | unchanged (9) | reads the hostname history once before any write (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store the verb already opened) and refuses below the floor; before each record copy beforeRecord GETs the destination key or Puts a create-only mark under control/hosts-used/; no new kind of read, no path or input a tenant, app or box agent can name | |
| +| `accounts.go` `runAccountsMigrate` | body | unchanged (9) | reads the hostname history before it opens the registry (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store, the one store the verb uses) and refuses below the floor; each record copy goes through copyMigrationRecord, which GETs the destination key or Puts a create-only mark under control/hosts-used/ and, once the history exists, never writes a data-kind record; no new kind of read, no path or input a tenant, app or box agent can name | |
| Envelopes re-pinned: `.`, `internal/layout`, `internal/provision`. |
| @@ -14,10 +14,6 @@ Recorded dispositions, which each change must still satisfy: |
| - `accounts.go` `runAccountsMigrate`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1,J4;basis=route-and-input |
| -New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| - |
| -- new `system_hostsused.go:readListingsFile`: reads +file:ReadFile; written legacy, accepted-legacy, frozen |
| - |
| -Seal: `0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af` → `ae97d10a4270ebd65636b0b45781a728009b8d32fb74d88dc164287d05515bcc`. |
| +Seal: `0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af` → `1afc79e244319487755197b17845083150e83409058d81ac78d70aca3f3f8543`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md b/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md| index c6bf844f4..0de96c296 100644 |
| --- a/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md |
| +++ b/docs/superpowers/notes/copy/nearest-region-never-reuse-b.md |
| @@ -124,3 +124,72 @@ Changes to "Turning app regions on": |
| turning the switch on has no effect. |
| - in step 5: Use new probe hostnames every run. A probe hostname is |
| recorded once created, so it can never be created again. |
| + |
| + |
| +## Rework (offline activation): approved copy |
| + |
| +approved by delegated Luna pass on Paul's standing rule, 2026-10-26. Apply verbatim; placeholders are in angle brackets. These replace the window's strings (A2, A6-A11, B1-B7, C2-C6, C10, S7, S8, E4-E9 are removed from the product) and the README paragraphs named below. |
| + |
| +Placeholders in angle brackets. Lines printed by the console binary's offline verbs follow the CLI voice (lower case after a full stop). |
| + |
| +## N. Console binary (console hosts-used ...) |
| +N1 refusal while the console runs: the console is running. stop it, then run this again |
| +N2 roster written: roster written to <file>: <n> targets to scan |
| +N3 pending lifetime rows: <n> instance creates or deletes are still settling. start the console until they finish, stop it, then run this again |
| +N4 unfinished moves or seeds: <n> moves or seeded instances have not finished. start the console until they finish, stop it, then run this again |
| +N5 roster changed since it was taken: the regions, fleets or boxes changed since the roster was taken. take the roster again and scan its targets again |
| +N6 a listing for a target off the roster: <target> is not on the roster |
| +N7 -close-fleet on something that is not a roster fleet: <name> is not a fleet on the roster. regions can't be closed |
| +N8 console serve refusing to start under the lock: another console, or a hosts-used command, holds <path>. stop it, then start the console |
| +N9 usage (appended to the console binary's usage line): hosts-used roster -o <file> | hosts-used activate -roster <file> -listings <file> [-close-fleet <fleet>]... | hosts-used invalidate |
| +N10 flag help: -o "the roster file to write"; -roster "the roster file the scan covered"; -listings "the scan output"; -close-fleet "a fleet to close instead of scanning (repeatable)" |
| + |
| +Reused unchanged (already approved): B8, B9 (printed by activate, invalidate), C1, C7, C8, C9, C11, C12 (activate/invalidate refusals), D4 (the offline invalidation's reason), S5 (also while the start-up check has not passed). |
| + |
| +Removed from the product: A2, A6-A11, B1-B7, C2-C6, C10, S7, S8, E4-E9. |
| + |
| +## README (replaces the approved F text in these paragraphs; everything else in F stays verbatim) |
| + |
| +The history has three modes. `carlos system hosts-used status` shows the |
| +current mode: |
| + |
| +- incomplete, from when this release is installed until the history is |
| + completed. New hostnames are recorded and nothing is refused. App |
| + regions stay off. |
| +- active. A recorded hostname is refused everywhere, and app regions can |
| + be turned on. |
| +- invalidated, when the console finds a record the history does not |
| + cover, or an operator invalidates it. New instances are refused until |
| + the history is completed again. |
| + |
| +**Completing the history.** Complete the history once per deployment, |
| +starting in dev, on the console's box with the console stopped. Announce |
| +the work: nothing can be created, changed or deleted through the console |
| +while it is stopped. |
| + |
| +1. Stop the console. |
| +2. Run `console hosts-used roster -o roster.json`. It lists every box and |
| + bucket the regions and fleets use. |
| +3. Scan every target on the roster with `scripts/hosts-used-scan-aws.sh` |
| + (in infra). |
| +4. Run `console hosts-used activate -roster roster.json -listings |
| + scan.jsonl`. A fleet that cannot be scanned can be closed instead, with |
| + `-close-fleet <fleet>`. A closed fleet takes no new instances. Regions |
| + cannot be closed. It refuses while the console is running, while |
| + anything is still settling or any target is unscanned or unreadable, or |
| + when the roster has changed since it was taken, and reports the problem. |
| + On success the mode is active and the floor is written. |
| +5. Start the console. Before it serves a new instance it checks that the |
| + history covers every record. Until that check passes, new instances |
| + are refused and app regions stay off. |
| + |
| +There are two limits. A deployment runs one console process: `console |
| +serve` holds a lock beside its database, and a second process refuses to |
| +start. A region or fleet added after completion takes no new instances |
| +until the history is completed again. |
| + |
| +Restores, last sentence (was "run `carlos system hosts-used invalidate` and complete the history again"): |
| +If any objects may have been dropped, stop the console, run `console |
| +hosts-used invalidate`, and complete the history again. |
| + |
| +(Pools no longer appear as roster targets, per the earlier copy question.) |
diff --git a/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md b/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md| index 9c427d97d..0b708c2bd 100644 |
| --- a/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md |
| +++ b/docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md |
| @@ -10,6 +10,10 @@ |
| **Spec:** docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md (rev 5, accepted 2026-10-26). Read §1-§5 before any task. |
| +## Rework (2026-10-26, Paul's cut on #404) |
| + |
| +Merge B's live window (Tasks 5 and 6 as written below) is replaced by offline activation (spec §3b): `console hosts-used roster`, `activate` and `invalidate` on the console's box with the console stopped, proved by its serve lock. Task 5 shrinks to the start-up gate and the console's serve lock; Task 6's import, close-fleet and complete become the offline `activate` (roster compared in full, including each region's and fleet's targets); Task 7 keeps S1-S4 and recovery marking, with the invalidation latch taken under the admission lock before paging; Task 8 keeps the tripwire, now run before any create is served, and loses the online invalidate door; Task 10 never writes a data-kind record once the history exists. Round history: Task 5 r1-r3, Task 6 r1-r2, Task 7 r1-r2, Task 8 r1, Task 10 r1 (all NOT READY; findings under docs/superpowers/notes/reviews/). The reworked branch gets one whole-branch review, a new round for the parts that changed. |
| + |
| ## Global Constraints |
| - The rule applies only with claims off (`cfg.HostClaim` false) and Phase 1 off (`CARLOS_MOVES_PHASE1`, moves/switch.go:6). `complete` refuses otherwise. |
diff --git a/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md| index 97f1d50e8..4d470675d 100644 |
| --- a/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md |
| +++ b/docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md |
| @@ -66,6 +66,10 @@ A one-time maintenance window wraps the inventory. It closes round 3's P1: a mar |
| **How consoles observe the mode.** The doors live on the console, and a deployment runs one console process (the same assumption self-serve moves plan 1 makes for `console.db`). The roll stops the old process before starting the new one. A console reads `@mode` (`incomplete`, `activating`, `active` or `invalidated`) once at start, before serving, and the doors change it in process and in the store together. Cost: one GET per console start and nothing per request. A second console process is out of scope. The README says so, and it would need its own mode read per create. |
| +## 3b. Offline activation (rev 6, Paul's cut on #404, 2026-10-26) |
| + |
| +The live window of §3a is cut. Its build (merge B) took Astra rounds that kept finding interleavings of one cause, the mode checked in one place and acted on in another: Task 5 r1-r3 (the drain, three times; budget spent), Task 6 r1-r2 (a fleet closure waiving an open target; stopping rule 2), Task 7 r1-r2 (a breach's creates; stopping rule 2), Task 8 r1, Task 10 r1 (findings under docs/superpowers/notes/reviews/). Activation and operator invalidation now run offline, on the console's box with the console stopped: `console hosts-used roster` lists what to scan; `console hosts-used activate` (holding the console's serve lock, a flock on `<CONSOLE_DB>.serve.lock` that `console serve` holds for its life, so it refuses while the console runs and the console cannot start under it) reads the console database directly, refuses on any pending lifetime row, any unfinished move or seed, a roster changed since it was taken (target names and each region's and fleet's targets), a missing, failed or unmappable listing, or claims or Phase 1 on, then marks, writes the floor and the active mode; `console hosts-used invalidate` is the operator's invalidation. There is no activating mode, no drain and no in-process counter. On start the console runs the tripwire before it serves a data-kind create; until it passes, data-kind creates are refused (S5) and the region switch stays off. `carlos accounts migrate` never writes a data-kind record once the history exists. Pools are no separate target: their boxes are on the roster through their edges files. |
| + |
| ## 4. Modes and the floor |
| | Mode | Behaviour | |
diff --git a/internal/console/apiinstanceimport.go b/internal/console/apiinstanceimport.go| index fc0ba83ec..caca774e4 100644 |
| --- a/internal/console/apiinstanceimport.go |
| +++ b/internal/console/apiinstanceimport.go |
| @@ -456,9 +456,9 @@ func (s *Server) handleAPIImportUpload(w http.ResponseWriter, r *http.Request) { |
| } |
| writeJSON(w, http.StatusAccepted, map[string]string{"state": "checking"}) |
| handedOver = true |
| - job := &importUpload{ctx: context.WithoutCancel(ctx), acct: acct, app: app, host: host, by: principal, |
| - id: seed.ID, dir: dir, spool: spool, release: releaseScratch, unit: detachUnit(ctx)} |
| - s.goSeedWorker(func() { s.runImportUpload(job) }) |
| + s.seedCopies.Add(1) |
| + go s.runImportUpload(&importUpload{ctx: context.WithoutCancel(ctx), acct: acct, app: app, host: host, by: principal, |
| + id: seed.ID, dir: dir, spool: spool, release: releaseScratch, unit: detachUnit(ctx)}) |
| } |
| // readImportRecord reads host's record under instanceStoreTimeout. |
| @@ -551,8 +551,7 @@ func (s *Server) spoolImport(w http.ResponseWriter, r *http.Request, spool strin |
| // leaves the record awaiting-upload, its spool is cleared at start, and |
| // the sweep aborts it (Plan 8). |
| func (s *Server) runImportUpload(j *importUpload) { |
| - // goSeedWorker releases s.seedCopies and the drain count after this |
| - // returns, so after every deferred step below. |
| + defer s.seedCopies.Done() |
| // Registered second, so it runs after every other deferred step: the |
| // abort, the spool's removal and the reservation's release. |
| defer j.unit.done() |
diff --git a/internal/console/apiinstancemove.go b/internal/console/apiinstancemove.go| index c78881270..5a51c6cb9 100644 |
| --- a/internal/console/apiinstancemove.go |
| +++ b/internal/console/apiinstancemove.go |
| @@ -413,15 +413,6 @@ func (s *Server) legacyHandleAPIInstanceMoveRequest(w http.ResponseWriter, r *ht |
| if !ok { |
| return |
| } |
| - // The hostname history's admission (hostsused.go): no move is admitted |
| - // while the activation window is open (S7); an admitted one is counted |
| - // until this handler returns. |
| - done, ref := s.admitMoveOrPlace(r.Context()) |
| - if ref != nil { |
| - writeDoorRefusalJSON(w, r, ref) |
| - return |
| - } |
| - defer done() |
| if s.refuseSeedMove(w, rec) { |
| return |
| } |
| @@ -578,15 +569,6 @@ func (s *Server) handleAPIInstanceMoveRequest(w http.ResponseWriter, r *http.Req |
| if !ok { |
| return |
| } |
| - // The hostname history's admission (hostsused.go): no move is admitted |
| - // while the activation window is open (S7); an admitted one is counted |
| - // until this handler returns. |
| - done, ref := s.admitMoveOrPlace(r.Context()) |
| - if ref != nil { |
| - writeDoorRefusalJSON(w, r, ref) |
| - return |
| - } |
| - defer done() |
| if s.refuseSeedMove(w, rec) { |
| return |
| } |
diff --git a/internal/console/apiinstancemove_offline.go b/internal/console/apiinstancemove_offline.go| index f57573f7f..21c2341c7 100644 |
| --- a/internal/console/apiinstancemove_offline.go |
| +++ b/internal/console/apiinstancemove_offline.go |
| @@ -620,15 +620,6 @@ func (s *Server) handleAPIInstanceOfflineStart(w http.ResponseWriter, r *http.Re |
| if !ok { |
| return |
| } |
| - // The hostname history's admission (hostsused.go): no move is admitted |
| - // while the activation window is open (S7); an admitted one is counted |
| - // until this handler returns. |
| - done, ref := s.admitMoveOrPlace(r.Context()) |
| - if ref != nil { |
| - writeDoorRefusalJSON(w, r, ref) |
| - return |
| - } |
| - defer done() |
| to, fleet, ok := s.offlineBeginChecks(w, r, d) |
| if !ok { |
| return |
| @@ -667,15 +658,6 @@ func (s *Server) handleAPIInstanceOfflineStage(w http.ResponseWriter, r *http.Re |
| if !ok { |
| return |
| } |
| - // The hostname history's admission (hostsused.go): no move is admitted |
| - // while the activation window is open (S7); an admitted one is counted |
| - // until this handler returns. |
| - done, ref := s.admitMoveOrPlace(r.Context()) |
| - if ref != nil { |
| - writeDoorRefusalJSON(w, r, ref) |
| - return |
| - } |
| - defer done() |
| to, fleet, ok := s.offlineBeginChecks(w, r, d) |
| if !ok { |
| return |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index b1d5d2472..2d6c2bdc0 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -1701,16 +1701,13 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| // The hostname history's admission (hostsused.go): a data-kind create |
| - // is refused while the activation window is open (S8) or the history is |
| - // invalidated (S5), and is otherwise counted until this handler returns, |
| - // which is what the window's drain waits on. Exempt kinds pass. |
| + // is refused once the history is invalidated, or while an active |
| + // history's start-up check has not passed (S5). Exempt kinds pass. |
| if rec.DataKind() { |
| - done, ref := s.admitDataCreate(r.Context(), rec.Host) |
| - if ref != nil { |
| + if ref := s.admitDataCreate(r.Context(), rec.Host); ref != nil { |
| writeDoorRefusalJSON(w, r, ref) |
| return |
| } |
| - defer done() |
| // Once active, only a region or fleet complete examined (S4). |
| if ref := s.hostsTargetRefusal(r.Context(), rec.Region); ref != nil { |
| writeDoorRefusalJSON(w, r, ref) |
diff --git a/internal/console/apiinstanceseed.go b/internal/console/apiinstanceseed.go| index ce85224b7..1126eed88 100644 |
| --- a/internal/console/apiinstanceseed.go |
| +++ b/internal/console/apiinstanceseed.go |
| @@ -240,7 +240,8 @@ func (s *Server) createFrom(w http.ResponseWriter, r *http.Request, c seedCreate |
| job := s.beginFrom(held, r, c, from) |
| if job != nil { |
| job.unit = detachUnit(r.Context()) |
| - s.goSeedWorker(func() { s.runFrom(job) }) |
| + s.seedCopies.Add(1) |
| + go s.runFrom(job) |
| } |
| held.flush(w, fmt.Sprintf("could not copy %s. Nothing was created. Try again.", strings.TrimSpace(from.Host))) |
| } |
| @@ -405,8 +406,7 @@ func (s *Server) beginFrom(w http.ResponseWriter, r *http.Request, c seedCreate, |
| // leaves the record reserving, its scratch is cleared at start, and the |
| // sweep aborts it (Plan 8). |
| func (s *Server) runFrom(j *fromCopy) { |
| - // goSeedWorker releases s.seedCopies and the drain count after this |
| - // returns, so after every deferred step below. |
| + defer s.seedCopies.Done() |
| // Registered second, so it runs after every other deferred step: the |
| // abort, the scratch's removal and the reservation's release. |
| defer j.unit.done() |
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go| index 21b94983a..fb4a891de 100644 |
| --- a/internal/console/apisidecars.go |
| +++ b/internal/console/apisidecars.go |
| @@ -346,14 +346,12 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request) |
| } |
| } |
| // The hostname history's admission (hostsused.go): a sidecar is always |
| - // a data kind. Refused while the window is open (S8) or the history is |
| - // invalidated (S5), and otherwise counted until this handler returns. |
| - done, ref := s.admitDataCreate(r.Context(), rec.Host) |
| - if ref != nil { |
| + // a data kind. Refused once the history is invalidated, or while an |
| + // active history's start-up check has not passed (S5). |
| + if ref := s.admitDataCreate(r.Context(), rec.Host); ref != nil { |
| writeDoorRefusalJSON(w, r, ref) |
| return |
| } |
| - defer done() |
| // Once active, only a region or fleet complete examined (S4). |
| if ref := s.hostsTargetRefusal(r.Context(), rec.Region); ref != nil { |
| writeDoorRefusalJSON(w, r, ref) |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index d83eecc27..da8dde151 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -1074,15 +1074,6 @@ func (s *Server) registerCLIRoutes() { |
| // The hostname history's status (nearest-region never-reuse, plan Task |
| // 4, hostsused.go): apiSystemRoller, read-only. |
| s.cliRoute("GET /api/cli/system/hosts-used/status", svcrole.Set{}, s.handleAPIHostsUsedStatus) |
| - // 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) |
| - // Invalidation (hostsused_tripwire.go): apiSystemRoller. |
| - s.cliRoute("POST /api/cli/system/hosts-used/invalidate", svcrole.Set{}, s.handleAPIHostsUsedInvalidate) |
| 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 a0218fbe2..f30449353 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -874,7 +874,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /api/cli/billing/problems": claimRead("operator view of billing problems; names no app"), |
| "route GET /api/cli/system/antivirus": claimRead("reads the deployment scanning setting"), |
| "route GET /api/cli/system/geoip": claimRead("operator view of the GeoIP pointer, box heartbeats and feed status (control/geoip/, status/, edge files); writes nothing"), |
| - "route GET /api/cli/system/hosts-used/status": claimRead("operator view of the hostname history: its mode, a count of control/hosts-used/ marks and the console's pending lifetime rows; writes nothing"), |
| + "route GET /api/cli/system/hosts-used/status": claimRead("operator view of the hostname history: its mode, a count of control/hosts-used/ marks, closed fleets and the floor; writes nothing"), |
| "route GET /api/cli/system/jobs/{id}": claimRead("reads a system update job"), |
| "route GET /api/cli/system/layout": claimRead("reads the deployment layout intent"), |
| "route GET /api/cli/system/pointer-digests": claimRead("operator report of each account's pointer digest marker and the channels whose head has no digest; writes nothing"), |
| @@ -1567,42 +1567,6 @@ var claimFixtures = map[string]claimFixture{ |
| // host claims: a claim console answers its 409 after the operator check |
| // and before it reads or writes anything. It names no app; the app here |
| // is the world's, whose foreign run proves nothing app-scoped moved. |
| - "route POST /api/cli/system/hosts-used/begin": {refused: &claimRefusalFixture{ |
| - apps: claimRefs("bab/titogo"), |
| - do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/begin", ""), |
| - status: http.StatusConflict, |
| - msg: msgHostsClaimsOn, |
| - }}, |
| - "route POST /api/cli/system/hosts-used/cancel": {refused: &claimRefusalFixture{ |
| - apps: claimRefs("bab/titogo"), |
| - do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/cancel", ""), |
| - 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/hosts-used/invalidate": {refused: &claimRefusalFixture{ |
| - apps: claimRefs("bab/titogo"), |
| - do: claimRefusedAPI(http.MethodPost, "/api/cli/system/hosts-used/invalidate", ""), |
| - 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/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 6c8b5f6c4..f4921d5e1 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -115,8 +115,6 @@ var claimUnsupported = map[string]string{ |
| "no operation gates both, so every transfer is refused", |
| claimMoveResolveUnavailableMsg: "the operator's door out of a stuck move (CARLOS_MOVES_PHASE1) has only its gate until " + |
| "the Moves resolution body lands; it answers this sentence and writes nothing", |
| - msgHostsClaimsOn: "the hostname history is bound to claims off and Phase 1 moves off (nearest-region never-reuse spec §1); " + |
| - "the window doors refuse after their operator check and before they read or write anything", |
| msgLifetimesClaimsOn: "instance lifetimes are the claims-off console's protocol (self-serve moves plan 1); " + |
| "the cutover door refuses after its operator check and before it reads or writes anything", |
| claimDBReadResidencyMsg: "a forwarded db read needs the root signer, which a host-claim console never uses for it " + |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index b0da2f0eb..f427c2b3f 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -576,14 +576,6 @@ func (s *Server) placeAppTarget(ctx context.Context, acct *Account, app, target |
| if mode, err := s.hostsMode(ctx); err == nil && (mode == provision.HostsModeActive || mode == provision.HostsModeInvalidated) { |
| return http.StatusConflict, msgPlacementFixed |
| } |
| - // The hostname history's admission (hostsused.go): no placement while |
| - // the activation window is open (S7); an admitted one is counted until |
| - // it returns. |
| - done, ref := s.admitMoveOrPlace(ctx) |
| - if ref != nil { |
| - return ref.Status, ref.Msg |
| - } |
| - defer done() |
| // A temporary app stays on the shared fleet at its own platform address |
| // (spec §4, ruling 5, Task 6 review fix): placement would move its |
| // already-provisioned estate onto a fleet an automatic purge never |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index 1d0a1001f..a7e1ba545 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -16,33 +16,36 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// The hostname history at the create doors (nearest-region never-reuse, |
| -// spec docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md |
| -// §2, plan Task 3). Every data-kind create writer marks its hostname |
| -// (provision.MarkHostUsed) after every other check of its door and |
| -// immediately before the call that persists the record: the create-only |
| -// record write with lifetimes off and for sidecars, BeginAllocation with |
| -// lifetimes on. Exempt kinds (static, service) never mark. |
| +// The hostname history in the serving console (nearest-region never-reuse, |
| +// spec docs/superpowers/specs/2026-10-26-nearest-region-without-claims-design.md). |
| // |
| -// Until the history is active (Task 6's complete) a mark that is already |
| -// there passes: today's behaviour, with the history filling in. Once active |
| -// it refuses the create (S1). A store that cannot be read or written |
| -// refuses in every mode (S2): a create is never persisted unmarked. |
| - |
| -// The approved strings (docs/superpowers/notes/copy/nearest-region-never-reuse.md). |
| -func msgHostUsed(host string) string { |
| +// Every data-kind create writer marks its hostname (provision.MarkHostUsed) |
| +// after every other check of its door and immediately before the call that |
| +// persists the record: the create-only record write with lifetimes off and |
| +// for sidecars, BeginAllocation with lifetimes on. Exempt kinds (static, |
| +// service) never mark. Until the history is active a mark already there |
| +// passes; once active it refuses the create (S1). A store that cannot be |
| +// read or written refuses in every mode (S2). |
| +// |
| +// The history is made active, and invalidated by an operator, only offline, |
| +// with the console stopped (hostsused_activate.go, Paul's cut on #404). The |
| +// serving console reads the mode once at start and runs the start-up check |
| +// (hostsused_tripwire.go) before it serves a data-kind create; it can move |
| +// an active history to invalidated itself (a record the history does not |
| +// cover, an unmarked allocation in recovery), never the other way. |
| + |
| +// The approved strings (docs/superpowers/notes/copy/nearest-region-never-reuse.md and -b.md). |
| +func msgHostUsed(host string) string { // S1 |
| return host + " is in use or has held an app's data before, so it can't be created. Choose another address." |
| } |
| -func msgHostUnchecked(host string) string { |
| +func msgHostUnchecked(host string) string { // S2 |
| return "Could not check whether " + host + " is free. Try again." |
| } |
| const ( |
| - msgHostsInvalidated = "New instances can't be created right now. Try again later." // S5 |
| - msgHostsActivating = "New instances can't be created during maintenance. Try again in a few minutes." // S8 |
| - msgHostsMovesPaused = "Moves and placement are paused for maintenance. Try again later." // S7 |
| - msgPlacementFixed = "An app's placement can't be changed once it exists." // S3 |
| + msgHostsInvalidated = "New instances can't be created right now. Try again later." // S5 |
| + msgPlacementFixed = "An app's placement can't be changed once it exists." // S3 |
| ) |
| // msgHostsTargetUnexamined is S4: target is a region's place name, or |
| @@ -51,7 +54,7 @@ func msgHostsTargetUnexamined(target string) string { |
| return "New instances can't be created on " + target + " yet. Choose another region." |
| } |
| -// D1-D3, the operator log line and the pages (approved, nearest-region-never-reuse-b.md). |
| +// D1-D3, the operator log line and the pages. |
| const msgAppRegionsWaitForHistory = "app regions are off until the hostname history is complete" |
| func msgHostsPageUncovered(key string) string { |
| @@ -63,38 +66,34 @@ func msgHostsPagePendingCreate(host string) string { |
| } |
| // hostsHistory is the process's copy of control/hosts-used/@mode. One |
| -// console process serves a deployment (spec §3a): the state is read once, |
| -// before the first door needs it, and changed only by this process's own |
| -// doors (hostsTransition), in the store and here together. |
| +// console process serves a deployment, and nothing else changes the mode |
| +// while it runs: activation and operator invalidation need it stopped. |
| type hostsHistory struct { |
| mu sync.Mutex |
| state provision.HostsState // Mode "" until read |
| etag string |
| - // admitted is the data-kind creates, moves and placements admitted and |
| - // still inside their handlers: the window's in-process drain count. |
| - admitted int |
| + // verified is the start-up check's result (hostsTripwire): until it |
| + // has passed, an active history admits no data-kind create and keeps |
| + // the region switch off. |
| + verified bool |
| // latched is a breach this process found and could not yet write: the |
| - // reason, held as invalidated whatever the store says, until a write |
| - // of the history's mode lands (invalidateHosts). |
| + // reason, held as invalidated whatever the store says, until the write |
| + // lands (invalidateHosts). |
| latched string |
| - // background is the seed copies and import uploads running detached |
| - // (goSeedWorker): counted until the worker returns, after its last |
| - // write, whatever its record says. |
| - background int |
| } |
| -// reset forgets the state, so the next caller reads the store again. A |
| -// console start, as far as the mode is concerned (tests use it to restart). |
| +// reset forgets the state, so the next caller reads the store again: a |
| +// console start, as far as the history goes (tests use it to restart). |
| func (h *hostsHistory) reset() { |
| h.mu.Lock() |
| - h.state, h.etag = provision.HostsState{}, "" |
| + h.state, h.etag, h.verified = provision.HostsState{}, "", false |
| h.mu.Unlock() |
| } |
| // loadHostsLocked reads the state if it has not been read. A failed read is |
| -// not held: the next caller reads again, and the caller refuses, never |
| -// defaulting. A console with no control store writes no records and reads |
| -// incomplete. The caller holds s.hosts.mu. |
| +// not held: the next caller reads again, and refuses meanwhile. A console |
| +// with no control store writes no records and reads incomplete. The caller |
| +// holds s.hosts.mu. |
| func (s *Server) loadHostsLocked(ctx context.Context) error { |
| if s.hosts.state.Mode != "" { |
| return nil |
| @@ -108,8 +107,8 @@ func (s *Server) loadHostsLocked(ctx context.Context) error { |
| return err |
| } |
| if s.hosts.latched != "" && st.Mode == provision.HostsModeActive { |
| - // A breach this process found and has not yet written: the store's |
| - // active is stale (Astra Task 7 r1). |
| + // A breach this process found and has not yet written: the |
| + // store's active is stale. |
| st = provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: s.hosts.latched, Closed: st.Closed} |
| } |
| s.hosts.state, s.hosts.etag = st, etag |
| @@ -132,20 +131,22 @@ func (s *Server) hostsState(ctx context.Context) (provision.HostsState, error) { |
| return s.hosts.state, nil |
| } |
| -// LoadHostsMode reads the history's state at console start, before the |
| -// console serves (spec §3a). A failure is logged and left for the first door |
| -// to read again, which refuses until it can. With app regions switched on |
| -// and the history not active, it says once that they stay off (spec §4). |
| +// LoadHostsMode reads the history's state at console start and, when it is |
| +// active, runs the start-up check before the console serves (spec §4). A |
| +// check that cannot finish keeps data-kind creates refused and the region |
| +// switch off, and runs again in the background until it does. With app |
| +// regions switched on and the history not active, it says once that they |
| +// stay off. |
| func (s *Server) LoadHostsMode(ctx context.Context) { |
| mode, err := s.hostsMode(ctx) |
| if err != nil { |
| - log.Printf("console: hosts used: read the mode at start: %v (the first door that needs it reads it again)", err) |
| + log.Printf("console: hosts used: read the mode at start: %v (data-kind creates are refused until it reads)", err) |
| + go s.RunHostsTripwire(context.WithoutCancel(ctx)) |
| + return |
| } |
| if mode == provision.HostsModeActive { |
| - // The start's tripwire (hostsused_tripwire.go): once here, and |
| - // again in the background until it finishes (RunHostsTripwire). |
| if err := s.hostsTripwire(ctx); err != nil { |
| - log.Printf("console: hosts used: the start's tripwire could not finish: %v (it runs again in the background)", err) |
| + log.Printf("console: hosts used: the start-up check could not finish: %v (data-kind creates are refused until it does; it runs again in the background)", err) |
| go s.RunHostsTripwire(context.WithoutCancel(ctx)) |
| } |
| mode, _ = s.hostsMode(ctx) |
| @@ -155,30 +156,34 @@ func (s *Server) LoadHostsMode(ctx context.Context) { |
| } |
| } |
| -// hostsCached is the held state, without a read: Mode is "" until some |
| -// door or the start has read it. For callers with no request to fail |
| -// (appRegionsOn, the region candidates), which read unknown as not active. |
| -func (s *Server) hostsCached() provision.HostsState { |
| +// hostsCached is the held state and the check's result, without a read. |
| +// For callers with no request to fail (appRegionsOn, the region |
| +// candidates), which read unknown as not active. |
| +func (s *Server) hostsCached() (provision.HostsState, bool) { |
| s.hosts.mu.Lock() |
| defer s.hosts.mu.Unlock() |
| - return s.hosts.state |
| + return s.hosts.state, s.hosts.verified |
| } |
| -// hostsActive reports whether the held mode is active. |
| -func (s *Server) hostsActive() bool { return s.hostsCached().Mode == provision.HostsModeActive } |
| +// hostsActive reports whether the held mode is active and the start-up |
| +// check has passed: the condition for the region switch. |
| +func (s *Server) hostsActive() bool { |
| + st, verified := s.hostsCached() |
| + return st.Mode == provision.HostsModeActive && verified |
| +} |
| // regionExamined reports whether a data-kind create may be placed in the |
| // record-vocabulary region code once active: the home ("") always, any |
| -// other region only if complete examined it. |
| +// other region only if activation examined it. |
| func regionExamined(st provision.HostsState, code string) bool { |
| return code == "" || slices.Contains(st.Examined, "region:"+code) |
| } |
| // hostsTargetRefusal is S4 (spec §3): once the history is active, a |
| -// data-kind create placed on a region or fleet complete did not examine, |
| +// data-kind create placed on a region or fleet activation did not examine, |
| // or on a closed fleet, is refused. Pools are not a separate target: their |
| -// boxes are scanned under their regions' codes. Before activation, and for |
| -// exempt kinds (the caller's check), nothing is refused. |
| +// boxes are on the roster through their edges files. Before activation, and |
| +// for exempt kinds (the caller's check), nothing is refused. |
| func (s *Server) hostsTargetRefusal(ctx context.Context, region string) *doorRefusal { |
| st, err := s.hostsState(ctx) |
| if err != nil || st.Mode != provision.HostsModeActive { |
| @@ -196,55 +201,88 @@ func (s *Server) hostsTargetRefusal(ctx context.Context, region string) *doorRef |
| return nil |
| } |
| +// admitDataCreate is a data-kind create door's admission: S5 once |
| +// invalidated, and S5 while an active history's start-up check has not |
| +// passed. An unreadable mode refuses with S2 for host, as the mark would. |
| +func (s *Server) admitDataCreate(ctx context.Context, host string) *doorRefusal { |
| + s.hosts.mu.Lock() |
| + defer s.hosts.mu.Unlock() |
| + if err := s.loadHostsLocked(ctx); err != nil { |
| + log.Printf("console: hosts used: read the mode to admit a create of %s: %v", host, err) |
| + return &doorRefusal{http.StatusServiceUnavailable, msgHostUnchecked(host)} |
| + } |
| + switch { |
| + case s.hosts.state.Mode == provision.HostsModeInvalidated, |
| + s.hosts.state.Mode == provision.HostsModeActive && !s.hosts.verified: |
| + return &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated} |
| + } |
| + return nil |
| +} |
| + |
| // hostsInvalidateRetry is how long a breach's unwritten invalidation waits |
| // before it is written again. |
| var hostsInvalidateRetry = 30 * time.Second |
| -// invalidateHosts moves an active history to invalidated (spec §4), in the |
| -// store and the process, and pages with reason whether or not the write |
| -// lands. Every data-kind create is refused (S5) until a fresh inventory |
| -// completes. A write that fails latches the breach in this process (creates |
| -// stay refused) and is retried until it lands (Astra Task 7 r1). |
| +var errHostsNotActive = errors.New("console: hosts used: the history is not active") |
| + |
| +// invalidateHosts moves an active history to invalidated (spec §4) when |
| +// this process finds a breach. Under the lock every admission takes, it |
| +// writes the mode; a write that fails latches invalidated in the process |
| +// before the lock is released, so no later create is admitted, and the |
| +// write is retried until it lands. Then it pages, whether or not the write |
| +// landed. |
| func (s *Server) invalidateHosts(ctx context.Context, reason string) error { |
| - err := s.writeInvalidated(ctx, reason) |
| - if err != nil && err.Error() == msgHostsNotActive { |
| + s.hosts.mu.Lock() |
| + if err := s.loadHostsLocked(ctx); err != nil || s.hosts.state.Mode != provision.HostsModeActive { |
| + if err == nil { |
| + err = errHostsNotActive |
| + } |
| + s.hosts.mu.Unlock() |
| + if !errors.Is(err, errHostsNotActive) { |
| + // The mode could not be read: the breach is still a breach. |
| + s.latchLocked(reason) |
| + go s.persistInvalidation(context.WithoutCancel(ctx), reason) |
| + s.pageInvalidation(ctx, reason) |
| + return nil |
| + } |
| return err |
| } |
| - log.Printf("console: %s", reason) |
| - if perr := alerting.Page(ctx, alerting.LevelIncident, reason, reason); perr != nil { |
| - log.Printf("console: hosts used: page the invalidation: %v", perr) |
| - } |
| - if err != nil { |
| - s.hosts.mu.Lock() |
| + next := provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: reason, Closed: s.hosts.state.Closed, |
| + Examined: s.hosts.state.Examined, FleetTargets: s.hosts.state.FleetTargets, RegionTargets: s.hosts.state.RegionTargets, |
| + At: time.Now().UTC()} |
| + etag, err := provision.WriteHostsState(ctx, s.cfg.Releases, next, s.hosts.etag) |
| + if err == nil { |
| + s.hosts.state, s.hosts.etag, s.hosts.latched = next, etag, "" |
| + } else { |
| s.hosts.latched = reason |
| - s.hosts.state = provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: reason} |
| + s.hosts.state = next |
| s.hosts.etag = "" |
| - s.hosts.mu.Unlock() |
| log.Printf("console: hosts used: write the invalidation: %v (new instances stay refused here; writing it again every %s)", err, hostsInvalidateRetry) |
| go s.persistInvalidation(context.WithoutCancel(ctx), reason) |
| } |
| + s.hosts.mu.Unlock() |
| + s.pageInvalidation(ctx, reason) |
| return nil |
| } |
| -// writeInvalidated writes invalidated over the store's active state. |
| -func (s *Server) writeInvalidated(ctx context.Context, reason string) error { |
| - _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| - if cur.Mode != provision.HostsModeActive { |
| - return cur, &doorRefusal{http.StatusConflict, msgHostsNotActive} |
| - } |
| - return provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: reason, Closed: cur.Closed}, nil |
| - }) |
| - if err != nil { |
| - return err |
| - } |
| - if ref != nil { |
| - return errors.New(ref.Msg) |
| +// latchLocked takes the lock and latches reason. |
| +func (s *Server) latchLocked(reason string) { |
| + s.hosts.mu.Lock() |
| + s.hosts.latched = reason |
| + s.hosts.state = provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: reason} |
| + s.hosts.etag = "" |
| + s.hosts.mu.Unlock() |
| +} |
| + |
| +func (s *Server) pageInvalidation(ctx context.Context, reason string) { |
| + log.Printf("console: %s", reason) |
| + if err := alerting.Page(ctx, alerting.LevelIncident, reason, reason); err != nil { |
| + log.Printf("console: hosts used: page the invalidation: %v", err) |
| } |
| - return nil |
| } |
| // persistInvalidation writes a latched breach until the store holds it, or |
| -// holds anything but active (an operator's re-inventory has begun). |
| +// holds anything but active. |
| func (s *Server) persistInvalidation(ctx context.Context, reason string) { |
| for { |
| time.Sleep(hostsInvalidateRetry) |
| @@ -256,12 +294,13 @@ func (s *Server) persistInvalidation(ctx context.Context, reason string) { |
| st, etag, err := provision.ReadHostsState(ctx, s.cfg.Releases) |
| if err == nil && st.Mode != provision.HostsModeActive { |
| s.hosts.latched = "" |
| - s.hosts.state, s.hosts.etag = provision.HostsState{}, "" // read again |
| + s.hosts.state, s.hosts.etag = st, etag |
| s.hosts.mu.Unlock() |
| return |
| } |
| if err == nil { |
| - next := provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: reason, Closed: st.Closed, At: time.Now().UTC()} |
| + next := st |
| + next.Mode, next.Reason, next.At = provision.HostsModeInvalidated, reason, time.Now().UTC() |
| if tag, werr := provision.WriteHostsState(ctx, s.cfg.Releases, next, etag); werr == nil { |
| s.hosts.latched = "" |
| s.hosts.state, s.hosts.etag = next, tag |
| @@ -310,114 +349,6 @@ func (s *Server) recoveryMark(ctx context.Context, a Allocation) bool { |
| return true |
| } |
| -// 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. 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() |
| - if err := s.loadHostsLocked(ctx); err != nil { |
| - return provision.HostsState{}, nil, err |
| - } |
| - st, ref := next(s.hosts.state) |
| - if ref != nil { |
| - return s.hosts.state, ref, nil |
| - } |
| - st.At = time.Now().UTC() |
| - etag, err := provision.WriteHostsState(ctx, s.cfg.Releases, st, s.hosts.etag) |
| - if err != nil { |
| - // 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 |
| - s.hosts.latched = "" // a mode write landed: the store is the truth again |
| - return st, nil, nil |
| -} |
| - |
| -// admit counts one admitted request until its done is called. |
| -func (s *Server) admitLocked() func() { |
| - s.hosts.admitted++ |
| - var once sync.Once |
| - return func() { |
| - once.Do(func() { |
| - s.hosts.mu.Lock() |
| - s.hosts.admitted-- |
| - s.hosts.mu.Unlock() |
| - }) |
| - } |
| -} |
| - |
| -// admitDataCreate is a data-kind create door's admission (spec §3a): S8 |
| -// while the window is open, S5 once invalidated, and otherwise a count the |
| -// window's drain waits on, held until done. An unreadable mode refuses with |
| -// S2 for host, as the mark would. |
| -func (s *Server) admitDataCreate(ctx context.Context, host string) (done func(), ref *doorRefusal) { |
| - s.hosts.mu.Lock() |
| - defer s.hosts.mu.Unlock() |
| - if err := s.loadHostsLocked(ctx); err != nil { |
| - log.Printf("console: hosts used: read the mode to admit a create of %s: %v", host, err) |
| - return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostUnchecked(host)} |
| - } |
| - switch s.hosts.state.Mode { |
| - case provision.HostsModeActivating: |
| - return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsActivating} |
| - case provision.HostsModeInvalidated: |
| - return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated} |
| - } |
| - return s.admitLocked(), nil |
| -} |
| - |
| -// admitMoveOrPlace is a move or placement door's admission: S7 while the |
| -// window is open, otherwise counted until done, as a create is. |
| -func (s *Server) admitMoveOrPlace(ctx context.Context) (done func(), ref *doorRefusal) { |
| - s.hosts.mu.Lock() |
| - defer s.hosts.mu.Unlock() |
| - if err := s.loadHostsLocked(ctx); err != nil { |
| - log.Printf("console: hosts used: read the mode to admit a move or placement: %v", err) |
| - return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsMovesPaused} |
| - } |
| - if s.hosts.state.Mode == provision.HostsModeActivating { |
| - return nil, &doorRefusal{http.StatusServiceUnavailable, msgHostsMovesPaused} |
| - } |
| - return s.admitLocked(), nil |
| -} |
| - |
| -// hostsAdmitted is the in-process drain count: requests admitted and still |
| -// in their handlers, and detached seed workers still running. |
| -func (s *Server) hostsAdmitted() int { |
| - s.hosts.mu.Lock() |
| - defer s.hosts.mu.Unlock() |
| - return s.hosts.admitted + s.hosts.background |
| -} |
| - |
| -// goSeedWorker is the one way a seed copy or an import upload runs detached |
| -// (Paul's ruling on Task 5: the drain's single enforcement point; |
| -// TestEverySeedWorkerIsCounted keeps it so). It holds s.seedCopies and the |
| -// hostname history's drain count from before the goroutine starts until |
| -// run returns, after the worker's last write. A record can say a seed has |
| -// ended (an abort) while its worker is still writing; this count does not |
| -// depend on the record. A console restart ends the worker, and the count |
| -// with it. |
| -func (s *Server) goSeedWorker(run func()) { |
| - s.seedCopies.Add(1) |
| - s.hosts.mu.Lock() |
| - s.hosts.background++ |
| - s.hosts.mu.Unlock() |
| - go func() { |
| - defer s.seedCopies.Done() |
| - defer func() { |
| - s.hosts.mu.Lock() |
| - s.hosts.background-- |
| - s.hosts.mu.Unlock() |
| - }() |
| - run() |
| - }() |
| -} |
| - |
| // hostsUsedError carries a mark refusal out of a create core that answers |
| // errors (createRecordWithLifetimeLocked, createRecordMarked); |
| // lifetimeCreateRefusal turns it back into its door refusal. |
| @@ -443,10 +374,7 @@ func (s *Server) markHost(ctx context.Context, u provision.HostUse) (markResult, |
| log.Printf("console: hosts used: read the mode for %s: %v", u.Host, err) |
| return 0, &doorRefusal{http.StatusServiceUnavailable, msgHostUnchecked(u.Host)} |
| } |
| - switch mode { |
| - case provision.HostsModeActivating: |
| - return 0, &doorRefusal{http.StatusServiceUnavailable, msgHostsActivating} |
| - case provision.HostsModeInvalidated: |
| + if mode == provision.HostsModeInvalidated { |
| return 0, &doorRefusal{http.StatusServiceUnavailable, msgHostsInvalidated} |
| } |
| if u.At.IsZero() { |
diff --git a/internal/console/hostsused_activate.go b/internal/console/hostsused_activate.go| new file mode 100644 |
| index 000000000..dc4b8fa72 |
| --- /dev/null |
| +++ b/internal/console/hostsused_activate.go |
| @@ -0,0 +1,468 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "reflect" |
| + "runtime/debug" |
| + "slices" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + boxlayout "github.com/carlosframework/platform/internal/layout" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "github.com/carlosframework/platform/internal/version" |
| +) |
| + |
| +// Offline activation and invalidation (nearest-region never-reuse; Paul's |
| +// cut on #404, 2026-10-26). The history is made active, or invalidated by an |
| +// operator, only with the console stopped, by the console binary's |
| +// `hosts-used` verbs (cmd/console), which hold the console's serve lock for |
| +// the whole run. Nothing serving changes records or the mode meanwhile, so |
| +// there is no window to drain: activation reads the console's database |
| +// directly, checks that the scan covers the roster as it is now, marks every |
| +// hostname its sources name, and writes the floor and the active mode. |
| + |
| +// The approved strings (docs/superpowers/notes/copy/nearest-region-never-reuse-b.md). |
| +const ( |
| + msgHostsAlreadyComplete = "The hostname history is already complete." // C1 |
| + msgHostsNotActive = "The hostname history is not active, so there is nothing to invalidate." // C12 |
| + msgHostsClaimsOn = "This console runs host claims or live moves, so the hostname history can't be completed." // C11 |
| + msgHostsPageOperator = "the hostname history is invalidated by an operator" // D4 |
| +) |
| + |
| +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 + "." |
| +} |
| + |
| +// The approved rework strings (nearest-region-never-reuse-b.md, the rework list). |
| +func msgHostsStillSettling(n int) string { // N3 |
| + return fmt.Sprintf("%d instance creates or deletes are still settling. start the console until they finish, stop it, then run this again", n) |
| +} |
| + |
| +func msgHostsWorkUnfinished(n int) string { // N4 |
| + return fmt.Sprintf("%d moves or seeded instances have not finished. start the console until they finish, stop it, then run this again", n) |
| +} |
| + |
| +const msgHostsRosterChanged = "the regions, fleets or boxes changed since the roster was taken. take the roster again and scan its targets again" // N5 |
| + |
| +func msgHostsNotOnRoster(target string) string { // N6 |
| + return target + " is not on the roster" |
| +} |
| + |
| +func msgHostsNotAFleet(name string) string { // N7 |
| + return name + " is not a fleet on the roster. regions can't be closed" |
| +} |
| + |
| +// unmappedSample is how many unmapped entries a refusal can name. |
| +const unmappedSample = 1 |
| + |
| +// HostsRoster is everything that may hold a hostname's data, as the console |
| +// sees it now: the listing targets ("box:<box>", "bucket:<bucket>") and, |
| +// for each region ("region:<placement code>") and fleet ("fleet:<name>"), |
| +// the targets it uses. The adapter scans its Targets; activation refuses if |
| +// the roster has changed since (a fleet's or region's target set is fixed |
| +// once recorded). |
| +type HostsRoster struct { |
| + Targets []string `json:"targets"` |
| + Regions map[string][]string `json:"regions"` |
| + Fleets map[string][]string `json:"fleets"` |
| +} |
| + |
| +// HostsActivation is what the offline verbs need: the console's database, |
| +// opened while the console is stopped, the deployment bucket, the registry |
| +// path and the two switches the history is bound to. |
| +type HostsActivation struct { |
| + DB *Store |
| + Releases release.Store |
| + Registry string |
| + HostClaim bool |
| + MovesEnabled bool |
| +} |
| + |
| +// Roster reads the roster now: the edges files (all of them, read and |
| +// parsed, or an error) and the console's fleet table. |
| +func (a HostsActivation) Roster(ctx context.Context) (HostsRoster, error) { |
| + snap, err := readEdgesSnapshot(ctx, a.Releases) |
| + if err != nil { |
| + return HostsRoster{}, fmt.Errorf("list the edges files: %w", err) |
| + } |
| + if !snap.Complete { |
| + return HostsRoster{}, errors.New("an edges file could not be read or parsed") |
| + } |
| + r := HostsRoster{Regions: map[string][]string{}, Fleets: map[string][]string{}} |
| + for _, f := range snap.Files { |
| + region := "region:" + f.Placement |
| + r.Regions[region] = append(r.Regions[region], "box:"+f.Box) |
| + if f.DataBucket != "" { |
| + r.Regions[region] = append(r.Regions[region], "bucket:"+f.DataBucket) |
| + } |
| + } |
| + if a.Registry != "" { |
| + reg, err := openRegistry(a.Registry) |
| + if err != nil { |
| + return HostsRoster{}, fmt.Errorf("open the registry: %w", err) |
| + } |
| + fleets, err := reg.ListFleets() |
| + if err != nil { |
| + return HostsRoster{}, fmt.Errorf("list the fleets: %w", err) |
| + } |
| + for _, fl := range fleets { |
| + key := "fleet:" + fl.Name |
| + r.Fleets[key] = []string{} |
| + if fl.Bucket != "" { |
| + r.Fleets[key] = append(r.Fleets[key], "bucket:"+fl.Bucket) |
| + } |
| + boxes, err := reg.ListFleetBoxes(fl.Name) |
| + if err != nil { |
| + return HostsRoster{}, fmt.Errorf("list fleet %s's boxes: %w", fl.Name, err) |
| + } |
| + for _, b := range boxes { |
| + if b.Status != "detached" { |
| + r.Fleets[key] = append(r.Fleets[key], "box:fleet/"+fl.Name+"/"+b.Label) |
| + } |
| + } |
| + } |
| + } |
| + var all []string |
| + for k, ts := range r.Regions { |
| + r.Regions[k] = sortedUnique(ts) |
| + all = append(all, ts...) |
| + } |
| + for k, ts := range r.Fleets { |
| + r.Fleets[k] = sortedUnique(ts) |
| + all = append(all, ts...) |
| + } |
| + r.Targets = sortedUnique(all) |
| + return r, nil |
| +} |
| + |
| +// excusedTargets is every listing target the closed fleets excuse: a target |
| +// only when every consumer of it, region or fleet, is a closed fleet. |
| +func (r HostsRoster) excusedTargets(closed []string) map[string]bool { |
| + out := map[string]bool{} |
| + for _, c := range closed { |
| + for _, t := range r.Fleets[c] { |
| + out[t] = true |
| + } |
| + } |
| + for _, ts := range r.Regions { |
| + for _, t := range ts { |
| + delete(out, t) |
| + } |
| + } |
| + for fleet, ts := range r.Fleets { |
| + if slices.Contains(closed, fleet) { |
| + continue |
| + } |
| + for _, t := range ts { |
| + delete(out, t) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +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 |
| +} |
| + |
| +func normalRoster(r HostsRoster) HostsRoster { |
| + n := HostsRoster{Targets: sortedUnique(r.Targets), Regions: map[string][]string{}, Fleets: map[string][]string{}} |
| + for k, v := range r.Regions { |
| + n.Regions[k] = sortedUnique(v) |
| + } |
| + for k, v := range r.Fleets { |
| + n.Fleets[k] = sortedUnique(v) |
| + } |
| + return n |
| +} |
| + |
| +// 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 |
| +} |
| + |
| +// recordFacts walks every raw record key under apps/ once: the hostnames |
| +// whose data a record may hold (source 1: whatever its app, account or body; |
| +// only a body that decodes to static or service is skipped, an instance |
| +// key's hostname is its key's, a sidecar's is its body's), and how many |
| +// records carry a move or a seed that has not ended. unmapped is a sidecar |
| +// key whose body names no hostname. |
| +func recordFacts(ctx context.Context, rel release.Store) (hosts []string, unfinished int, unmapped string, err error) { |
| + keys, err := rel.List(ctx, "apps/") |
| + if err != nil { |
| + return nil, 0, "", err |
| + } |
| + for _, k := range keys { |
| + if !provision.IsRecordKey(k) { |
| + continue |
| + } |
| + raw, _, err := rel.Get(ctx, k) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + return nil, 0, "", err |
| + } |
| + segs := strings.Split(k, "/") |
| + var body struct { |
| + Kind string `json:"kind"` |
| + Host string `json:"host"` |
| + Move json.RawMessage `json:"move"` |
| + Seed *struct { |
| + State string `json:"state"` |
| + } `json:"seed"` |
| + } |
| + derr := json.Unmarshal(raw, &body) |
| + if derr == nil && ((len(body.Move) > 0 && string(body.Move) != "null") || (body.Seed != nil && !seedEnded(body.Seed.State))) { |
| + unfinished++ |
| + } |
| + if segs[3] == "sidecars" { |
| + if derr != nil || !provision.ValidHostShape(body.Host) { |
| + return nil, 0, k, nil |
| + } |
| + hosts = append(hosts, body.Host) |
| + continue |
| + } |
| + host := strings.TrimSuffix(segs[4], ".json") |
| + if derr == nil && (body.Kind == "static" || body.Kind == "service") { |
| + continue |
| + } |
| + if !provision.ValidHostShape(host) { |
| + return nil, 0, k, nil |
| + } |
| + hosts = append(hosts, host) |
| + } |
| + return hosts, unfinished, "", 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 |
| +} |
| + |
| +// Activate makes the history active. scanned is the roster the adapter |
| +// scanned, listings its output, closeFleets the fleets not scanned. It |
| +// refuses (each error is the operator's sentence) with claims or Phase 1 |
| +// on, a history already active, any pending lifetime row, any unfinished |
| +// move or seed, a roster changed since scanned, a closed name that is not a |
| +// roster fleet, a listing of a target off the roster, a target with no good |
| +// listing, or any entry with no hostname. Then it marks every hostname from |
| +// the records, the lifetime tables and the listings, writes the floor and |
| +// the active mode, and answers how many hostnames the history holds. |
| +func (a HostsActivation) Activate(ctx context.Context, scanned HostsRoster, listings []provision.TargetListing, closeFleets []string) (int, error) { |
| + if a.HostClaim || a.MovesEnabled { |
| + return 0, errors.New(msgHostsClaimsOn) |
| + } |
| + st, etag, err := provision.ReadHostsState(ctx, a.Releases) |
| + if err != nil { |
| + return 0, fmt.Errorf("read the hostname history's mode: %w", err) |
| + } |
| + if st.Mode == provision.HostsModeActive { |
| + return 0, errors.New(msgHostsAlreadyComplete) |
| + } |
| + allocs, err := a.DB.PendingAllocations() |
| + if err != nil { |
| + return 0, fmt.Errorf("read the pending creates: %w", err) |
| + } |
| + rets, err := a.DB.PendingRetirements() |
| + if err != nil { |
| + return 0, fmt.Errorf("read the pending deletes: %w", err) |
| + } |
| + migs, err := a.DB.PendingMigrations() |
| + if err != nil { |
| + return 0, fmt.Errorf("read the pending migrations: %w", err) |
| + } |
| + if n := len(allocs) + len(rets) + len(migs); n > 0 { |
| + return 0, errors.New(msgHostsStillSettling(n)) |
| + } |
| + recordHosts, unfinished, unmappedKey, err := recordFacts(ctx, a.Releases) |
| + if err != nil { |
| + return 0, fmt.Errorf("read the records: %w", err) |
| + } |
| + if unfinished > 0 { |
| + return 0, errors.New(msgHostsWorkUnfinished(unfinished)) |
| + } |
| + now, err := a.Roster(ctx) |
| + if err != nil { |
| + return 0, fmt.Errorf("read the roster: %w", err) |
| + } |
| + if !reflect.DeepEqual(normalRoster(now), normalRoster(scanned)) { |
| + return 0, errors.New(msgHostsRosterChanged) |
| + } |
| + var closed []string |
| + for _, name := range closeFleets { |
| + key := "fleet:" + strings.TrimPrefix(name, "fleet:") |
| + if _, ok := now.Fleets[key]; !ok { |
| + return 0, errors.New(msgHostsNotAFleet(name)) |
| + } |
| + closed = append(closed, key) |
| + } |
| + closed = sortedUnique(closed) |
| + excused := now.excusedTargets(closed) |
| + onRoster := map[string]bool{} |
| + for _, t := range now.Targets { |
| + onRoster[t] = true |
| + } |
| + byTarget := map[string]provision.TargetListing{} |
| + for _, l := range listings { |
| + t := l.Kind + ":" + l.Target |
| + if !onRoster[t] { |
| + return 0, errors.New(msgHostsNotOnRoster(t)) |
| + } |
| + byTarget[t] = l |
| + } |
| + sources := map[string]string{} |
| + add := func(host, source string) { |
| + if _, ok := sources[host]; !ok { |
| + sources[host] = source |
| + } |
| + } |
| + var missing []string |
| + for _, t := range now.Targets { |
| + if excused[t] { |
| + continue |
| + } |
| + l, ok := byTarget[t] |
| + switch { |
| + case !ok: |
| + missing = append(missing, t) |
| + continue |
| + case !l.OK: |
| + return 0, errors.New(msgHostsListingFailed(t)) |
| + } |
| + var hosts, unmapped []string |
| + if l.Kind == "bucket" { |
| + hosts, unmapped = provision.HostsFromBucketListing(l.Prefix, l.Entries) |
| + } else { |
| + hosts, unmapped = boxlayout.HostsFromBoxListing(l.Entries) |
| + } |
| + if len(unmapped) > 0 { |
| + return 0, errors.New(msgHostsListingUnmapped(t, unmapped[0])) |
| + } |
| + for _, h := range hosts { |
| + add(h, t) |
| + } |
| + } |
| + if len(missing) > 0 { |
| + return 0, errors.New(msgHostsNoListing(missing)) |
| + } |
| + if unmappedKey != "" { |
| + return 0, errors.New(msgHostsListingUnmapped("records", unmappedKey)) |
| + } |
| + for _, h := range recordHosts { |
| + add(h, "records") |
| + } |
| + tableHosts, err := a.DB.LifetimeHosts() |
| + if err != nil { |
| + return 0, fmt.Errorf("read the lifetime tables: %w", err) |
| + } |
| + for _, h := range tableHosts { |
| + if !provision.ValidHostShape(h) { |
| + return 0, errors.New(msgHostsListingUnmapped("tables", h)) |
| + } |
| + add(h, "tables") |
| + } |
| + hosts := make([]string, 0, len(sources)) |
| + for h := range sources { |
| + hosts = append(hosts, h) |
| + } |
| + sort.Strings(hosts) |
| + at := time.Now().UTC() |
| + for _, h := range hosts { |
| + if _, err := provision.MarkHostUsed(ctx, a.Releases, provision.HostUse{Host: h, Kind: "inventory", Source: sources[h], At: at}); err != nil { |
| + return 0, fmt.Errorf("mark %s: %w", h, err) |
| + } |
| + } |
| + _, floorETag, err := provision.ReadHostsFloor(ctx, a.Releases) |
| + if err != nil { |
| + return 0, fmt.Errorf("read the floor: %w", err) |
| + } |
| + if _, err := provision.WriteHostsFloor(ctx, a.Releases, floorNow(), floorETag); err != nil { |
| + return 0, fmt.Errorf("write the floor: %w", err) |
| + } |
| + var examined []string |
| + for k := range now.Regions { |
| + examined = append(examined, k) |
| + } |
| + for k := range now.Fleets { |
| + if !slices.Contains(closed, k) { |
| + examined = append(examined, k) |
| + } |
| + } |
| + regionTargets := []string{} |
| + for _, ts := range now.Regions { |
| + regionTargets = append(regionTargets, ts...) |
| + } |
| + next := provision.HostsState{Mode: provision.HostsModeActive, Examined: sortedUnique(examined), Closed: closed, |
| + FleetTargets: now.Fleets, RegionTargets: sortedUnique(regionTargets), At: at} |
| + if _, err := provision.WriteHostsState(ctx, a.Releases, next, etag); err != nil { |
| + return 0, fmt.Errorf("write the active mode: %w", err) |
| + } |
| + keys, err := a.Releases.List(ctx, provision.HostsUsedPrefix) |
| + if err != nil { |
| + return len(hosts), nil |
| + } |
| + n := 0 |
| + for _, k := range keys { |
| + if host, ok := strings.CutSuffix(strings.TrimPrefix(k, provision.HostsUsedPrefix), ".json"); ok && provision.HostsUsedKey(host) == k { |
| + n++ |
| + } |
| + } |
| + return n, nil |
| +} |
| + |
| +// Invalidate moves an active history to invalidated (D4), offline. Leaving |
| +// it again needs a fresh activation. |
| +func (a HostsActivation) Invalidate(ctx context.Context) error { |
| + st, etag, err := provision.ReadHostsState(ctx, a.Releases) |
| + if err != nil { |
| + return fmt.Errorf("read the hostname history's mode: %w", err) |
| + } |
| + if st.Mode != provision.HostsModeActive { |
| + return errors.New(msgHostsNotActive) |
| + } |
| + next := st |
| + next.Mode, next.Reason, next.At = provision.HostsModeInvalidated, msgHostsPageOperator, time.Now().UTC() |
| + if _, err := provision.WriteHostsState(ctx, a.Releases, next, etag); err != nil { |
| + return fmt.Errorf("write the invalidated mode: %w", err) |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/hostsused_activate_test.go b/internal/console/hostsused_activate_test.go| new file mode 100644 |
| index 000000000..ac710c2f5 |
| --- /dev/null |
| +++ b/internal/console/hostsused_activate_test.go |
| @@ -0,0 +1,351 @@ |
| +package console |
| + |
| +// Offline activation and invalidation (nearest-region never-reuse; Paul's |
| +// cut on #404): HostsActivation, the core of `console hosts-used activate` |
| +// and `invalidate`, over a console stopped for it: its database read |
| +// directly, 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" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +// 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":{}}` |
| + key := "control/edges/" + box + ".json" |
| + _, etag, _ := st.Get(context.Background(), key) |
| + if _, err := st.Put(context.Background(), key, []byte(body), etag); 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 activation(l lifetimesFx) HostsActivation { |
| + return HostsActivation{DB: l.fx.st, Releases: l.fx.rel, Registry: l.fx.srv.cfg.Registry} |
| +} |
| + |
| +func rosterOf(t *testing.T, l lifetimesFx) HostsRoster { |
| + t.Helper() |
| + r, err := activation(l).Roster(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return r |
| +} |
| + |
| +// clean is a good listing of b1 and data-ie with these entries. |
| +func clean(box, bucket []string) []provision.TargetListing { |
| + return []provision.TargetListing{ |
| + {Target: "b1", Kind: "box", OK: true, Entries: box}, |
| + {Target: "data-ie", Kind: "bucket", Prefix: "instances", OK: true, Entries: bucket}, |
| + } |
| +} |
| + |
| +func activate(t *testing.T, l lifetimesFx, listings []provision.TargetListing, closeFleets ...string) (int, error) { |
| + t.Helper() |
| + return activation(l).Activate(context.Background(), rosterOf(t, l), listings, closeFleets) |
| +} |
| + |
| +func mustActivate(t *testing.T, l lifetimesFx, listings []provision.TargetListing, closeFleets ...string) int { |
| + t.Helper() |
| + n, err := activate(t, l, listings, closeFleets...) |
| + if err != nil { |
| + t.Fatalf("activate: %v", err) |
| + } |
| + // The console starts again: the mode is read and checked. |
| + l.fx.srv.hosts.reset() |
| + l.fx.srv.LoadHostsMode(context.Background()) |
| + return n |
| +} |
| + |
| +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 refusedWith(t *testing.T, err error, want string) { |
| + t.Helper() |
| + if err == nil || err.Error() != want { |
| + t.Fatalf("activate = %v, want %q", err, want) |
| + } |
| +} |
| + |
| +func TestActivateHistoricalOnlyNameAllowed(t *testing.T) { |
| + l := invFx(t) |
| + if n := mustActivate(t, l, clean([]string{"registry.db"}, nil)); n != 0 { |
| + t.Fatalf("marks = %d, want none", n) |
| + } |
| + 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) |
| + } |
| + if _, err := activate(t, l, clean(nil, nil)); err == nil || err.Error() != msgHostsAlreadyComplete { |
| + t.Fatalf("activate again = %v, want C1", err) |
| + } |
| +} |
| + |
| +func TestActivateLocalOnlyLeftoverRefused(t *testing.T) { |
| + l := invFx(t) |
| + mustActivate(t, l, clean([]string{"local.shop.example.com.db", "instances/nested.shop.example.com/nested.shop.example.com.db"}, nil)) |
| + 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 TestActivateMarksOrphanSeedSnapshot(t *testing.T) { |
| + l := invFx(t) |
| + mustActivate(t, l, clean(nil, []string{"seeds/orphan.shop.example.com/sd_1/snapshot.db", "instances/bucket.shop.example.com/0000/x.ltx", "moves/@lanes/uk/x"})) |
| + 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) |
| + } |
| + } |
| +} |
| + |
| +// TestActivateMarksRawRecordKeys: source 1 reads raw record keys, whatever |
| +// their app, account or body; only a body that decodes to an exempt kind is |
| +// skipped. |
| +func TestActivateMarksRawRecordKeys(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)) |
| + mustActivate(t, l, clean(nil, nil)) |
| + 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 TestActivateRefusals(t *testing.T) { |
| + for name, c := range map[string]struct { |
| + prep func(t *testing.T, l lifetimesFx) |
| + listings func() []provision.TargetListing |
| + want string |
| + }{ |
| + "undecodable sidecar": { |
| + prep: func(t *testing.T, l lifetimesFx) { |
| + l.fx.rel.Put(context.Background(), provision.SidecarRecordKey("bab", ltApp, "bot"), []byte("{not json"), "") |
| + }, |
| + listings: func() []provision.TargetListing { return clean(nil, nil) }, |
| + want: "The listing of records has entries with no hostname, such as apps/bab/shop/sidecars/bot.json.", |
| + }, |
| + "missing listing": { |
| + listings: func() []provision.TargetListing { return clean(nil, nil)[:1] }, |
| + want: "No listing has been imported for bucket:data-ie.", |
| + }, |
| + "failed listing": { |
| + listings: func() []provision.TargetListing { |
| + ls := clean(nil, nil) |
| + ls[0].OK, ls[0].Error = false, "ssm: timed out" |
| + return ls |
| + }, |
| + want: "The listing of box:b1 failed. Scan it again and import it.", |
| + }, |
| + "unmapped nested": { |
| + listings: func() []provision.TargetListing { return clean([]string{".offline-moves/Bad.Host/x"}, nil) }, |
| + want: "The listing of box:b1 has entries with no hostname, such as .offline-moves/Bad.Host.", |
| + }, |
| + "unmapped flat": { |
| + listings: func() []provision.TargetListing { return clean([]string{"Shop.example.com.db"}, nil) }, |
| + want: "The listing of box:b1 has entries with no hostname, such as Shop.example.com.db.", |
| + }, |
| + "off the roster": { |
| + listings: func() []provision.TargetListing { |
| + return append(clean(nil, nil), provision.TargetListing{Target: "b9", Kind: "box", OK: true}) |
| + }, |
| + want: msgHostsNotOnRoster("box:b9"), |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + l := invFx(t) |
| + if c.prep != nil { |
| + c.prep(t, l) |
| + } |
| + _, err := activate(t, l, c.listings()) |
| + refusedWith(t, err, c.want) |
| + if st, _, _ := provision.ReadHostsState(context.Background(), l.fx.rel); st.Mode != provision.HostsModeIncomplete { |
| + t.Fatalf("a refused activation left mode %s", st.Mode) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestActivateRefusesClaimsOrPhase1(t *testing.T) { |
| + l := invFx(t) |
| + a := activation(l) |
| + a.MovesEnabled = true |
| + _, err := a.Activate(context.Background(), rosterOf(t, l), clean(nil, nil), nil) |
| + refusedWith(t, err, msgHostsClaimsOn) |
| + a.MovesEnabled, a.HostClaim = false, true |
| + _, err = a.Activate(context.Background(), rosterOf(t, l), clean(nil, nil), nil) |
| + refusedWith(t, err, msgHostsClaimsOn) |
| +} |
| + |
| +// TestActivateRefusesRosterChange: a roster that changed since the scan, |
| +// including a box moved to another bucket with the set of target names |
| +// unchanged (Astra Task 6 r2), refuses. |
| +func TestActivateRefusesRosterChange(t *testing.T) { |
| + t.Run("a new box", func(t *testing.T) { |
| + l := invFx(t) |
| + scanned := rosterOf(t, l) |
| + putHostsEdges(t, l.fx.rel, "b2", "uk", "data-uk") |
| + _, err := activation(l).Activate(context.Background(), scanned, clean(nil, nil), nil) |
| + refusedWith(t, err, msgHostsRosterChanged) |
| + }) |
| + t.Run("consumers remapped", func(t *testing.T) { |
| + l := invFx(t) |
| + putHostsEdges(t, l.fx.rel, "b2", "uk", "data-ie") |
| + reg := openTestReg(t, l.fx) |
| + if _, err := reg.CreateFleet(registry.Fleet{Name: "fx", Account: "bab", Bucket: "data-b"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + scanned := rosterOf(t, l) |
| + putHostsEdges(t, l.fx.rel, "b2", "uk", "data-b") // same names, uk now uses fx's bucket |
| + _, err := activation(l).Activate(context.Background(), scanned, nil, []string{"fx"}) |
| + refusedWith(t, err, msgHostsRosterChanged) |
| + }) |
| +} |
| + |
| +// TestActivateRefusesPendingWork: a pending lifetime row in the console's |
| +// database, or a record whose move or seed has not ended, refuses until it |
| +// has settled. |
| +func TestActivateRefusesPendingWork(t *testing.T) { |
| + t.Run("allocation", func(t *testing.T) { |
| + lt := newLtOn(t) |
| + putHostsEdges(t, lt.fx.rel, "b1", "ie", "data-ie") |
| + lt.pendingCreate(t, "pending.shop.example.com", "record") |
| + _, err := activate(t, lt.lifetimesFx, clean(nil, nil)) |
| + refusedWith(t, err, msgHostsStillSettling(1)) |
| + recoverOn(t, lt.fx.srv) |
| + mustActivate(t, lt.lifetimesFx, clean(nil, nil)) |
| + }) |
| + for name, rec := range map[string]provision.Record{ |
| + "move": {Move: &provision.MoveState{ID: "mv_abcdefghijklmnopqrstuvwxyz", To: "uk", State: "requested", RequestedAt: time.Now().UTC()}}, |
| + "seed": {Seed: &provision.SeedSource{ID: "sd_abcdefghijklmnopqrstuvwxyz", Kind: seeds.KindImport, State: seeds.StateAwaitingUpload}}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + l := invFx(t) |
| + rec.Schema, rec.Host, rec.Slug, rec.App, rec.Account, rec.Channel, rec.CreatedAt = 1, "w.shop.example.com", "w", ltApp, "bab", "stable", time.Now().UTC() |
| + if err := provision.CreateRecord(context.Background(), l.fx.rel, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err := activate(t, l, clean(nil, nil)) |
| + refusedWith(t, err, msgHostsWorkUnfinished(1)) |
| + }) |
| + } |
| +} |
| + |
| +// TestActivateClosesAFleet: a closed fleet's own targets need no listing; a |
| +// bucket a region also uses still does, and the fleet takes no instance. |
| +func TestActivateClosesAFleet(t *testing.T) { |
| + l := invFx(t) |
| + reg := openTestReg(t, l.fx) |
| + if _, err := reg.CreateFleet(registry.Fleet{Name: "fx", Account: "bab", Bucket: "data-ie"}); 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) |
| + } |
| + _, err := activate(t, l, clean(nil, nil)[:1], "fx") |
| + refusedWith(t, err, "No listing has been imported for bucket:data-ie.") |
| + _, err = activate(t, l, clean(nil, nil), "ie") |
| + refusedWith(t, err, msgHostsNotAFleet("ie")) |
| + mustActivate(t, l, clean(nil, nil), "fx") |
| + 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) |
| + } |
| + if ref := l.fx.srv.hostsTargetRefusal(context.Background(), "fleet/fx"); ref == nil || ref.Msg != msgHostsTargetUnexamined("fleet fx") { |
| + t.Fatalf("a create on the closed fleet = %+v, want S4", ref) |
| + } |
| +} |
| + |
| +// TestReactivateFromInvalidated: an invalidated history becomes active |
| +// again only through a fresh activation. |
| +func TestReactivateFromInvalidated(t *testing.T) { |
| + l := invFx(t) |
| + mustActivate(t, l, clean(nil, nil)) |
| + if err := activation(l).Invalidate(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + l.fx.srv.hosts.reset() |
| + l.fx.srv.LoadHostsMode(context.Background()) |
| + if code, out := createAs(t, l, `{"host":"x.shop.example.com"}`); code != http.StatusServiceUnavailable || ltErr(out) != msgHostsInvalidated { |
| + t.Fatalf("create once invalidated = %d %s, want 503 S5", code, out) |
| + } |
| + mustActivate(t, l, clean(nil, nil)) |
| + if code, out := createAs(t, l, `{"host":"y.shop.example.com"}`); code != http.StatusCreated { |
| + t.Fatalf("create once active again = %d %s", code, out) |
| + } |
| +} |
| + |
| +func TestInvalidateOffline(t *testing.T) { |
| + l := invFx(t) |
| + if err := activation(l).Invalidate(context.Background()); err == nil || err.Error() != msgHostsNotActive { |
| + t.Fatalf("invalidate when incomplete = %v, want C12", err) |
| + } |
| + mustActivate(t, l, clean(nil, nil)) |
| + if err := activation(l).Invalidate(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + st, _, err := provision.ReadHostsState(context.Background(), l.fx.rel) |
| + if err != nil || st.Mode != provision.HostsModeInvalidated || st.Reason != msgHostsPageOperator { |
| + t.Fatalf("state = %+v %v, want invalidated with D4", st, err) |
| + } |
| +} |
| + |
| +func createAs(t *testing.T, l lifetimesFx, body string) (int, string) { |
| + t.Helper() |
| + code, _, out := rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", ltApp), l.member, body) |
| + return code, out |
| +} |
diff --git a/internal/console/hostsused_active_test.go b/internal/console/hostsused_active_test.go| index fadd057d5..4e426edee 100644 |
| --- a/internal/console/hostsused_active_test.go |
| +++ b/internal/console/hostsused_active_test.go |
| @@ -35,6 +35,11 @@ func forceHostsState(t *testing.T, srv *Server, st provision.HostsState) { |
| if got, err := srv.hostsMode(ctx); err != nil || got != st.Mode { |
| t.Fatalf("mode = %q %v, want %q", got, err, st.Mode) |
| } |
| + // As if the start-up check had passed (its own tests are in |
| + // hostsused_tripwire_test.go). |
| + srv.hosts.mu.Lock() |
| + srv.hosts.verified = true |
| + srv.hosts.mu.Unlock() |
| } |
| func dropMark(t *testing.T, st release.Store, host string) { |
| @@ -172,7 +177,6 @@ func TestAppRegionsNeedActive(t *testing.T) { |
| want bool |
| }{ |
| {provision.HostsModeIncomplete, false}, |
| - {provision.HostsModeActivating, false}, |
| {provision.HostsModeInvalidated, false}, |
| {provision.HostsModeActive, true}, |
| } { |
| @@ -274,6 +278,7 @@ func historyActive(srv *Server) { |
| defer srv.hosts.mu.Unlock() |
| srv.hosts.state = provision.HostsState{Mode: provision.HostsModeActive, |
| Examined: []string{"region:ie", "region:uk", "region:au", "region:us", "region:jp", "region:de", "region:ca"}} |
| + srv.hosts.verified = true |
| } |
| // TestFailedInvalidationStillRefuses (Astra Task 7 r1, P1): a breach found |
diff --git a/internal/console/hostsused_inventory.go b/internal/console/hostsused_inventory.go| deleted file mode 100644 |
| index 438e5af7a..000000000 |
| --- a/internal/console/hostsused_inventory.go |
| +++ /dev/null |
| @@ -1,540 +0,0 @@ |
| -package console |
| - |
| -import ( |
| - "bufio" |
| - "context" |
| - "encoding/json" |
| - "errors" |
| - "fmt" |
| - "io" |
| - "log" |
| - "net/http" |
| - "os" |
| - "runtime/debug" |
| - "slices" |
| - "sort" |
| - "strings" |
| - "time" |
| - |
| - boxlayout "github.com/carlosframework/platform/internal/layout" |
| - "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, []string, error) { |
| - snap, err := readEdgesSnapshot(ctx, s.cfg.Releases) |
| - if err != nil { |
| - return nil, nil, nil, fmt.Errorf("list the edges files: %w", err) |
| - } |
| - if !snap.Complete { |
| - return nil, nil, nil, errors.New("an edges file could not be read or parsed") |
| - } |
| - var roster, regionTargets []string |
| - for _, f := range snap.Files { |
| - roster = append(roster, "box:"+f.Box, "region:"+f.Placement) |
| - regionTargets = append(regionTargets, "box:"+f.Box) |
| - if f.DataBucket != "" { |
| - roster = append(roster, "bucket:"+f.DataBucket) |
| - regionTargets = append(regionTargets, "bucket:"+f.DataBucket) |
| - } |
| - } |
| - fleetTargets := map[string][]string{} |
| - if s.cfg.Registry != "" { |
| - reg, err := openRegistry(s.cfg.Registry) |
| - if err != nil { |
| - return nil, nil, nil, fmt.Errorf("open the registry: %w", err) |
| - } |
| - fleets, err := reg.ListFleets() |
| - if err != nil { |
| - return nil, 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, 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, sortedUnique(regionTargets), nil |
| -} |
| - |
| -// closedTargets is every listing target the closed fleets excuse, as fixed |
| -// when the window opened: a target only when every consumer of it is a |
| -// closed fleet. A target a region uses, or an open fleet, is never excused |
| -// (Astra Task 6 r1). |
| -func closedTargets(st provision.HostsState) map[string]bool { |
| - out := map[string]bool{} |
| - for _, c := range st.Closed { |
| - for _, t := range st.FleetTargets[c] { |
| - if !slices.Contains(st.RegionTargets, t) { |
| - out[t] = true |
| - } |
| - } |
| - } |
| - for fleet, targets := range st.FleetTargets { |
| - if slices.Contains(st.Closed, fleet) { |
| - continue |
| - } |
| - for _, t := range targets { |
| - delete(out, t) |
| - } |
| - } |
| - 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, Window: st.Window, 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 = boxlayout.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. |
| -type hostsSources struct { |
| - hosts map[string]string |
| -} |
| - |
| -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"` |
| - } |
| - 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") |
| - } |
| - 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. Pools are no separate |
| -// target: their boxes are on the roster through their edges files. |
| -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, st.Window) |
| - 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{}} |
| - 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) |
| - } |
| - } |
| - sort.Strings(examined) |
| - _, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| - // Only the window this complete checked (Astra Task 6 r1): one |
| - // cancelled and reopened meanwhile has its own drain and listings. |
| - if cur.Mode != provision.HostsModeActivating || cur.Window != st.Window { |
| - 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| deleted file mode 100644 |
| index abbb43a75..000000000 |
| --- a/internal/console/hostsused_inventory_test.go |
| +++ /dev/null |
| @@ -1,406 +0,0 @@ |
| -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) { |
| - for entry, sample := range map[string]string{ |
| - ".offline-moves/Bad.Host/x": ".offline-moves/Bad.Host", |
| - "Shop.example.com.db": "Shop.example.com.db", // a malformed flat name (Astra Task 6 r1, P2) |
| - } { |
| - t.Run(entry, func(t *testing.T) { |
| - l := invFx(t) |
| - begin(t, l) |
| - cleanImport(t, l, []string{entry}, nil) |
| - if code, out := complete(t, l); code != http.StatusConflict || out["error"] != "The listing of box:b1 has entries with no hostname, such as "+sample+"." { |
| - 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") |
| - } |
| -} |
| - |
| -// TestClosingAFleetKeepsASharedBucket (Astra Task 6 r1, P1 1): a bucket a |
| -// region also uses is never excused by closing a fleet that names it. |
| -func TestClosingAFleetKeepsASharedBucket(t *testing.T) { |
| - l := invFx(t) |
| - reg := openTestReg(t, l.fx) |
| - if _, err := reg.CreateFleet(registry.Fleet{Name: "fx", Account: "bab", Bucket: "data-ie"}); err != nil { |
| - t.Fatal(err) |
| - } |
| - begin(t, l) |
| - if code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCloseFleetURL, l.operator, `{"fleet":"fx"}`); code != http.StatusOK { |
| - t.Fatalf("close-fleet = %d %v", code, out) |
| - } |
| - if code, out := importLines(t, l, listingLine(t, provision.TargetListing{Target: "b1", Kind: "box", OK: true})); 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 with the shared bucket unscanned = %d %v, want C7", code, out) |
| - } |
| -} |
| - |
| -// TestStaleCompleteCannotActivateANewWindow (Astra Task 6 r1, P1 2): a |
| -// complete paused after its checks, while the window is cancelled and a new |
| -// one opened, cannot activate the new window. |
| -func TestStaleCompleteCannotActivateANewWindow(t *testing.T) { |
| - l := invFx(t) |
| - bucket := <Store{Store: l.fx.rel} |
| - l.fx.srv.cfg.Releases = bucket |
| - begin(t, l) |
| - cleanImport(t, l, nil, nil) |
| - gate, hook := pauseNth(t, "put", provision.HostsFloorKey, 1) |
| - bucket.setHook(hook) |
| - done := make(chan struct{}) |
| - var code int |
| - var out map[string]any |
| - go func() { |
| - defer close(done) |
| - code, out = complete(t, l) |
| - }() |
| - <-gate.entered |
| - bucket.setHook(nil) |
| - if c, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`); c != http.StatusOK { |
| - t.Fatalf("cancel = %d %v", c, st) |
| - } |
| - begin(t, l) |
| - gate.open() |
| - <-done |
| - if code != http.StatusConflict || out["error"] != msgHostsNoWindow { |
| - t.Fatalf("the stale complete = %d %v, want 409 C3", code, out) |
| - } |
| - if st := statusOf(t, l); st["mode"] != provision.HostsModeActivating || st["listings"] != float64(0) { |
| - t.Fatalf("status after the stale complete = %v, want the new window open with no listings", st) |
| - } |
| -} |
diff --git a/internal/console/hostsused_listings.go b/internal/console/hostsused_listings.go| deleted file mode 100644 |
| index b549e5bf0..000000000 |
| --- a/internal/console/hostsused_listings.go |
| +++ /dev/null |
| @@ -1,109 +0,0 @@ |
| -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"` |
| - Window string `json:"window"` |
| - 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 of window, by target. A listing of |
| -// another window is no listing of this one. |
| -func (s *Server) hostsListings(ctx context.Context, window string) (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) |
| - } |
| - if l.Window == window { |
| - 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_status.go b/internal/console/hostsused_status.go| new file mode 100644 |
| index 000000000..215c96e75 |
| --- /dev/null |
| +++ b/internal/console/hostsused_status.go |
| @@ -0,0 +1,57 @@ |
| +package console |
| + |
| +import ( |
| + "log" |
| + "net/http" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// hostsUsedStatus is GET /api/cli/system/hosts-used/status: the history's |
| +// mode, how many hostnames it has recorded (counted by listing the prefix, |
| +// a page per 1,000 keys; an operator action, never polled), the closed |
| +// fleets and the floor. |
| +type hostsUsedStatus struct { |
| + Mode string `json:"mode"` |
| + Marks int `json:"marks"` |
| + Closed []string `json:"closed,omitempty"` |
| + Floor *provision.HostsFloor `json:"floor,omitempty"` |
| +} |
| + |
| +// handleAPIHostsUsedStatus answers the status. apiSystemRoller, like the |
| +// other system doors. It writes nothing. |
| +func (s *Server) handleAPIHostsUsedStatus(w http.ResponseWriter, r *http.Request) { |
| + if _, _, ok := s.apiSystemRoller(w, r); !ok { |
| + return |
| + } |
| + if !s.systemBucket(w) { |
| + return |
| + } |
| + ctx := r.Context() |
| + fail := func(msg string, err error) { |
| + log.Printf("console: hosts used status: %s (%v)", msg, err) |
| + jsonError(w, http.StatusBadGateway, msg) |
| + } |
| + st, err := s.hostsState(ctx) |
| + if err != nil { |
| + fail("could not read the hostname history's mode. Try again.", err) |
| + return |
| + } |
| + keys, err := s.cfg.Releases.List(ctx, provision.HostsUsedPrefix) |
| + if err != nil { |
| + fail("could not list the hostname history. Try again.", err) |
| + return |
| + } |
| + out := hostsUsedStatus{Mode: st.Mode, Closed: st.Closed} |
| + for _, k := range keys { |
| + if host, ok := strings.CutSuffix(strings.TrimPrefix(k, provision.HostsUsedPrefix), ".json"); ok && provision.HostsUsedKey(host) == k { |
| + out.Marks++ |
| + } |
| + } |
| + if out.Floor, _, err = provision.ReadHostsFloor(ctx, s.cfg.Releases); err != nil { |
| + fail("could not read the hostname history's floor. Try again.", err) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
diff --git a/internal/console/hostsused_tripwire.go b/internal/console/hostsused_tripwire.go| index 512644391..1005146e6 100644 |
| --- a/internal/console/hostsused_tripwire.go |
| +++ b/internal/console/hostsused_tripwire.go |
| @@ -5,7 +5,6 @@ import ( |
| "encoding/json" |
| "errors" |
| "log" |
| - "net/http" |
| "os" |
| "strings" |
| "time" |
| @@ -13,24 +12,24 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| ) |
| -// The tripwire and invalidation (nearest-region never-reuse spec §4, plan |
| -// Task 8). At a start with the history active, every record that may hold |
| -// data must be covered by a mark; one that is not (a restore that dropped |
| -// marks, a console below the floor) invalidates the history. Cost per |
| -// start: a listing of apps/ and one of control/hosts-used/ (a page per |
| -// 1,000 keys), and a GET per record key with no mark, which is every |
| -// static and service record. Nothing per request. |
| +// The start-up check (nearest-region never-reuse spec §4, plan Task 8). At |
| +// a start with the history active, every record that may hold data must be |
| +// covered by a mark; one that is not (a restore that dropped marks, a |
| +// console below the floor) invalidates the history before the console |
| +// serves a data-kind create. Until the check has passed, data-kind creates |
| +// are refused (S5) and the region switch stays off; a store error is not a |
| +// breach, and the check runs again until it finishes. Cost per start: a |
| +// listing of apps/ and one of control/hosts-used/ (a page per 1,000 keys), |
| +// and a GET per record key with no mark, which is every static and service |
| +// record. Nothing per request. |
| -// msgHostsPageOperator is D4 (approved, nearest-region-never-reuse-b.md). |
| -const msgHostsPageOperator = "the hostname history is invalidated by an operator" |
| - |
| -// hostsTripwireRetry is how long the tripwire waits before trying a start's |
| -// check again after a store error. |
| +// hostsTripwireRetry is how long the check waits before running again |
| +// after a store error. |
| var hostsTripwireRetry = time.Minute |
| -// hostsTripwire is the start-time check. It returns nil when the history is |
| -// not active, when every record is covered, or once it has invalidated the |
| -// history; an error means the check could not finish. |
| +// hostsTripwire is the start-up check. It returns nil once the history is |
| +// verified, is not active, or has been invalidated; an error means the |
| +// check could not finish. |
| func (s *Server) hostsTripwire(ctx context.Context) error { |
| if s.cfg.Releases == nil { |
| return nil |
| @@ -81,71 +80,27 @@ func (s *Server) hostsTripwire(ctx context.Context) error { |
| } else if derr == nil && (body.Kind == "static" || body.Kind == "service") { |
| continue |
| } |
| - if err := s.invalidateHosts(ctx, msgHostsPageUncovered(k)); err != nil { |
| - return err |
| - } |
| - return nil |
| + return s.invalidateHosts(ctx, msgHostsPageUncovered(k)) |
| } |
| + s.hosts.mu.Lock() |
| + s.hosts.verified = true |
| + s.hosts.mu.Unlock() |
| return nil |
| } |
| -// RunHostsTripwire runs the start's check, and again every |
| -// hostsTripwireRetry until it finishes: a store error is not a breach, and |
| -// must not invalidate the history by itself. LoadHostsMode starts it when |
| -// the start's own run could not finish. |
| +// RunHostsTripwire runs the start-up check every hostsTripwireRetry until it |
| +// finishes. |
| func (s *Server) RunHostsTripwire(ctx context.Context) { |
| for { |
| - err := s.hostsTripwire(ctx) |
| - if err == nil { |
| - return |
| - } |
| - log.Printf("console: hosts used: the start's tripwire could not finish: %v (trying again in %s)", err, hostsTripwireRetry) |
| select { |
| case <-ctx.Done(): |
| return |
| case <-time.After(hostsTripwireRetry): |
| } |
| - } |
| -} |
| - |
| -// handleAPIHostsUsedInvalidate is POST /api/cli/system/hosts-used/invalidate: |
| -// an operator invalidates an active history (after a restore that may have |
| -// dropped marks, spec §4). C12 when it is not active. |
| -func (s *Server) handleAPIHostsUsedInvalidate(w http.ResponseWriter, r *http.Request) { |
| - addr, _, ok := s.apiSystemRoller(w, r) |
| - if !ok { |
| - return |
| - } |
| - if !s.systemBucket(w) { |
| - return |
| - } |
| - if s.cfg.HostClaim || s.cfg.MovesEnabled { |
| - jsonError(w, http.StatusConflict, msgHostsClaimsOn) |
| - return |
| - } |
| - ctx := r.Context() |
| - st, err := s.hostsState(ctx) |
| - if err != nil { |
| - hostsWriteFailed(w, "invalidate", err) |
| - return |
| - } |
| - if st.Mode != provision.HostsModeActive { |
| - jsonError(w, http.StatusConflict, msgHostsNotActive) |
| - return |
| - } |
| - if err := s.invalidateHosts(ctx, msgHostsPageOperator); err != nil { |
| - if err.Error() == msgHostsNotActive { |
| - jsonError(w, http.StatusConflict, msgHostsNotActive) |
| + err := s.hostsTripwire(ctx) |
| + if err == nil { |
| return |
| } |
| - hostsWriteFailed(w, "invalidate", err) |
| - return |
| - } |
| - log.Printf("console: hosts used: %s invalidated the hostname history", addr) |
| - st, err = s.hostsState(ctx) |
| - if err != nil { |
| - hostsWriteFailed(w, "invalidate", err) |
| - return |
| + log.Printf("console: hosts used: the start-up check could not finish: %v (trying again in %s)", err, hostsTripwireRetry) |
| } |
| - writeJSON(w, http.StatusOK, hostsStateAnswer(st)) |
| } |
diff --git a/internal/console/hostsused_tripwire_test.go b/internal/console/hostsused_tripwire_test.go| index 180910c70..b27b725e1 100644 |
| --- a/internal/console/hostsused_tripwire_test.go |
| +++ b/internal/console/hostsused_tripwire_test.go |
| @@ -8,15 +8,15 @@ package console |
| import ( |
| "context" |
| "encoding/json" |
| + "errors" |
| "net/http" |
| "testing" |
| "time" |
| "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| -const hostsUsedInvalidateURL = "/api/cli/system/hosts-used/invalidate" |
| - |
| // startHostsAgain is a console start as far as the history goes. |
| func startHostsAgain(t *testing.T, srv *Server) { |
| t.Helper() |
| @@ -105,33 +105,47 @@ func TestRestoreDroppingMarksInvalidates(t *testing.T) { |
| } |
| } |
| -// TestReinventoryLeavesInvalidated: begin from invalidated, clean scans, |
| -// complete: active again. |
| -func TestReinventoryLeavesInvalidated(t *testing.T) { |
| - l := invFx(t) |
| - forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeInvalidated, Reason: "test"}) |
| - begin(t, l) |
| - cleanImport(t, l, nil, nil) |
| - mustComplete(t, l) |
| - if code, out := createAs(t, l, `{"host":"fresh.shop.example.com"}`); code != http.StatusCreated { |
| - t.Fatalf("create once active again = %d %s", code, out) |
| +// failingAppsList fails every listing of prefix. |
| +type failingAppsList struct { |
| + release.Store |
| + prefix string |
| +} |
| + |
| +func (f failingAppsList) List(ctx context.Context, prefix string) ([]string, error) { |
| + if prefix == f.prefix { |
| + return nil, errors.New("the bucket did not answer") |
| } |
| + return f.Store.List(ctx, prefix) |
| } |
| -func TestInvalidateDoor(t *testing.T) { |
| +// TestStartupCheckGatesCreates: until the start-up check has passed, an |
| +// active history admits no data-kind create and keeps the region switch |
| +// off; once it passes, both work. |
| +func TestStartupCheckGatesCreates(t *testing.T) { |
| + old := hostsTripwireRetry |
| + hostsTripwireRetry = 10 * time.Millisecond |
| + t.Cleanup(func() { hostsTripwireRetry = old }) |
| l := newLifetimesFx(t) |
| - if code, _ := hostsDoor(t, l.fx, http.MethodPost, hostsUsedInvalidateURL, l.member, `{}`); code != http.StatusNotFound { |
| - t.Fatalf("a member's invalidate = %d, want 404", code) |
| + forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive, Examined: []string{"region:ie"}}) |
| + l.fx.srv.cfg.AppRegions, l.fx.srv.cfg.HomeRegion = true, "ie" |
| + good := l.fx.srv.cfg.Releases |
| + l.fx.srv.cfg.Releases = failingAppsList{Store: good, prefix: "apps/"} |
| + startHostsAgain(t, l.fx.srv) |
| + if code, out := createAs(t, l, `{"host":"early.shop.example.com"}`); code != http.StatusServiceUnavailable || ltErr(out) != msgHostsInvalidated { |
| + t.Fatalf("create before the check passed = %d %s, want 503 S5", code, out) |
| } |
| - if code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedInvalidateURL, l.operator, `{}`); code != http.StatusConflict || out["error"] != msgHostsNotActive { |
| - t.Fatalf("invalidate when incomplete = %d %v, want 409 C12", code, out) |
| + if l.fx.srv.appRegionsOn() { |
| + t.Fatal("the switch is on before the check passed") |
| } |
| - forceHostsState(t, l.fx.srv, provision.HostsState{Mode: provision.HostsModeActive}) |
| - code, out := hostsDoor(t, l.fx, http.MethodPost, hostsUsedInvalidateURL, l.operator, `{}`) |
| - if code != http.StatusOK || out["mode"] != provision.HostsModeInvalidated { |
| - t.Fatalf("invalidate = %d %v", code, out) |
| + l.fx.srv.cfg.Releases = good |
| + deadline := time.Now().Add(5 * time.Second) |
| + for !l.fx.srv.appRegionsOn() { |
| + if time.Now().After(deadline) { |
| + t.Fatal("the check never passed once the bucket answered") |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| } |
| - if st := modeOf(t, l); st.Reason != msgHostsPageOperator { |
| - t.Fatalf("reason = %q, want D4", st.Reason) |
| + if code, out := createAs(t, l, `{"host":"later.shop.example.com"}`); code != http.StatusCreated { |
| + t.Fatalf("create once the check passed = %d %s", code, out) |
| } |
| } |
diff --git a/internal/console/hostsused_window.go b/internal/console/hostsused_window.go| deleted file mode 100644 |
| index b1e8b1309..000000000 |
| --- a/internal/console/hostsused_window.go |
| +++ /dev/null |
| @@ -1,311 +0,0 @@ |
| -package console |
| - |
| -import ( |
| - "context" |
| - "encoding/json" |
| - "errors" |
| - "log" |
| - "net/http" |
| - "os" |
| - "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) |
| -// and the history's status door (Task 4). begin opens the window: data-kind |
| -// creates (S8), move admissions and placement (S7) are refused while the |
| -// work admitted before it drains. status reports what is left. cancel |
| -// returns to the mode begin started from. Operators only (apiSystemRoller). |
| - |
| -// The approved strings (docs/superpowers/notes/copy/nearest-region-never-reuse-b.md). |
| -const ( |
| - msgHostsAlreadyComplete = "The hostname history is already complete." // C1 |
| - msgHostsWindowOpen = "A maintenance window is already open." // C2 |
| - msgHostsNoWindow = "No maintenance window is open. Start one with carlos system hosts-used begin." // C3 |
| - msgHostsNotActive = "The hostname history is not active, so there is nothing to invalidate." // C12 |
| - msgHostsClaimsOn = "This console runs host claims or live moves, so the hostname history can't be completed." // C11 |
| -) |
| - |
| -// hostsUsedStatus is what the status, begin and cancel doors answer. |
| -// UnfinishedMoves is counted only while the window is open (it reads every |
| -// record), and is null otherwise. |
| -type hostsUsedStatus struct { |
| - Mode string `json:"mode"` |
| - Marks int `json:"marks"` |
| - InflightCreates *int `json:"inflight_creates"` |
| - PendingAllocations int `json:"pending_allocations"` |
| - PendingRetirements int `json:"pending_retirements"` |
| - UnfinishedMoves *int `json:"unfinished_moves"` |
| - // 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 |
| -// and the door's diagnostic. |
| -type hostsStatusFailure struct { |
| - msg string |
| - err error |
| -} |
| - |
| -// hostsStatus reads the history's status: the mode, the marks counted by |
| -// listing the prefix (a page per 1,000 keys), the in-process admissions, |
| -// the console's pending lifetime rows and, while the window is open, the |
| -// records whose move has not ended (one apps/ listing and a GET per record). |
| -// An operator action, never polled. |
| -func (s *Server) hostsStatus(ctx context.Context) (hostsUsedStatus, *hostsStatusFailure) { |
| - st, err := s.hostsState(ctx) |
| - if err != nil { |
| - return hostsUsedStatus{}, &hostsStatusFailure{"could not read the hostname history's mode. Try again.", err} |
| - } |
| - keys, err := s.cfg.Releases.List(ctx, provision.HostsUsedPrefix) |
| - if err != nil { |
| - return hostsUsedStatus{}, &hostsStatusFailure{"could not list the hostname history. Try again.", err} |
| - } |
| - out := hostsUsedStatus{Mode: st.Mode} |
| - for _, k := range keys { |
| - if host, ok := strings.CutSuffix(strings.TrimPrefix(k, provision.HostsUsedPrefix), ".json"); ok && provision.HostsUsedKey(host) == k { |
| - out.Marks++ |
| - } |
| - } |
| - admitted := s.hostsAdmitted() |
| - out.InflightCreates = &admitted |
| - allocs, err := s.store.PendingAllocations() |
| - if err != nil { |
| - return hostsUsedStatus{}, &hostsStatusFailure{"could not read the console's pending creates. Try again.", err} |
| - } |
| - rets, err := s.store.PendingRetirements() |
| - if err != nil { |
| - return hostsUsedStatus{}, &hostsStatusFailure{"could not read the console's pending deletes. Try again.", err} |
| - } |
| - out.PendingAllocations, out.PendingRetirements = len(allocs), len(rets) |
| - if st.Mode == provision.HostsModeActivating { |
| - moves, seeding, err := s.unfinishedWork(ctx) |
| - if err != nil { |
| - return hostsUsedStatus{}, &hostsStatusFailure{"could not read the instance records. Try again.", err} |
| - } |
| - out.UnfinishedMoves, out.UnfinishedSeeds = &moves, &seeding |
| - closed := closedTargets(st) |
| - listings, err := s.hostsListings(ctx, st.Window) |
| - 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 |
| -} |
| - |
| -// 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, 0, err |
| - } |
| - for _, k := range keys { |
| - if !provision.IsRecordKey(k) { |
| - continue |
| - } |
| - raw, _, err := s.cfg.Releases.Get(ctx, k) |
| - if err != nil { |
| - if errors.Is(err, os.ErrNotExist) { |
| - continue // deleted since the listing |
| - } |
| - 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 or seed: %v", k, err) |
| - continue |
| - } |
| - if len(body.Move) > 0 && string(body.Move) != "null" { |
| - moves++ |
| - } |
| - if body.Seed != nil && !seedEnded(body.Seed.State) { |
| - seeding++ |
| - } |
| - } |
| - 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) { |
| - out, fail := s.hostsStatus(ctx) |
| - if fail != nil { |
| - log.Printf("console: hosts used status: %s (%v)", fail.msg, fail.err) |
| - jsonError(w, http.StatusBadGateway, fail.msg) |
| - return |
| - } |
| - writeJSON(w, http.StatusOK, out) |
| -} |
| - |
| -// handleAPIHostsUsedStatus is GET /api/cli/system/hosts-used/status. It |
| -// writes nothing. |
| -func (s *Server) handleAPIHostsUsedStatus(w http.ResponseWriter, r *http.Request) { |
| - if _, _, ok := s.apiSystemRoller(w, r); !ok { |
| - return |
| - } |
| - if !s.systemBucket(w) { |
| - return |
| - } |
| - s.writeHostsStatus(w, r.Context()) |
| -} |
| - |
| -// hostsWriteFailed answers a mode write that failed. |
| -func hostsWriteFailed(w http.ResponseWriter, what string, err error) { |
| - log.Printf("console: hosts used %s: write the mode: %v", what, err) |
| - jsonError(w, http.StatusBadGateway, "could not write the hostname history's mode. Try again.") |
| -} |
| - |
| -// handleAPIHostsUsedBegin is POST /api/cli/system/hosts-used/begin: open the |
| -// window from incomplete, or from invalidated for a re-inventory. |
| -func (s *Server) handleAPIHostsUsedBegin(w http.ResponseWriter, r *http.Request) { |
| - addr, _, ok := s.apiSystemRoller(w, r) |
| - if !ok { |
| - return |
| - } |
| - if !s.systemBucket(w) { |
| - return |
| - } |
| - // The history is bound to claims off and Phase 1 off (spec §1): complete |
| - // refuses either, so the window is not opened for nothing. |
| - if s.cfg.HostClaim || s.cfg.MovesEnabled { |
| - jsonError(w, http.StatusConflict, msgHostsClaimsOn) |
| - return |
| - } |
| - ctx := r.Context() |
| - // The roster is fixed now (spec §3): complete refuses if it changes. |
| - roster, fleetTargets, regionTargets, 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 |
| - } |
| - } |
| - window, err := newLifetimeOpID() |
| - if err != nil { |
| - hostsWriteFailed(w, "begin", err) |
| - 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, Window: window, |
| - Roster: roster, FleetTargets: fleetTargets, RegionTargets: regionTargets}, nil |
| - }) |
| - switch { |
| - case err != nil: |
| - hostsWriteFailed(w, "begin", err) |
| - return |
| - case ref != nil: |
| - writeDoorRefusalJSON(w, r, ref) |
| - return |
| - } |
| - log.Printf("console: hosts used: %s opened the maintenance window", addr) |
| - writeJSON(w, http.StatusOK, hostsStateAnswer(next)) |
| -} |
| - |
| -// handleAPIHostsUsedCancel is POST /api/cli/system/hosts-used/cancel: close |
| -// the window, back to the mode begin started from. A window opened from |
| -// invalidated goes back to invalidated, never to incomplete (an accepted |
| -// deviation from spec §3a item 5): cancelling a re-inventory never turns the |
| -// refusals off. |
| -func (s *Server) handleAPIHostsUsedCancel(w http.ResponseWriter, r *http.Request) { |
| - addr, _, ok := s.apiSystemRoller(w, r) |
| - if !ok { |
| - return |
| - } |
| - if !s.systemBucket(w) { |
| - return |
| - } |
| - if s.cfg.HostClaim || s.cfg.MovesEnabled { |
| - jsonError(w, http.StatusConflict, msgHostsClaimsOn) |
| - return |
| - } |
| - ctx := r.Context() |
| - next, ref, err := s.hostsTransition(ctx, func(cur provision.HostsState) (provision.HostsState, *doorRefusal) { |
| - if cur.Mode != provision.HostsModeActivating { |
| - return cur, &doorRefusal{http.StatusConflict, msgHostsNoWindow} |
| - } |
| - back := provision.HostsModeIncomplete |
| - if cur.From == provision.HostsModeInvalidated { |
| - back = provision.HostsModeInvalidated |
| - } |
| - return provision.HostsState{Mode: back}, nil |
| - }) |
| - switch { |
| - case err != nil: |
| - hostsWriteFailed(w, "cancel", err) |
| - return |
| - case ref != nil: |
| - writeDoorRefusalJSON(w, r, ref) |
| - return |
| - } |
| - log.Printf("console: hosts used: %s closed the maintenance window", addr) |
| - writeJSON(w, http.StatusOK, hostsStateAnswer(next)) |
| -} |
diff --git a/internal/console/hostsused_window_test.go b/internal/console/hostsused_window_test.go| deleted file mode 100644 |
| index 9e25eb269..000000000 |
| --- a/internal/console/hostsused_window_test.go |
| +++ /dev/null |
| @@ -1,419 +0,0 @@ |
| -package console |
| - |
| -// The activation window (nearest-region never-reuse plan, Task 5; spec |
| -// §3a): begin stops data-kind creates, move admissions and placement, the |
| -// work admitted before it drains and is counted, and cancel returns to the |
| -// mode begin started from. Through the real doors. |
| - |
| -import ( |
| - "context" |
| - "encoding/json" |
| - "errors" |
| - "go/ast" |
| - "go/parser" |
| - "go/token" |
| - "net/http" |
| - "path/filepath" |
| - "strings" |
| - "sync" |
| - "testing" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/provision" |
| - "github.com/carlosframework/platform/internal/release" |
| - "github.com/carlosframework/platform/internal/seeds" |
| -) |
| - |
| -const ( |
| - hostsUsedBeginURL = "/api/cli/system/hosts-used/begin" |
| - hostsUsedCancelURL = "/api/cli/system/hosts-used/cancel" |
| -) |
| - |
| -// hostsDoor calls a hosts-used system door as token and decodes its JSON. |
| -func hostsDoor(t *testing.T, fx *consoleFixture, method, path, token, body string) (int, map[string]any) { |
| - t.Helper() |
| - code, _, out := rawReq(t, method, fx.ts.URL+path, token, body) |
| - var m map[string]any |
| - _ = json.Unmarshal([]byte(out), &m) |
| - if m == nil { |
| - m = map[string]any{"raw": out} |
| - } |
| - return code, m |
| -} |
| - |
| -func begin(t *testing.T, l lifetimesFx) map[string]any { |
| - t.Helper() |
| - code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedBeginURL, l.operator, `{}`) |
| - if code != http.StatusOK || st["mode"] != provision.HostsModeActivating { |
| - t.Fatalf("begin = %d %v", code, st) |
| - } |
| - return st |
| -} |
| - |
| -func statusOf(t *testing.T, l lifetimesFx) map[string]any { |
| - t.Helper() |
| - code, st := hostsDoor(t, l.fx, http.MethodGet, hostsUsedStatusURL, l.operator, "") |
| - if code != http.StatusOK { |
| - t.Fatalf("status = %d %v", code, st) |
| - } |
| - return st |
| -} |
| - |
| -func createAs(t *testing.T, l lifetimesFx, body string) (int, string) { |
| - t.Helper() |
| - code, _, out := rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", ltApp), l.member, body) |
| - return code, out |
| -} |
| - |
| -func TestBeginIsOperatorOnly(t *testing.T) { |
| - l := newLifetimesFx(t) |
| - for _, path := range []string{hostsUsedBeginURL, hostsUsedCancelURL} { |
| - 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) |
| - } |
| - } |
| - if st := statusOf(t, l); st["mode"] != provision.HostsModeIncomplete { |
| - t.Fatalf("mode after refused doors = %v", st["mode"]) |
| - } |
| -} |
| - |
| -func TestBeginStopsAdmissions(t *testing.T) { |
| - l := newLifetimesFx(t) |
| - const one = "one.shop.example.com" |
| - if code, out := createAs(t, l, `{"host":"`+one+`"}`); code != http.StatusCreated { |
| - t.Fatalf("create before begin = %d %s", code, out) |
| - } |
| - begin(t, l) |
| - code, out := createAs(t, l, `{"host":"two.shop.example.com"}`) |
| - if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsActivating { |
| - t.Fatalf("data-kind create in the window = %d %s, want 503 S8", code, out) |
| - } |
| - if raw, _ := rawOf(t, l.fx.rel, ltApp, "two.shop.example.com"); raw != nil { |
| - t.Fatal("a record was written in the window") |
| - } |
| - if code, out := createAs(t, l, `{"host":"site.shop.example.com","kind":"static"}`); code != http.StatusCreated { |
| - t.Fatalf("static create in the window = %d %s, want 201", code, out) |
| - } |
| - for _, c := range []struct{ name, path, body string }{ |
| - {"offline start", "/api/cli/apps/bab/" + ltApp + "/instances/" + one + "/move/offline", `{"to":"uk"}`}, |
| - {"offline stage", "/api/cli/apps/bab/" + ltApp + "/instances/" + one + "/move/offline/stage", `{"to":"uk"}`}, |
| - {"move", "/api/cli/apps/bab/" + ltApp + "/instances/" + one + "/move", `{"to":"uk"}`}, |
| - {"place", "/api/cli/apps/bab/" + ltApp + "/place", `{"target":""}`}, |
| - } { |
| - code, _, out := rawReq(t, http.MethodPost, l.fx.ts.URL+c.path, l.operator, c.body) |
| - if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsMovesPaused { |
| - t.Errorf("%s in the window = %d %s, want 503 S7", c.name, code, out) |
| - } |
| - } |
| - // The window stays open across a refused admission. |
| - if st := statusOf(t, l); st["mode"] != provision.HostsModeActivating { |
| - t.Fatalf("mode = %v", st["mode"]) |
| - } |
| -} |
| - |
| -func TestSidecarCreateRefusedInTheWindow(t *testing.T) { |
| - fx := leftoverFixture(t, "code-window-sidecar") |
| - forceHostsMode(t, fx.srv, provision.HostsModeActivating) |
| - code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot","region":"ie"}`) |
| - if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsActivating { |
| - t.Fatalf("sidecar create in the window = %d %s, want 503 S8", code, out) |
| - } |
| - forceHostsMode(t, fx.srv, provision.HostsModeInvalidated) |
| - code, _, out = rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot","region":"ie"}`) |
| - if code != http.StatusServiceUnavailable || ltErr(out) != msgHostsInvalidated { |
| - t.Fatalf("sidecar create invalidated = %d %s, want 503 S5", code, out) |
| - } |
| -} |
| - |
| -// TestDrainWaitsForAdmittedMove: a record whose Move is not terminal keeps |
| -// unfinished_moves at 1 until the move ends. |
| -func TestDrainWaitsForAdmittedMove(t *testing.T) { |
| - l := newLifetimesFx(t) |
| - const host = "moving.shop.example.com" |
| - rec := provision.Record{Schema: 1, Host: host, Slug: "moving", App: ltApp, Account: "bab", Channel: "stable", |
| - CreatedAt: time.Now().UTC(), Move: &provision.MoveState{ID: "mv_abcdefghijklmnopqrstuvwxyz", To: "uk", State: "requested", RequestedAt: time.Now().UTC()}} |
| - if err := provision.CreateRecord(context.Background(), l.fx.rel, rec); err != nil { |
| - t.Fatal(err) |
| - } |
| - if st := statusOf(t, l); st["unfinished_moves"] != nil { |
| - t.Fatalf("unfinished_moves outside the window = %v, want null", st["unfinished_moves"]) |
| - } |
| - begin(t, l) |
| - if st := statusOf(t, l); st["unfinished_moves"] != float64(1) { |
| - t.Fatalf("unfinished_moves = %v, want 1", st["unfinished_moves"]) |
| - } |
| - got, etag, err := provision.GetRecordETag(context.Background(), l.fx.rel, "bab", ltApp, host) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - got.Move = nil |
| - if err := provision.UpdateRecord(context.Background(), l.fx.rel, *got, etag); err != nil { |
| - t.Fatal(err) |
| - } |
| - if st := statusOf(t, l); st["unfinished_moves"] != float64(0) { |
| - t.Fatalf("unfinished_moves after the move ended = %v, want 0", st["unfinished_moves"]) |
| - } |
| -} |
| - |
| -// TestDrainCountsInflightCreate: a create admitted before begin and still in |
| -// its handler is counted until the handler returns, and it cannot persist |
| -// once the window is open. |
| -func TestDrainCountsInflightCreate(t *testing.T) { |
| - l := newLifetimesFx(t) |
| - bucket := <Store{Store: l.fx.rel} |
| - l.fx.srv.cfg.Releases = bucket |
| - const host = "slow.shop.example.com" |
| - markGate, markHook := pauseNth(t, "put", provision.HostsUsedKey(host), 1) |
| - bucket.setHook(markHook) |
| - done := make(chan struct{}) |
| - var code int |
| - var out string |
| - go func() { |
| - defer close(done) |
| - code, _, out = rawReq(t, http.MethodPost, instancesURL(l.fx, "bab", ltApp), l.member, `{"host":"`+host+`"}`) |
| - }() |
| - <-markGate.entered |
| - bucket.setHook(nil) |
| - begin(t, l) |
| - if st := statusOf(t, l); st["inflight_creates"] != float64(1) { |
| - t.Fatalf("inflight_creates = %v, want 1", st["inflight_creates"]) |
| - } |
| - markGate.open() |
| - <-done |
| - if code != http.StatusCreated { |
| - t.Fatalf("the in-flight create = %d %s, want it to finish", code, out) |
| - } |
| - if st := statusOf(t, l); st["inflight_creates"] != float64(0) { |
| - t.Fatalf("inflight_creates after the handler returned = %v, want 0", st["inflight_creates"]) |
| - } |
| -} |
| - |
| -func TestActivatingSurvivesRestart(t *testing.T) { |
| - l := newLifetimesFx(t) |
| - begin(t, l) |
| - srv, err := NewServer(l.fx.srv.cfg, l.fx.st) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - mode, err := srv.hostsMode(context.Background()) |
| - if err != nil || mode != provision.HostsModeActivating { |
| - t.Fatalf("the restarted console's mode = %q %v, want activating", mode, err) |
| - } |
| - if done, ref := srv.admitDataCreate(context.Background(), "x.shop.example.com"); ref == nil || ref.Msg != msgHostsActivating { |
| - if done != nil { |
| - done() |
| - } |
| - t.Fatalf("the restarted console admitted a data-kind create: %+v", ref) |
| - } |
| -} |
| - |
| -func TestCancelReturnsToIncomplete(t *testing.T) { |
| - l := newLifetimesFx(t) |
| - if code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`); code != http.StatusConflict || st["error"] != msgHostsNoWindow { |
| - t.Fatalf("cancel with no window = %d %v, want 409 C3", code, st) |
| - } |
| - begin(t, l) |
| - if code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedBeginURL, l.operator, `{}`); code != http.StatusConflict || st["error"] != msgHostsWindowOpen { |
| - t.Fatalf("a second begin = %d %v, want 409 C2", code, st) |
| - } |
| - code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`) |
| - if code != http.StatusOK || st["mode"] != provision.HostsModeIncomplete { |
| - t.Fatalf("cancel = %d %v", code, st) |
| - } |
| - if code, out := createAs(t, l, `{"host":"after.shop.example.com"}`); code != http.StatusCreated { |
| - t.Fatalf("create after cancel = %d %s", code, out) |
| - } |
| - // A window opened from invalidated goes back to invalidated (accepted |
| - // deviation, spec §3a item 5). |
| - forceHostsMode(t, l.fx.srv, provision.HostsModeInvalidated) |
| - begin(t, l) |
| - code, st = hostsDoor(t, l.fx, http.MethodPost, hostsUsedCancelURL, l.operator, `{}`) |
| - if code != http.StatusOK || st["mode"] != provision.HostsModeInvalidated { |
| - t.Fatalf("cancel of a re-inventory = %d %v, want invalidated", code, st) |
| - } |
| - forceHostsMode(t, l.fx.srv, provision.HostsModeActive) |
| - if code, st := hostsDoor(t, l.fx, http.MethodPost, hostsUsedBeginURL, l.operator, `{}`); code != http.StatusConflict || st["error"] != msgHostsAlreadyComplete { |
| - 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) |
| - } |
| -} |
| - |
| -// pausingPut holds the first Put of key until released. |
| -type pausingPut struct { |
| - release.Store |
| - key string |
| - gate *pauseGate |
| - once *sync.Once |
| -} |
| - |
| -func (p pausingPut) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| - if key == p.key { |
| - p.once.Do(func() { |
| - close(p.gate.entered) |
| - <-p.gate.release |
| - }) |
| - } |
| - return p.Store.Put(ctx, key, body, ifMatch) |
| -} |
| - |
| -// TestDrainHoldsADetachedUploadPastItsAbort (Astra Task 5 r2, P1): an |
| -// import's upload still inside its snapshot write after the import was |
| -// aborted is counted until the worker returns, so the drain and complete |
| -// wait for its last write. |
| -func TestDrainHoldsADetachedUploadPastItsAbort(t *testing.T) { |
| - f := newImportFixture(t) |
| - operator := cliToken(t, f.fx, "paul@keymail.dev", "code-drain-upload") |
| - body, sha := sqliteBytes(t) |
| - code, out := beginImport(t, f, importHost, sha, int64(len(body))) |
| - begun, _ := f.requireBegun(t, code, out, importHost) |
| - gate := newPauseGate() |
| - t.Cleanup(gate.open) |
| - f.fx.srv.cfg.SeedData = pausingPut{Store: f.data, key: seeds.SnapshotKey(importHost, begun.Seed.ID), gate: gate, once: new(sync.Once)} |
| - if code, out := uploadImport(t, f, importHost, body); code != http.StatusAccepted { |
| - t.Fatalf("upload = %d %v", code, out) |
| - } |
| - <-gate.entered |
| - if code, out := postImport(t, f, importHost, "abort"); code != http.StatusOK || out["state"] != "aborted" { |
| - t.Fatalf("abort during the upload = %d %v", code, out) |
| - } |
| - if code, st := hostsDoor(t, f.fx, http.MethodPost, hostsUsedBeginURL, operator, `{}`); code != http.StatusOK || st["mode"] != provision.HostsModeActivating { |
| - t.Fatalf("begin = %d %v", code, st) |
| - } |
| - code, st := hostsDoor(t, f.fx, http.MethodGet, hostsUsedStatusURL, operator, "") |
| - if code != http.StatusOK || st["inflight_creates"] != float64(1) || st["unfinished_seeds"] != float64(0) { |
| - t.Fatalf("status with the upload still writing = %d %v, want inflight_creates 1", code, st) |
| - } |
| - if code, out := hostsDoor(t, f.fx, http.MethodPost, "/api/cli/system/hosts-used/complete", operator, `{}`); code != http.StatusConflict || out["error"] != msgHostsStillSettling { |
| - t.Fatalf("complete with the upload still writing = %d %v, want C6", code, out) |
| - } |
| - gate.open() |
| - f.fx.srv.seedCopies.Wait() |
| - if code, st := hostsDoor(t, f.fx, http.MethodGet, hostsUsedStatusURL, operator, ""); code != http.StatusOK || st["inflight_creates"] != float64(0) { |
| - t.Fatalf("status once the upload returned = %d %v, want 0", code, st) |
| - } |
| -} |
| - |
| -// TestEverySeedWorkerIsCounted is the guard for the single enforcement |
| -// point (Paul's ruling on Task 5, option 1): in internal/console, a |
| -// goroutine starts only through goSeedWorker, or is listed here with why it |
| -// writes nothing a box could later read for a hostname. |
| -func TestEverySeedWorkerIsCounted(t *testing.T) { |
| - allowed := map[string]string{ |
| - "apiinstanceseed.go restoreWatch": "a size watcher: it measures scratch and cancels the restore, writing nothing", |
| - } |
| - seedFiles, err := filepath.Glob("seed*.go") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - seedFiles = append(seedFiles, "apiinstanceseed.go", "apiinstanceimport.go") |
| - fset := token.NewFileSet() |
| - for _, file := range seedFiles { |
| - if strings.HasSuffix(file, "_test.go") { |
| - continue |
| - } |
| - f, err := parser.ParseFile(fset, file, nil, 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, decl := range f.Decls { |
| - fn, ok := decl.(*ast.FuncDecl) |
| - if !ok || fn.Body == nil { |
| - continue |
| - } |
| - ast.Inspect(fn.Body, func(n ast.Node) bool { |
| - if g, ok := n.(*ast.GoStmt); ok { |
| - if _, ok := allowed[file+" "+fn.Name.Name]; !ok { |
| - t.Errorf("%s: %s starts a goroutine outside goSeedWorker (%s)", file, fn.Name.Name, fset.Position(g.Pos())) |
| - } |
| - } |
| - if call, ok := n.(*ast.CallExpr); ok && exprName(call.Fun) == "s.seedCopies.Add" { |
| - t.Errorf("%s: %s adds to seedCopies outside goSeedWorker (%s)", file, fn.Name.Name, fset.Position(call.Pos())) |
| - } |
| - return true |
| - }) |
| - } |
| - } |
| -} |
diff --git a/internal/console/hostsused_writers_test.go b/internal/console/hostsused_writers_test.go| index c33588c71..500ebb63f 100644 |
| --- a/internal/console/hostsused_writers_test.go |
| +++ b/internal/console/hostsused_writers_test.go |
| @@ -186,6 +186,9 @@ func forceHostsMode(t *testing.T, srv *Server, mode string) { |
| if got, err := srv.hostsMode(ctx); err != nil || got != mode { |
| t.Fatalf("hostsMode = %q %v, want %q", got, err, mode) |
| } |
| + srv.hosts.mu.Lock() |
| + srv.hosts.verified = true // as if the start-up check had passed |
| + srv.hosts.mu.Unlock() |
| } |
| func eachMarkDoor(t *testing.T, body func(t *testing.T, c markCase)) { |
| @@ -566,15 +569,11 @@ func TestHostsUsedStatusDoor(t *testing.T) { |
| if code != http.StatusOK || st["mode"] != provision.HostsModeIncomplete || st["marks"] != float64(0) { |
| t.Fatalf("empty status = %d %v", code, st) |
| } |
| - for _, k := range []string{"pending_allocations", "pending_retirements", "inflight_creates"} { |
| - if st[k] != float64(0) { |
| - t.Fatalf("%s = %v, want 0", k, st[k]) |
| + for _, k := range []string{"pending_allocations", "pending_retirements", "inflight_creates", "unfinished_moves"} { |
| + if _, ok := st[k]; ok { |
| + t.Fatalf("%s is still in the status: %v", k, st) |
| } |
| } |
| - // Moves are counted only while the window is open (Task 5). |
| - if v, ok := st["unfinished_moves"]; !ok || v != nil { |
| - t.Fatalf("unfinished_moves = %v (present %v), want null outside the window", v, ok) |
| - } |
| for _, host := range []string{"a.shop.example.com", "b.shop.example.com"} { |
| if code, out := (ltOn{lifetimesFx: l}).create(t, host); code != http.StatusCreated { |
| t.Fatalf("create %s = %d %s", host, code, out) |
diff --git a/internal/console/regioncandidates.go b/internal/console/regioncandidates.go| index cb50d8099..b0d6e3fc1 100644 |
| --- a/internal/console/regioncandidates.go |
| +++ b/internal/console/regioncandidates.go |
| @@ -198,7 +198,7 @@ func (s *Server) regionCands(snap edgesSnapshot) []regionCandidate { |
| cands := regionCandidates(snap, s.cfg.HomeRegion, s.expectedSecretsFP()) |
| // Once the hostname history is active, a region complete did not |
| // examine is no automatic choice (nearest-region never-reuse spec §3). |
| - if st := s.hostsCached(); st.Mode == provision.HostsModeActive { |
| + if st, verified := s.hostsCached(); st.Mode == provision.HostsModeActive && verified { |
| for i := range cands { |
| if !cands[i].Home && !regionExamined(st, cands[i].Code) { |
| cands[i].Eligible = false |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 4f0ccb611..d3ed03c36 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -294,12 +294,6 @@ var closedDoors = []string{ |
| // The hostname history's status (nearest-region never-reuse): an |
| // operator's deployment-wide view, the same cut. |
| "GET /api/cli/system/hosts-used/status", |
| - "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", |
| - "POST /api/cli/system/hosts-used/invalidate", |
| // `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", |
| @@ -1109,8 +1103,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 73 { |
| - t.Errorf("walked %d closed doors, want all %d (and 73 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 six 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 != 67 { |
| + t.Errorf("walked %d closed doors, want all %d (and 67 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, 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-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt| index 8cb44d9fe..6fd44302d 100644 |
| --- a/internal/console/testdata/claim-authority-sites.txt |
| +++ b/internal/console/testdata/claim-authority-sites.txt |
| @@ -150,3 +150,4 @@ awsregionmetric.go|capacityPublisherFromEnv|cloudwatch.NewFromConfig(cfg, func(o |
| enrollpass.go|startEnrollPass|newAutoEnroller(s.cfg.ClaimAuthority, members) |
| enrollpass.go|startEnrollPass|runEnrollPass(ctx, e, enrollPassInterval, log.Printf) |
| enrollpass.go|runEnrollPass|e.EnrollPass(ctx) |
| +../../cmd/console/hostsused.go|runHostsUsed|os.Open(*listingsPath) |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 26fab8d70..908a5fda2 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -267,12 +267,6 @@ route POST /api/cli/services/{account}/{name}/rotate |
| route POST /api/cli/system/activation/cancel |
| 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/hosts-used/invalidate |
| 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 5af84b65a..7f22fc4e1 100644 |
| --- a/internal/provision/hostsused.go |
| +++ b/internal/provision/hostsused.go |
| @@ -30,10 +30,12 @@ const ( |
| HostsFloorKey = HostsUsedPrefix + "@floor" |
| ) |
| -// The history modes (spec §4). Absent in the store means incomplete. |
| +// The history modes (spec §4). Absent in the store means incomplete. The |
| +// history becomes active, or is invalidated by an operator, only offline |
| +// with the console stopped (console hosts-used); a serving console can only |
| +// move active to invalidated. |
| const ( |
| HostsModeIncomplete = "incomplete" |
| - HostsModeActivating = "activating" |
| HostsModeActive = "active" |
| HostsModeInvalidated = "invalidated" |
| ) |
| @@ -117,7 +119,7 @@ func (r Record) DataKind() bool { |
| func validHostsMode(m string) bool { |
| switch m { |
| - case HostsModeIncomplete, HostsModeActivating, HostsModeActive, HostsModeInvalidated: |
| + case HostsModeIncomplete, HostsModeActive, HostsModeInvalidated: |
| return true |
| } |
| return false |
| @@ -127,24 +129,15 @@ func validHostsMode(m string) bool { |
| // A merge-A body carries the mode alone, and still reads. |
| type HostsState struct { |
| Mode string `json:"mode"` |
| - // From is the mode an open window (activating) returns to on cancel: |
| - // incomplete, or invalidated for a re-inventory. |
| - From string `json:"from,omitempty"` |
| - // Roster is the targets fixed when the window opened ("box:<box>", |
| - // "bucket:<bucket>"), which complete needs listings for. |
| - Roster []string `json:"roster,omitempty"` |
| - // Examined is the regions, pools and fleets complete examined |
| - // ("region:<code>", "pool:<name>", "fleet:<name>"). A data-kind create |
| - // anywhere else is refused once active. |
| + // Examined is the regions and fleets activation examined |
| + // ("region:<code>", "fleet:<name>"). A data-kind create anywhere else |
| + // is refused once active (S4). |
| Examined []string `json:"examined,omitempty"` |
| - // Window identifies one opening of the window (activating): its |
| - // listings carry it, and complete activates only the window it checked. |
| - Window string `json:"window,omitempty"` |
| - // FleetTargets is, for each fleet on the roster, the listing targets |
| - // it owns (its boxes and its bucket), which closing it may excuse. |
| + // FleetTargets is, for each fleet on the roster at activation, the |
| + // listing targets it used (its boxes and its bucket). |
| FleetTargets map[string][]string `json:"fleet_targets,omitempty"` |
| - // RegionTargets is the listing targets the edges files name (regions' |
| - // boxes and buckets): closing a fleet never excuses one of them. |
| + // RegionTargets is the listing targets the regions used at activation: |
| + // closing a fleet never excuses one of them. |
| RegionTargets []string `json:"region_targets,omitempty"` |
| // Closed is the fleets closed instead of scanned ("fleet:<name>"), |
| // which take no data-kind create. |
diff --git a/internal/provision/hostsused_test.go b/internal/provision/hostsused_test.go| index f34160f4a..0499d3ff1 100644 |
| --- a/internal/provision/hostsused_test.go |
| +++ b/internal/provision/hostsused_test.go |
| @@ -115,7 +115,7 @@ func TestHostsModeDefaultsIncomplete(t *testing.T) { |
| if err != nil || mode != HostsModeIncomplete || etag != "" { |
| t.Fatalf("ReadHostsMode of an empty store = (%q, %q, %v), want (incomplete, \"\", nil)", mode, etag, err) |
| } |
| - tag, err := WriteHostsMode(ctx, s, HostsModeActivating, "") |
| + tag, err := WriteHostsMode(ctx, s, HostsModeInvalidated, "") |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -293,16 +293,16 @@ func TestHostsStateRoundTrips(t *testing.T) { |
| if err != nil || st.Mode != HostsModeIncomplete || etag == "" { |
| t.Fatalf("merge-A body = %+v %q %v", st, etag, err) |
| } |
| - want := HostsState{Mode: HostsModeActivating, From: HostsModeInvalidated, Roster: []string{"box:a", "bucket:b"}, |
| + want := HostsState{Mode: HostsModeInvalidated, RegionTargets: []string{"box:a", "bucket:b"}, |
| Closed: []string{"fleet:f"}, Examined: []string{"region:uk"}, Reason: "r"} |
| if _, err := WriteHostsState(ctx, s, want, etag); err != nil { |
| t.Fatal(err) |
| } |
| got, _, err := ReadHostsState(ctx, s) |
| - if err != nil || got.Mode != want.Mode || got.From != want.From || len(got.Roster) != 2 || got.Closed[0] != "fleet:f" || got.Examined[0] != "region:uk" || got.Reason != "r" { |
| + if err != nil || got.Mode != want.Mode || len(got.RegionTargets) != 2 || got.Closed[0] != "fleet:f" || got.Examined[0] != "region:uk" || got.Reason != "r" { |
| t.Fatalf("round trip = %+v %v", got, err) |
| } |
| - if mode, _, err := ReadHostsMode(ctx, s); err != nil || mode != HostsModeActivating { |
| + if mode, _, err := ReadHostsMode(ctx, s); err != nil || mode != HostsModeInvalidated { |
| t.Fatalf("ReadHostsMode = %q %v", mode, err) |
| } |
| if _, err := WriteHostsState(ctx, s, HostsState{Mode: "sideways"}, ""); err == nil { |
diff --git a/internal/provision/nearest_region_b_census_test.go b/internal/provision/nearest_region_b_census_test.go| index b1759d8f8..f9adae17f 100644 |
| --- a/internal/provision/nearest_region_b_census_test.go |
| +++ b/internal/provision/nearest_region_b_census_test.go |
| @@ -1,53 +1,33 @@ |
| package provision |
| // Record-write census entries for nearest-region never-reuse merge B (branch |
| -// nearest-region-b, plan docs/superpowers/plans/2026-10-26-nearest-region-never-reuse.md |
| -// Tasks 5-10 and 13), layered on nearestRegionAWriteCensusInventory (main's |
| -// newest at 70d37672). Reviewed by the branch author; the census approval |
| -// is recorded on #280 with the root-read card |
| -// (docs/superpowers/notes/census-proposal-nearest-region-b.md). |
| -// - 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.unfinishedWork (console), new: lists apps/ and reads each |
| -// record key (IsRecordKey) to count moves and seeds not ended. Reads |
| +// nearest-region-b, reworked to offline activation on Paul's cut, #404), |
| +// layered on nearestRegionAWriteCensusInventory. Reviewed by the branch |
| +// author; the census approval is recorded on #280. |
| +// - WriteHostsState (provision), new: the one Put of control/hosts-used/@mode. |
| +// No record key or body: nonrecord. WriteHostsMode writes through it. |
| +// - recordFacts (console), new: activation's source 1, lists apps/ and reads |
| +// each record key (IsRecordKey; "sidecars" names the key shape). 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 (internal/layout, beside the names it reads), |
| -// 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.runFrom, Server.runImportUpload, re-pinned (Task 5 round 2): |
| -// goSeedWorker now holds the wait group and the drain count around |
| -// them, so their own deferred Done goes. Their SetRecordSeed sites are |
| -// unchanged: still record-writer. |
| -// - 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.allocRecordLocked, re-pinned (Task 7): a recovery replay of a |
| -// data-kind allocation marks the hostname first, or requires the mark |
| -// once active (recoveryMark); the door's own call skips it. Its |
| -// create-only WriteRecord is unchanged. |
| -// - Server.createRecordWithLifetimeLocked, re-pinned: passes doorMarked |
| -// to allocRecordLocked. Same sites: still key-site. |
| -// - Server.hostsTripwire (console, Task 8), new: lists apps/ and |
| -// control/hosts-used/ and reads each record key with no mark. Reads |
| +// - Server.hostsTripwire (console), new: the start-up check, lists apps/ |
| +// and control/hosts-used/ and reads each record key with no mark. Reads |
| // only: key-site. |
| -// - migrationHistory.beforeRecord, migrationRecordHost (root, Task 10), |
| -// new: carlos accounts migrate's check before a record copy, reading the |
| -// destination record key (IsRecordKey; "sidecars" names the key shape) |
| -// or writing a mark through provision.MarkHostUsed. No record write of |
| -// their own: key-site. |
| -// - Server.placeAppTarget, re-pinned again (Task 9): S3 first once the |
| -// history is active or invalidated. Its write sites are unchanged. |
| -// - Server.registerCLIRoutes, re-pinned: the window's doors. Same |
| -// literals: still key-site. |
| +// - HostsFromBoxListing (internal/layout), new: pure mapping of a box's |
| +// data-directory listing ("instances" is the layout's directory name). |
| +// No store: key-site. |
| +// - migrationHistory.beforeRecord, migrationRecordHost (root), new: carlos |
| +// accounts migrate's check before a record copy: reads the destination |
| +// record key, or writes a mark through provision.MarkHostUsed. No record |
| +// write of their own: key-site. |
| +// - Server.allocRecordLocked, re-pinned: a recovery replay of a data-kind |
| +// allocation marks first, or requires the mark once active. Its |
| +// create-only WriteRecord is unchanged: record-writer. |
| +// - Server.createRecordWithLifetimeLocked, re-pinned: passes doorMarked. |
| +// Same sites: key-site. |
| +// - Server.placeAppTarget, re-pinned: S3 first once the history is active |
| +// or invalidated. Its write sites are unchanged: record-writer. |
| +// - Server.registerCLIRoutes, re-pinned (merge A's status door's |
| +// neighbourhood only). Same literals: key-site. |
| func nearestRegionBWriteCensusInventory() []censusEntry { |
| entries := append([]censusEntry(nil), nearestRegionAWriteCensusInventory()...) |
| for _, r := range []struct{ file, unit string }{ |
| @@ -67,20 +47,15 @@ func nearestRegionBWriteCensusInventory() []censusEntry { |
| } |
| replacements := []censusEntry{ |
| {"internal/provision/hostsused.go", "WriteHostsState", "nonrecord", "sel:Put", "5f1b95198e45dedc9715d73a57bfa57cb1305d364895cd981375e0ed3610c8da"}, |
| - {"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", "ff2d8ac415c19d18189f5127eef277f8678e5962a18fff29d793394b193605ce"}, |
| {"internal/layout/hostsused.go", "HostsFromBoxListing", "key-site", "lit:instances", "b3c85cf9c369941664a8bdb7dcf1fe92b37c8b5ffd719d963e1f88243712d577"}, |
| - {"internal/console/apiinstanceseed.go", "Server.runFrom", "record-writer", "key:SetRecordSeed", "63891e8213198a95c7adbbab70fcbe7519f594dfe736eee1ec9358f33c9bd570"}, |
| - {"internal/console/apiinstanceimport.go", "Server.runImportUpload", "record-writer", "key:SetRecordSeed", "be3cf61080df584f3009c976714af355998b228b2249bcb85093c0fe58555158"}, |
| - {"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", "7049e15b2a5b957cac2367ffe858781e0cd23d58e9d0b82d631a042f78112a4e"}, |
| + {"internal/console/fleets.go", "Server.placeAppTarget", "record-writer", "key:RecordsPrefix,key:SetRecordRegion", "3b67c0d7ace89dfa2fc0f1ff3b025d02a066c2aaa9127200dbd1eda8c830e830"}, |
| {"internal/console/lifetimes_create.go", "Server.allocRecordLocked", "record-writer", "key:RecordKey,key:WriteRecord", "302a206cc99aff175e7fe59e8d63c7d25424adad16cfef64f315fce5d19401f4"}, |
| {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "3cf4ed6b5d4f4abef3dc25e6fc98c42dd10dfa9bc1073c19ff152ed66d4b7774"}, |
| - {"internal/console/hostsused_tripwire.go", "Server.hostsTripwire", "key-site", "key:IsRecordKey,lit:instances,lit:sidecars", "3b4a510e500fec80184b7d6f529e4a0e1331cd9216367d6d25043c4ecbf44505"}, |
| - {"accounts_hostsused.go", "migrationHistory.beforeRecord", "key-site", "key:IsRecordKey", "5de38aedc1379e302ec9a730e3882850e28e818a72e71ba5c46a638110ab3923"}, |
| + {"internal/console/hostsused_activate.go", "recordFacts", "key-site", "key:IsRecordKey,lit:sidecars", "98c7830b6fb3af8129f9b9d6a8fe27597a9efcecfd44782b209da911f9210771"}, |
| + {"internal/console/hostsused_tripwire.go", "Server.hostsTripwire", "key-site", "key:IsRecordKey,lit:instances,lit:sidecars", "6a503a4b29f7909c45ec6a3e52a33a2e5a8b8b37a816942cabba9fa6f80faeba"}, |
| + {"accounts_hostsused.go", "migrationHistory.beforeRecord", "key-site", "key:IsRecordKey", "bf9243ed8c05ebbad2d2a3de1d8d3796c87fa14a6295d8007bf509f3550f8c44"}, |
| {"accounts_hostsused.go", "migrationRecordHost", "key-site", "lit:sidecars", "709eb800cebb6e9a9fa6ba40caf9bed51ab4ecc81b22676270aab28eefeddbb3"}, |
| - {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "79273a3ef15061485df2212a068309790be8a8dd45b3b693fa50d967316982cd"}, |
| + {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "25cb2b7d4f7d264d8a45e5b9306f8f7f95fe886237fd88b9e4a492d7e66e90e3"}, |
| } |
| for _, r := range replacements { |
| found := false |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 96638fcf1..70cc1c11e 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -1,4 +1,4 @@ |
| # The census chain since the re-base (C2): one "<overlay file>\t<seal>" per line, |
| # loaded in order onto census-base.tsv. census-propose appends to it. |
| plan14-root-reads-c2-root-exec-inputs.tsv 0ef813eebfb1a2e2812d897c4f0b5fd7f75e3e39c7602cf64d1634e8374327af |
| -plan14-root-reads-nearest-region-b.tsv ae97d10a4270ebd65636b0b45781a728009b8d32fb74d88dc164287d05515bcc |
| +plan14-root-reads-nearest-region-b.tsv 1afc79e244319487755197b17845083150e83409058d81ac78d70aca3f3f8543 |
diff --git a/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv b/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv| index 91aae0775..e2036c25c 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-nearest-region-b.tsv |
| @@ -1,10 +1,7 @@ |
| # Census overlay nearest-region-b, written by census-propose (#369). census-ruling-nearest-region-b, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-nearest-region-b.md. |
| # 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| -# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| -@legacy 8720f12acd3abd00ad0d8ea54fdf482ac517359fcf3ef5569cf7dff505574ddc accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history once before any write (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store the verb already opened) and refuses below the floor; before each record copy beforeRecord GETs the destination key or Puts a create-only mark under control/hosts-used/; no new kind of read, no path or input a tenant, app or box agent can name file:Open@943,registry:Account@6619,registry:Account@6753,registry:App@6601,registry:Host@6744,registry:Host@6806,registry:Host@6882,registry:Host@6984,whole:Route@6587 935d33270749a480b9c013330c83e8a880595f2b4586dcef463d49f0b91bde62 |
| -@legacy a6d01068743cee22787c29edf3e83d054cf6983fa805e9aecbc696bcc035a9cd system_hostsused.go readListingsFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-nearest-region-b;basis=new: the operator CLI (carlos system hosts-used import <file>, run as the operator user, not root) reads the file the operator names, the scan adapter output, and posts it to the console; JSON only, nothing opened, run or followed from it file:ReadFile@75 35047e3878d0cd9d569450b099321fca7405349a70370cc8e4777bc4894c9bd8 |
| -accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history once before any write (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store the verb already opened) and refuses below the floor; before each record copy beforeRecord GETs the destination key or Puts a create-only mark under control/hosts-used/; no new kind of read, no path or input a tenant, app or box agent can name file:Open@943,registry:Account@6619,registry:Account@6753,registry:App@6601,registry:Host@6744,registry:Host@6806,registry:Host@6882,registry:Host@6984,whole:Route@6587 935d33270749a480b9c013330c83e8a880595f2b4586dcef463d49f0b91bde62 |
| -system_hostsused.go readListingsFile legacy accepted-legacy accepted-legacy;rev3=census-ruling-nearest-region-b;basis=new: the operator CLI (carlos system hosts-used import <file>, run as the operator user, not root) reads the file the operator names, the scan adapter output, and posts it to the console; JSON only, nothing opened, run or followed from it file:ReadFile@75 35047e3878d0cd9d569450b099321fca7405349a70370cc8e4777bc4894c9bd8 |
| -@coverage . 3cdec37e08c664140c5a77fcce71611a1bd21368adbe0a6064f8c62ed0c6c505 |
| +@legacy 0fdb5f0432bd858058ac08c2de8b501fb909839cfda825d6e613de9db2df81f3 accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history before it opens the registry (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store, the one store the verb uses) and refuses below the floor; each record copy goes through copyMigrationRecord, which GETs the destination key or Puts a create-only mark under control/hosts-used/ and, once the history exists, never writes a data-kind record; no new kind of read, no path or input a tenant, app or box agent can name file:Open@1260,registry:Account@6252,registry:Account@6386,registry:App@6234,registry:Host@6377,registry:Host@6439,registry:Host@6515,registry:Host@6617,whole:Route@6220 6febe79bb71b3e6db75a847e867707cb0d5d22e924a21468f6660ae17e2f637b |
| +accounts.go runAccountsMigrate legacy accepted-legacy accepted-legacy;rev3=J1,J4;basis=route-and-input;rev3=census-ruling-nearest-region-b;basis=reads the hostname history before it opens the registry (readMigrationHistoryNow: GETs control/hosts-used/@floor and @mode from the deployment store, the one store the verb uses) and refuses below the floor; each record copy goes through copyMigrationRecord, which GETs the destination key or Puts a create-only mark under control/hosts-used/ and, once the history exists, never writes a data-kind record; no new kind of read, no path or input a tenant, app or box agent can name file:Open@1260,registry:Account@6252,registry:Account@6386,registry:App@6234,registry:Host@6377,registry:Host@6439,registry:Host@6515,registry:Host@6617,whole:Route@6220 6febe79bb71b3e6db75a847e867707cb0d5d22e924a21468f6660ae17e2f637b |
| +@coverage . dc22e658d94f155f98986efed82ac24a810d7e3b6d1a95384fbe80888a90bca8 |
| @coverage internal/layout 7ccc87fc72e0bb9a30332b965e43200c223b72a9e46ca495754e2f13770ff940 |
| -@coverage internal/provision c48a7af3eccf052a223bcceca6e04ba36a467f58b73871a2c89e3df82464fd5a |
| +@coverage internal/provision eb8e66dfc8b4e95269de1d15850f47aba73f2c3420cd3ddd08afe4696dad1b01 |
diff --git a/system.go b/system.go| index 8cda61883..0e3564fb5 100644 |
| --- a/system.go |
| +++ b/system.go |
| @@ -148,7 +148,7 @@ func systemUsage() { |
| carlos system seeds-floor publish --min-release <release> |
| carlos system legacy-routes assign --name <name> --to <account>/<app> |
| carlos system lifetimes cutover [--no-wait] |
| - carlos system hosts-used <status|begin|cancel|import|close-fleet|complete|invalidate> |
| + carlos system hosts-used status |
| carlos system box role <box> <default|legacy|platform> |
| carlos system box publish-record |
| carlos system group role <region> <default|legacy> |
| @@ -175,12 +175,6 @@ The platform's own binary (ops account owners and CARLOS_SYSTEM_OPERATORS): |
| hosts-used status |
| the hostname history: its mode, how many hostnames it has |
| recorded, and how much work is still settling |
| - hosts-used begin | cancel |
| - open or close the maintenance window used to complete the history |
| - hosts-used import <file> | close-fleet <fleet> | complete |
| - inside the window: load the scan, close a fleet, finish |
| - hosts-used invalidate |
| - stop new instances until a fresh inventory completes |
| box role <box> <default|legacy|platform> |
| whether new instances may be placed on a box. A legacy or |
| platform box keeps the instances it has and takes no new ones |
diff --git a/system_hostsused.go b/system_hostsused.go| index a3c5660c7..8acae9560 100644 |
| --- a/system_hostsused.go |
| +++ b/system_hostsused.go |
| @@ -1,10 +1,8 @@ |
| package main |
| import ( |
| - "bytes" |
| "context" |
| "encoding/json" |
| - "errors" |
| "flag" |
| "fmt" |
| "io" |
| @@ -14,28 +12,21 @@ import ( |
| "strings" |
| ) |
| -// carlos system hosts-used status (nearest-region never-reuse, plan Task 4): |
| -// the console's hostname history, its mode and how many hostnames it has |
| -// recorded, with the work still settling. Ops account owners and |
| -// CARLOS_SYSTEM_OPERATORS. It reads and never writes. |
| +// carlos system hosts-used status (nearest-region never-reuse): the |
| +// console's hostname history, its mode, how many hostnames it has recorded, |
| +// the closed fleets and the floor. Ops account owners and |
| +// CARLOS_SYSTEM_OPERATORS. It reads and never writes. Activation and |
| +// operator invalidation are offline, on the console's box with the console |
| +// stopped (console hosts-used). |
| 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. |
| +// hostsUsedStatusView is what the door answers. |
| 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"` |
| - UnfinishedSeeds *int `json:"unfinished_seeds"` |
| - Listings *int `json:"listings"` |
| - Targets *int `json:"targets"` |
| - NotImported []string `json:"not_imported"` |
| - Closed []string `json:"closed"` |
| - Floor *struct { |
| + Mode string `json:"mode"` |
| + Marks int `json:"marks"` |
| + Closed []string `json:"closed"` |
| + Floor *struct { |
| Version string `json:"version"` |
| Commit string `json:"commit"` |
| } `json:"floor"` |
| @@ -64,8 +55,6 @@ func hostsUsedModeLine(mode string) string { |
| switch mode { |
| case "incomplete": |
| return "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet" |
| - case "activating": |
| - return "mode: activating. new instances, moves and placement changes are paused" |
| case "active": |
| return "mode: active. a hostname that has held data is never created again" |
| case "invalidated": |
| @@ -77,25 +66,6 @@ func hostsUsedModeLine(mode string) string { |
| func printHostsUsedStatus(w io.Writer, st hostsUsedStatusView) { |
| fmt.Fprintln(w, hostsUsedModeLine(st.Mode)) |
| fmt.Fprintf(w, "hostnames recorded: %d\n", st.Marks) |
| - if st.InflightCreates != nil { |
| - fmt.Fprintf(w, "create and placement requests in progress: %d\n", *st.InflightCreates) |
| - } |
| - // 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 { |
| @@ -108,170 +78,24 @@ func printHostsUsedStatus(w io.Writer, st hostsUsedStatusView) { |
| } |
| } |
| -// systemHostsUsedPost calls one of the window's POST doors, which answer |
| -// the status as the status door does. |
| -func systemHostsUsedPost(ctx context.Context, post rolePost, verb string, body any) (hostsUsedStatusView, error) { |
| - status, raw, err := post(ctx, "/api/cli/system/hosts-used/"+verb, body) |
| - if err != nil { |
| - return hostsUsedStatusView{}, err |
| - } |
| - if status != http.StatusOK { |
| - return hostsUsedStatusView{}, apiErrorFromBody(status, raw) |
| - } |
| - var st hostsUsedStatusView |
| - if err := json.Unmarshal(raw, &st); err != nil { |
| - return hostsUsedStatusView{}, fmt.Errorf("unreadable response: %w", err) |
| - } |
| - return st, nil |
| -} |
| - |
| -// The approved command output (B1-B3). |
| -const ( |
| - hostsUsedBeginLine = "maintenance window open. new instances, moves and placement changes are paused until you complete or cancel it" |
| - hostsUsedBeginNext = "run carlos system hosts-used status until every count is 0, then scan every target and import the listings" |
| - hostsUsedCancelLine = "maintenance window closed. nothing was recorded" |
| -) |
| - |
| -// printHostsUsedBegin and printHostsUsedCancel are the two verbs' output. |
| -func printHostsUsedBegin(w io.Writer, st hostsUsedStatusView) { |
| - fmt.Fprintln(w, hostsUsedBeginLine) |
| - fmt.Fprintln(w, hostsUsedBeginNext) |
| -} |
| - |
| -func printHostsUsedCancel(w io.Writer, st hostsUsedStatusView) { |
| - fmt.Fprintln(w, hostsUsedCancelLine) |
| - 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>`. |
| +// runSystemHostsUsedVerb is `carlos system hosts-used status`. |
| func runSystemHostsUsedVerb(rest []string) { |
| - if len(rest) == 0 { |
| - systemUsage() |
| - os.Exit(2) |
| - } |
| - verb := rest[0] |
| - args := 0 |
| - switch verb { |
| - case "status", "begin", "cancel", "complete", "invalidate": |
| - case "import", "close-fleet": |
| - args = 1 |
| - default: |
| + if len(rest) == 0 || rest[0] != "status" { |
| systemUsage() |
| os.Exit(2) |
| } |
| - fs := flag.NewFlagSet("system hosts-used "+verb, flag.ExitOnError) |
| + fs := flag.NewFlagSet("system hosts-used status", flag.ExitOnError) |
| consoleFlag := consoleOption(fs, "console origin (default: the only logged-in one)") |
| fs.Parse(rest[1:]) |
| - if fs.NArg() != args { |
| + if fs.NArg() != 0 { |
| 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 |
| - switch verb { |
| - case "status": |
| - st, err = systemHostsUsedStatus(ctx, sess.getJSON) |
| - 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{}) |
| - } |
| + st, err := systemHostsUsedStatus(context.Background(), sess.getJSON) |
| if err != nil { |
| - log.Fatalf("carlos system hosts-used %s: %v", verb, err) |
| - } |
| - switch verb { |
| - case "status": |
| - printHostsUsedStatus(stdout, st) |
| - case "begin": |
| - 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) |
| - case "invalidate": |
| - fmt.Fprintln(stdout, "the hostname history is invalidated. new instances are refused until a fresh inventory completes") |
| + log.Fatalf("carlos system hosts-used status: %v", err) |
| } |
| + printHostsUsedStatus(stdout, st) |
| } |
diff --git a/system_hostsused_test.go b/system_hostsused_test.go| index c8cf7baee..447e28a54 100644 |
| --- a/system_hostsused_test.go |
| +++ b/system_hostsused_test.go |
| @@ -3,7 +3,6 @@ package main |
| import ( |
| "bytes" |
| "context" |
| - "io" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| @@ -15,7 +14,7 @@ import ( |
| ) |
| // TestSystemHostsUsedStatusCLI: `carlos system hosts-used status` asks the |
| -// status door and prints one line per field the console knows. |
| +// status door and prints one line per field the console answered. |
| func TestSystemHostsUsedStatusCLI(t *testing.T) { |
| if verb, rest, _ := systemVerb([]string{"hosts-used", "status"}); verb != "hosts-used" || len(rest) != 1 || rest[0] != "status" { |
| t.Fatalf("systemVerb = %q %q", verb, rest) |
| @@ -27,7 +26,7 @@ func TestSystemHostsUsedStatusCLI(t *testing.T) { |
| return status, []byte(body), nil |
| } |
| } |
| - st, err := systemHostsUsedStatus(context.Background(), get(`{"mode":"incomplete","marks":12,"inflight_creates":null,"pending_allocations":1,"pending_retirements":0,"unfinished_moves":null}`, http.StatusOK)) |
| + st, err := systemHostsUsedStatus(context.Background(), get(`{"mode":"active","marks":12,"closed":["fleet:fx"],"floor":{"version":"v0.30.0","commit":"abc"}}`, http.StatusOK)) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -36,25 +35,10 @@ func TestSystemHostsUsedStatusCLI(t *testing.T) { |
| } |
| var out bytes.Buffer |
| printHostsUsedStatus(&out, st) |
| - want := "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet\n" + |
| + want := "mode: active. a hostname that has held data is never created again\n" + |
| "hostnames recorded: 12\n" + |
| - "instance creates still settling: 1\n" + |
| - "instance deletes still settling: 0\n" |
| - if out.String() != want { |
| - t.Fatalf("output:\n%s\nwant:\n%s", out.String(), want) |
| - } |
| - st, err = systemHostsUsedStatus(context.Background(), get(`{"mode":"activating","marks":3,"inflight_creates":2,"pending_allocations":0,"pending_retirements":0,"unfinished_moves":1}`, http.StatusOK)) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - out.Reset() |
| - printHostsUsedStatus(&out, st) |
| - want = "mode: activating. new instances, moves and placement changes are paused\n" + |
| - "hostnames recorded: 3\n" + |
| - "create and placement requests in progress: 2\n" + |
| - "instance creates still settling: 0\n" + |
| - "instance deletes still settling: 0\n" + |
| - "moves not finished: 1\n" |
| + "closed fleets: fx\n" + |
| + "floor: v0.30.0 (abc)\n" |
| if out.String() != want { |
| t.Fatalf("output:\n%s\nwant:\n%s", out.String(), want) |
| } |
| @@ -63,10 +47,10 @@ func TestSystemHostsUsedStatusCLI(t *testing.T) { |
| } |
| } |
| -// TestSystemHostsUsedStatusThroughTheBinary (Astra branch review r1, P2): |
| -// the built command, through runSystem's dispatch and the operator's own |
| -// session, against a fake console. It asks the one door with the saved |
| -// token, prints the door's answer, and exits non-zero on a refusal. |
| +// TestSystemHostsUsedStatusThroughTheBinary: the built command, through |
| +// runSystem's dispatch and the operator's own session, against a fake |
| +// console: the one door, the saved token, the answer printed, a refusal |
| +// exiting non-zero. |
| func TestSystemHostsUsedStatusThroughTheBinary(t *testing.T) { |
| bin := buildCarlos(t) |
| var mu sync.Mutex |
| @@ -82,20 +66,18 @@ func TestSystemHostsUsedStatusThroughTheBinary(t *testing.T) { |
| http.NotFound(w, r) |
| return |
| } |
| + w.Header().Set("Content-Type", "application/json") |
| if no { |
| - w.Header().Set("Content-Type", "application/json") |
| w.WriteHeader(http.StatusNotFound) |
| w.Write([]byte(`{"error":"404 page not found"}`)) |
| return |
| } |
| - w.Header().Set("Content-Type", "application/json") |
| - w.Write([]byte(`{"mode":"incomplete","marks":7,"inflight_creates":null,"pending_allocations":0,"pending_retirements":2,"unfinished_moves":null}`)) |
| + w.Write([]byte(`{"mode":"incomplete","marks":7}`)) |
| }) |
| ts := httptest.NewServer(mux) |
| t.Cleanup(ts.Close) |
| credPath := filepath.Join(t.TempDir(), "credentials") |
| - creds := `{"version":1,"credentials":[{"console":"` + ts.URL + `","address":"paul@keymail.dev","token":"tok-operator"}]}` |
| - if err := os.WriteFile(credPath, []byte(creds), 0o600); err != nil { |
| + if err := os.WriteFile(credPath, []byte(`{"version":1,"credentials":[{"console":"`+ts.URL+`","address":"paul@keymail.dev","token":"tok-operator"}]}`), 0o600); err != nil { |
| t.Fatal(err) |
| } |
| run := func() (string, error) { |
| @@ -112,7 +94,6 @@ func TestSystemHostsUsedStatusThroughTheBinary(t *testing.T) { |
| for _, line := range []string{ |
| "mode: incomplete. new hostnames are recorded, and a hostname that held data is not refused yet\n", |
| "hostnames recorded: 7\n", |
| - "instance deletes still settling: 2\n", |
| } { |
| if !strings.Contains(out, line) { |
| t.Fatalf("output lacks %q:\n%s", line, out) |
| @@ -137,160 +118,3 @@ func TestSystemHostsUsedStatusThroughTheBinary(t *testing.T) { |
| t.Fatalf("a refused status exited %v:\n%s", err, out) |
| } |
| } |
| - |
| -// TestSystemHostsUsedWindowVerbsThroughTheBinary: begin and cancel, built, |
| -// POST their doors with the saved token and print the approved lines. |
| -func TestSystemHostsUsedWindowVerbsThroughTheBinary(t *testing.T) { |
| - bin := buildCarlos(t) |
| - var mu sync.Mutex |
| - var asked []string |
| - mux := http.NewServeMux() |
| - mux.HandleFunc("POST /api/cli/system/hosts-used/begin", func(w http.ResponseWriter, r *http.Request) { |
| - mu.Lock() |
| - asked = append(asked, "begin "+r.Header.Get("Authorization")) |
| - mu.Unlock() |
| - w.Header().Set("Content-Type", "application/json") |
| - w.Write([]byte(`{"mode":"activating","marks":3,"inflight_creates":1,"pending_allocations":0,"pending_retirements":0,"unfinished_moves":0}`)) |
| - }) |
| - mux.HandleFunc("POST /api/cli/system/hosts-used/cancel", func(w http.ResponseWriter, r *http.Request) { |
| - mu.Lock() |
| - asked = append(asked, "cancel "+r.Header.Get("Authorization")) |
| - mu.Unlock() |
| - w.Header().Set("Content-Type", "application/json") |
| - w.Write([]byte(`{"mode":"invalidated","marks":3,"inflight_creates":0,"pending_allocations":0,"pending_retirements":0,"unfinished_moves":null}`)) |
| - }) |
| - ts := httptest.NewServer(mux) |
| - t.Cleanup(ts.Close) |
| - credPath := filepath.Join(t.TempDir(), "credentials") |
| - if err := os.WriteFile(credPath, []byte(`{"version":1,"credentials":[{"console":"`+ts.URL+`","address":"paul@keymail.dev","token":"tok-operator"}]}`), 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - run := func(verb string) string { |
| - cmd := exec.Command(bin, "system", "hosts-used", verb) |
| - cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+credPath) |
| - cmd.Dir = t.TempDir() |
| - out, err := cmd.CombinedOutput() |
| - if err != nil { |
| - t.Fatalf("%s: %v\n%s", verb, err, out) |
| - } |
| - return string(out) |
| - } |
| - out := run("begin") |
| - if !strings.Contains(out, "maintenance window open. new instances, moves and placement changes are paused until you complete or cancel it\n") || |
| - !strings.Contains(out, "run carlos system hosts-used status until every count is 0, then scan every target and import the listings\n") { |
| - t.Fatalf("begin printed:\n%s", out) |
| - } |
| - out = run("cancel") |
| - if !strings.Contains(out, "maintenance window closed. nothing was recorded\nmode: invalidated. new instances are refused until a fresh inventory completes\n") { |
| - t.Fatalf("cancel printed:\n%s", out) |
| - } |
| - mu.Lock() |
| - defer mu.Unlock() |
| - if len(asked) != 2 || asked[0] != "begin Bearer tok-operator" || asked[1] != "cancel Bearer tok-operator" { |
| - 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}`)) |
| - }) |
| - mux.HandleFunc("POST /api/cli/system/hosts-used/invalidate", func(w http.ResponseWriter, r *http.Request) { |
| - record("invalidate")(w, r) |
| - w.Write([]byte(`{"mode":"invalidated"}`)) |
| - }) |
| - 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) |
| - } |
| - if out := run("invalidate"); !strings.Contains(out, "the hostname history is invalidated. new instances are refused until a fresh inventory completes\n") { |
| - t.Fatalf("invalidate 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) |
| - } |
| -} |