channels retire: operator door for canary pointers of rowless apps (#1634)
Box reports gain route_channels: the account, app and channel of every non-platform route, managed or not, once each and with no host, plus route_channels_reported. Built from the routes the report already lists. carlos channels retire (POST /api/cli/system/channels/retire) deletes a canary pointer of an app the console has no row for. Beside the member door's guard it refuses while any box report names a route of the app on any channel, any fresh box cannot say, any box went dark in the last 7 days, or a report could not be read. It also refuses an unknown account, a live or trashed row, a trash marker, instance records, other channels and host claims; rechecks the no-row rule last under a lock the claim insert takes; deletes with CAS; writes a platform audit row. The digests mark names the command on canary lines. Copy by Luna.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
26 files changed,
+956
−32
canary_retire.go+51 −2canary_retire_test.go+70 −1channels_digests.go+10 −1commands.go+5 −3docs/parity.md+1 −0docs/site/cli.md+21 −1internal/console/apilinks_test.go+6 −5internal/console/canary_retire.go+243 −10internal/console/canary_retire_orphan_test.go+263 −0internal/console/claim_app_enroll.go+5 −0internal/console/claim_invariant_fixtures_test.go+9 −0internal/console/claim_invariant_test.go+2 −0internal/console/remoteinstances.go+96 −1internal/console/routedecls.go+3 −0internal/console/server.go+4 −0internal/console/svcroutes_test.go+5 −2internal/console/testdata/claim-authority-sites.txt+1 −0internal/console/testdata/claim-routes.txt+1 −0internal/provision/canary_retire_orphan_1634_census_test.go+28 −0internal/provision/plan9_b8_census_test.go+1 −1internal/release/adopt.go+4 −0internal/status/contract_test.go+5 −1internal/status/snapshot.go+57 −3internal/status/snapshot_test.go+1 −1internal/status/status_test.go+63 −0parity/parity.tsv+1 −0
diff --git a/canary_retire.go b/canary_retire.go| index 5ee44cb95..e999d59c3 100644 |
| --- a/canary_retire.go |
| +++ b/canary_retire.go |
| @@ -1,7 +1,7 @@ |
| package main |
| -// `carlos canary retire` (#1634): deleting a canary/<name> channel pointer |
| -// that nothing follows, through a console. |
| +// `carlos canary retire` and `carlos channels retire` (#1634): deleting a |
| +// canary/<name> channel pointer that nothing follows, through a console. |
| // The console does every check (no follower by registry, record or box |
| // report; the app still for 15 minutes; the pointer unchanged since it was |
| // read) and deletes only the pointer, never a shipped release. |
| @@ -20,6 +20,8 @@ import ( |
| const ( |
| textCanaryRetired = "%s's pointer is gone. Its releases are kept" |
| textCanaryRetireNeedName = "carlos canary retire: --name <n> is required" |
| + textChannelsRetireUsage = "usage: carlos channels retire --account-id <sqid> --app <a> canary/<name>" |
| + textChannelsRetired = "%s of %s/%s: its pointer is gone. Its releases are kept" |
| textRetireNeedsConsole = "carlos %s works through a console, and this shell is in direct bucket mode. Unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then run carlos auth login --console <url>" |
| ) |
| @@ -42,6 +44,20 @@ func (s *apiSession) canaryRetire(ctx context.Context, a apiAcct, app, name stri |
| return out.Channel, nil |
| } |
| +// systemChannelRetire asks the console to retire channel of acct/app, an |
| +// app the console has no row for (the operator door). |
| +func (s *apiSession) systemChannelRetire(ctx context.Context, acct, app, channel string) error { |
| + status, body, err := s.postJSON(ctx, "/api/cli/system/channels/retire", |
| + map[string]string{"account": acct, "app": app, "channel": channel}) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return apiErrorFromBody(status, body) |
| + } |
| + return nil |
| +} |
| + |
| // runCanaryRetire is `carlos canary retire --app <a> --name <n>`: the |
| // console's Retire button, from the CLI. canary rm deletes the instance; |
| // this deletes the channel it followed, once nothing does. |
| @@ -75,3 +91,36 @@ func runCanaryRetire(args []string) error { |
| mutedf(stdout, textCanaryRetired, channel) |
| return nil |
| } |
| + |
| +// runChannelsRetire is `carlos channels retire --account-id <sqid> --app |
| +// <a> canary/<name>`: a platform operator retires a canary pointer of an |
| +// app the console has no row for (the repair listing names the command on |
| +// such a line). The console refuses an account it does not have, an app it |
| +// has, one in the trash, one with instance records, a route of the app on |
| +// any box, a box that cannot say, and any channel outside canary/*. |
| +func runChannelsRetire(args []string) error { |
| + fs := flag.NewFlagSet("channels retire", flag.ExitOnError) |
| + acct := fs.String("account-id", "", "the account's sqid, as the repair listing prints it") |
| + app := fs.String("app", "", "the app, as the repair listing prints it") |
| + consoleFlag := consoleOption(fs, "console origin (default: the only logged-in one)") |
| + fs.Usage = flagUsage(fs, "") |
| + fs.Parse(args) |
| + if *acct == "" || *app == "" || fs.NArg() != 1 { |
| + return errors.New(textChannelsRetireUsage) |
| + } |
| + channel := fs.Arg(0) |
| + sess, err := resolveMode(*consoleFlag) |
| + if err != nil { |
| + return err |
| + } |
| + if sess == nil { |
| + return fmt.Errorf(textRetireNeedsConsole, "channels retire") |
| + } |
| + printUsing(stdout, sess) |
| + if err := sess.systemChannelRetire(context.Background(), *acct, *app, channel); err != nil { |
| + return err |
| + } |
| + fmt.Fprintf(stdout, "%s %s\n", colorFor(stdout).ok("retired"), channel) |
| + mutedf(stdout, textChannelsRetired, channel, *acct, *app) |
| + return nil |
| +} |
diff --git a/canary_retire_test.go b/canary_retire_test.go| index 5477e8704..a1329217f 100644 |
| --- a/canary_retire_test.go |
| +++ b/canary_retire_test.go |
| @@ -79,7 +79,7 @@ func TestCanaryRetireRefusesDirectBucketMode(t *testing.T) { |
| // A line of an app the console has no app for keeps its repair, with the |
| // mark after it; a line of an app the console has is unchanged. |
| func TestRepairCellMarksAppsWithNoRow(t *testing.T) { |
| - head := apiDigestRepair{Account: "bab", App: "old", Channel: "canary/rc", Version: "v1", NoRecord: true, NoApp: true} |
| + head := apiDigestRepair{Account: "bab", App: "old", Channel: "stable", Version: "v1", NoRecord: true, NoApp: true} |
| if got, want := repairCell(head), textRepairNoRecord+" (no app on this console)"; got != want { |
| t.Fatalf("no-app head = %q, want %q", got, want) |
| } |
| @@ -93,3 +93,72 @@ func TestRepairCellMarksAppsWithNoRow(t *testing.T) { |
| t.Fatalf("a head of an app with a row = %q", got) |
| } |
| } |
| + |
| +// `carlos channels retire` posts account, app and channel to the operator |
| +// door, exactly as the repair listing's line names them. |
| +func TestChannelsRetireAPIMode(t *testing.T) { |
| + useTempCredentials(t) |
| + clearDeploymentEnv(t) |
| + var posted map[string]string |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != "/api/cli/system/channels/retire" || r.Method != http.MethodPost { |
| + t.Errorf("request = %s %s", r.Method, r.URL.Path) |
| + } |
| + json.NewDecoder(r.Body).Decode(&posted) |
| + json.NewEncoder(w).Encode(map[string]string{"result": "retired", "channel": "canary/old"}) |
| + })) |
| + defer ts.Close() |
| + loginTo(t, ts.URL, "vicky@keymail.dev") |
| + out := captureStdout(t) |
| + |
| + if err := runChannelsRetire([]string{"--account-id", "bab", "--app", "old", "canary/old"}); err != nil { |
| + t.Fatalf("retire: %v", err) |
| + } |
| + want := map[string]string{"account": "bab", "app": "old", "channel": "canary/old"} |
| + if fmt.Sprint(posted) != fmt.Sprint(want) { |
| + t.Fatalf("posted %v, want %v", posted, want) |
| + } |
| + if line := fmt.Sprintf(textChannelsRetired, "canary/old", "bab", "old"); !strings.Contains(out.String(), line) { |
| + t.Fatalf("output lacks %q:\n%s", line, out.String()) |
| + } |
| + posted = nil |
| + for _, args := range [][]string{ |
| + {"--app", "old", "canary/old"}, |
| + {"--account-id", "bab", "canary/old"}, |
| + {"--account-id", "bab", "--app", "old"}, |
| + } { |
| + if err := runChannelsRetire(args); err == nil || err.Error() != textChannelsRetireUsage { |
| + t.Fatalf("channels retire %v = %v, want the usage", args, err) |
| + } |
| + } |
| + if posted != nil { |
| + t.Fatalf("an incomplete retire posted %v", posted) |
| + } |
| +} |
| + |
| +// Direct bucket mode has no console to ask the box reports, so the |
| +// operator verb refuses rather than touch the bucket. |
| +func TestChannelsRetireRefusesDirectBucketMode(t *testing.T) { |
| + useTempCredentials(t) |
| + clearDeploymentEnv(t) |
| + t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| + if err := runChannelsRetire([]string{"--account-id", "bab", "--app", "old", "canary/rc"}); err == nil || !strings.Contains(err.Error(), "direct bucket mode") { |
| + t.Fatalf("channels retire in direct bucket mode = %v", err) |
| + } |
| +} |
| + |
| +// A canary head of an app with no console row names the operator command |
| +// after the mark; a stable head or a record line of such an app keeps |
| +// only the mark. |
| +func TestRepairCellNamesTheRetireForNoAppCanaries(t *testing.T) { |
| + head := apiDigestRepair{Account: "bab", App: "old", Channel: "canary/rc", Version: "v1", NoRecord: true, NoApp: true} |
| + want := textRepairNoRecord + " (no app on this console). If no box runs it, remove it with carlos channels retire --account-id bab --app old canary/rc" |
| + if got := repairCell(head); got != want { |
| + t.Fatalf("no-app canary head = %q, want %q", got, want) |
| + } |
| + stable := head |
| + stable.Channel = "stable" |
| + if got := repairCell(stable); got != textRepairNoRecord+" (no app on this console)" { |
| + t.Fatalf("no-app stable head = %q", got) |
| + } |
| +} |
diff --git a/channels_digests.go b/channels_digests.go| index c2e837b8a..74c27ca49 100644 |
| --- a/channels_digests.go |
| +++ b/channels_digests.go |
| @@ -67,6 +67,10 @@ const ( |
| // (#1634), reviewed by Luna under delegation (2026-12-01). |
| const textRepairNoApp = "%s (no app on this console)" |
| +// A canary head of such an app also names the operator command that |
| +// removes it (#1634), reviewed by Luna under delegation (2026-12-02). |
| +const textRepairNoAppRetire = "%s (no app on this console). If no box runs it, remove it with carlos channels retire --account-id %s --app %s %s" |
| + |
| // apiDigestRepair is a channel whose head a fresh or replaced box would |
| // refuse: Unbound (not bound to its account: the pointer names none, or the |
| // key grant it was signed under names none) or NoRecord (no digest and no |
| @@ -112,8 +116,13 @@ type apiPointerDigests struct { |
| // version again writes no record. |
| // |
| // A line of an app the console has no row for keeps its repair and says so |
| -// after it (#1634): no member door reaches such an app. |
| +// after it (#1634): no member door reaches such an app. A canary head of |
| +// one also names the operator door that removes it, which refuses while |
| +// any box runs a route of the app. |
| func repairCell(r apiDigestRepair) string { |
| + if r.NoApp && !r.Record && strings.HasPrefix(r.Channel, release.RungCanary+"/") { |
| + return fmt.Sprintf(textRepairNoAppRetire, repairText(r), r.Account, r.App, r.Channel) |
| + } |
| if r.NoApp { |
| return fmt.Sprintf(textRepairNoApp, repairText(r)) |
| } |
diff --git a/commands.go b/commands.go| index 20777fdfc..62763010b 100644 |
| --- a/commands.go |
| +++ b/commands.go |
| @@ -303,9 +303,9 @@ func runRegistryChildTop(args []string) { |
| } |
| } |
| -// channelsCommand is `carlos channels`, moved from main's switch: two |
| -// sub-verbs, resign and digests (#253), and bare `carlos channels` (any |
| -// other word or flag too) still lists, the `carlos releases retention` |
| +// channelsCommand is `carlos channels`, moved from main's switch: three |
| +// sub-verbs, resign and digests (#253) and retire (#1634), and bare |
| +// `carlos channels` (any other word or flag too) still lists, the `carlos releases retention` |
| // precedent. The sub-verbs returned from main() before the update hint, so |
| // they skip it. |
| func channelsCommand() *clireg.Node { |
| @@ -318,6 +318,8 @@ func channelsCommand() *clireg.Node { |
| // digests' on|off counts only as its first argument |
| // (runChannelsDigests): an enum positional of this raw leaf. |
| noHint(rawErr("digests", clireg.Operator, runChannelsDigests)), |
| + // retire: a canary pointer of an app with no console row (#1634). |
| + noHint(rawErr("retire", clireg.Operator, runChannelsRetire)), |
| }, |
| DefaultLeaf: &clireg.Node{Audience: cust, Run: clireg.RawArgs(runChannels)}, |
| DefaultOn: clireg.OnAbsent | clireg.OnFlag | clireg.OnWord, |
diff --git a/docs/parity.md b/docs/parity.md| index c7639c2f5..e10e0afaf 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -459,6 +459,7 @@ Discussion #1536. |
| | op-upstreams | operator | `instances set-upstreams`<br>`instances create [--addr]` | | TCP backends are set by an operator. | |
| | op-digests | operator | `channels digests [on, off]` | | The digest signing switch. | |
| | channels-digests | operator | `channels digests [report]` | | Operator only: the report needs a system operator (apiSystemRoller). Shows which channel pointers are digest-signed. | |
| +| channels-retire | operator | `channels retire` | | Operator only. Requires a system operator (apiSystemRoller). Retires a canary pointer of an app with no console row, which no member door reaches. | |
| | op-releases-authorize | operator | `releases authorize` | | Signs a promotion record for an old build. | |
| | op-relay-rotate | operator | `relay rotate` | | Rotates a region's relay master. | |
| | op-move-lost | operator | `move resolve [--declare-lost]` | | Declares a box lost in the middle of a move. | |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index c8ba0a8bd..d7bca6a41 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -1038,7 +1038,27 @@ carlos channels digests |
| A line for an app with no entry in the console (it was shipped straight to |
| the bucket and never added, or was left behind when a deletion did not |
| finish) ends with “(no app on this console)”. The console’s own commands |
| -cannot reach such an app. |
| +cannot reach such an app. A canary line also gives the |
| +`carlos channels retire` command that removes the channel. |
| + |
| +### carlos channels retire |
| + |
| +For platform operators. This command deletes a `canary/<name>` channel of an |
| +app with no entry in the console, which `carlos canary retire` cannot reach. |
| +Copy the command from the `carlos channels digests` line. |
| + |
| +```sh |
| +carlos channels retire --account-id bab --app shop canary/new-queue |
| +``` |
| + |
| +It asks every box which apps it runs, including routes added by hand, and |
| +refuses if any box runs the app on any channel, if any box runs a CARLOS |
| +version too old to report which apps it serves, if any box has stopped |
| +reporting within the last 7 days, or if any report cannot be read. It also |
| +refuses if the console runs host claims, if the console has the app even in |
| +the trash, if the app has any instance record, or if the account is not on |
| +the console. It retires `canary/<name>` channels only, and never deletes |
| +shipped releases. |
| ### carlos pipeline |
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go| index a03d4c98e..e9a4ea842 100644 |
| --- a/internal/console/apilinks_test.go |
| +++ b/internal/console/apilinks_test.go |
| @@ -495,11 +495,12 @@ var linkedBodyAppDoors = map[string]string{ |
| "POST /a/{sqid}/domains/buy/check": "the app only travels on to step 2's preselection; the search writes nothing", |
| "POST /a/{sqid}/fleets/{fleet}/place": "placeAppTarget refuses a linked app with LD-C11", |
| // Cannot act on a linked app. |
| - "POST /a/{sqid}/trash/restore": "acts only on a trashed row; linked rows are never trashed", |
| - "POST /a/{sqid}/trash/delete": "acts only on a trashed row; linked rows are never trashed", |
| - "POST /a/{sqid}/services/new": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| - "POST /api/cli/services/{account}": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| - "POST /api/cli/link/publications": "the home console's own publish of a home app through its link; no serving-side app", |
| + "POST /a/{sqid}/trash/restore": "acts only on a trashed row; linked rows are never trashed", |
| + "POST /a/{sqid}/trash/delete": "acts only on a trashed row; linked rows are never trashed", |
| + "POST /a/{sqid}/services/new": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| + "POST /api/cli/services/{account}": "mints a credential scoped to the app; every door the credential reaches is an {app} door the policy guards", |
| + "POST /api/cli/link/publications": "the home console's own publish of a home app through its link; no serving-side app", |
| + "POST /api/cli/system/channels/retire": "acts only on an app with no row, live or trashed (orphanRefusal, asked again last under the lock a claim's insert takes); a linked app is a live row", |
| } |
| // TestLinkedPolicyCoversBodyAppDoors finds every declared non-link route |
diff --git a/internal/console/canary_retire.go b/internal/console/canary_retire.go| index c60992917..79a41a273 100644 |
| --- a/internal/console/canary_retire.go |
| +++ b/internal/console/canary_retire.go |
| @@ -1,16 +1,17 @@ |
| package console |
| // Retiring a canary: deleting a canary/<name> channel pointer that nothing |
| -// follows (#1634). Two doors share one guard and one delete: |
| +// follows (#1634). Three doors share one guard and one delete: |
| // |
| // - the browser's Retire button on an app's Releases tab |
| // (handleRetireCanary); |
| // - `carlos canary retire`, the same act for a member over the CLI API |
| -// (handleAPIRetireCanary). |
| -// |
| -// An app this console has no row for is out of reach of both: an |
| -// operator door for it waits on box reports that name every route's app |
| -// and channel, since its followers have no records to go by. |
| +// (handleAPIRetireCanary); |
| +// - `carlos channels retire`, a platform operator's door for a canary |
| +// pointer of an app this console has no row for |
| +// (handleAPISystemRetireChannel). Such an app has no records to name |
| +// its followers, so the door also asks every box report which apps it |
| +// runs routes of (status BoxMetrics.RouteChannels). |
| // |
| // Shipped releases are never touched: a retire un-points, it never deletes |
| // bits. Every door fails CLOSED: "could not check who follows this channel" |
| @@ -26,6 +27,7 @@ import ( |
| "net/url" |
| "os" |
| "strings" |
| + "sync" |
| "time" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -45,6 +47,23 @@ const ( |
| textRetireActivity = "retired canary %s (cli)" |
| ) |
| +// The operator door's answers (#1634). Reviewed by Luna under delegation |
| +// (2026-12-02). |
| +const ( |
| + textRetireBadChannel = "%q is not a canary channel: only canary/<name> channels can be retired" |
| + textRetireBadTarget = "provide a valid account sqid and a valid app" |
| + textRetireNoAccount = "account %s is not on this console, so it cannot check whether %s is still in use" |
| + textRetireHasApp = "%s/%s is an app on this console: use carlos canary retire --account %s --app %s --name %s" |
| + textRetireTrashed = "%s/%s is in the trash: restore it and retire the canary, or let the purge remove it" |
| + textRetireHasRecords = "%s/%s still has instance records in the deployment bucket, so its channels are not retired here" |
| + textRetireHostClaims = "this console runs host claims, so it cannot retire a channel for an app with no row" |
| + textRetireReports = "not every box report could be read, so nothing was deleted. Try again" |
| + textRetireSilent = "box %s runs a CARLOS version too old to report which apps it serves, so nothing was deleted. Retire the canary once every box runs this release" |
| + textRetireDark = "box %s has not reported since %s and may still run %s/%s, so nothing was deleted. Retire the canary once that box reports again, or after %s, a week after its last report" |
| + textRetireRoute = "box %s still runs a route of %s/%s (channel %s), so nothing was deleted" |
| + textRetireOrphanDone = "retired %s of %s/%s, an app not on this console (cli)" |
| +) |
| + |
| // errNoCanary is checkCanaryRetire's answer when the channel has no pointer. |
| var errNoCanary = errors.New("no such canary") |
| @@ -119,8 +138,10 @@ func (s *Server) checkCanaryRetire(ctx context.Context, acct, app, channel strin |
| // deleteRetiredCanary deletes the pointer c read, under the app lock, inside |
| // mutate (the door's app mutation). A change to the app's records or to the |
| // pointer since the check is an error wrapping errRetireUnsettled, and |
| -// nothing is deleted. |
| -func (s *Server) deleteRetiredCanary(ctx context.Context, c *canaryRetireCheck, mutate func(context.Context, func(context.Context) error) error) error { |
| +// nothing is deleted. guard, when not nil, runs last before the delete and |
| +// its release after it: the operator door asks there, under the lock a |
| +// claim's app row insert takes, that the app still has no row. |
| +func (s *Server) deleteRetiredCanary(ctx context.Context, c *canaryRetireCheck, mutate func(context.Context, func(context.Context) error) error, guard func(context.Context) (func(), error)) error { |
| ctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| defer cancel() |
| // The app lock from the re-list through the delete: every console |
| @@ -148,6 +169,13 @@ func (s *Server) deleteRetiredCanary(ctx context.Context, c *canaryRetireCheck, |
| } |
| return fmt.Errorf("%w: the canary's pointer changed during the check", errRetireUnsettled) |
| } |
| + if guard != nil { |
| + done, err := guard(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer done() |
| + } |
| // Delete exactly the pointer read above: a promotion since then |
| // conflicts, and the retire is refused rather than deleting bytes |
| // this check never saw. |
| @@ -244,7 +272,7 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) { |
| s.confirmRetireCanary(w, r, addr, raw, acct, role, app, name) |
| return |
| } |
| - err = s.deleteRetiredCanary(r.Context(), chk, s.appRetireMutation(acct, app)) |
| + err = s.deleteRetiredCanary(r.Context(), chk, s.appRetireMutation(acct, app), nil) |
| if errors.Is(err, errRetireUnsettled) { |
| log.Printf("console: retire %s %s: %v", app, channel, err) |
| back("err", "Could not verify no hosts follow this channel — try again.") |
| @@ -330,7 +358,7 @@ func (s *Server) handleAPIRetireCanary(w http.ResponseWriter, r *http.Request) { |
| if writeRetireRefusal(w, err, acct.Sqid, app, channel) { |
| return |
| } |
| - err = s.deleteRetiredCanary(r.Context(), chk, s.appRetireMutation(acct, app)) |
| + err = s.deleteRetiredCanary(r.Context(), chk, s.appRetireMutation(acct, app), nil) |
| if errors.Is(err, errRetireUnsettled) { |
| writeRetireRefusal(w, err, acct.Sqid, app, channel) |
| return |
| @@ -344,3 +372,208 @@ func (s *Server) handleAPIRetireCanary(w http.ResponseWriter, r *http.Request) { |
| Detail: fmt.Sprintf(textRetireActivity, req.Name)}) |
| writeJSON(w, http.StatusOK, map[string]string{"result": "retired", "channel": channel}) |
| } |
| + |
| +// orphanRefusedError is the operator door's no-row precondition failing, |
| +// with the status and sentence the door answers. |
| +type orphanRefusedError struct { |
| + status int |
| + msg string |
| + err error // the read that failed, when one did |
| +} |
| + |
| +func (e *orphanRefusedError) Error() string { |
| + if e.err != nil { |
| + return e.msg + ": " + e.err.Error() |
| + } |
| + return e.msg |
| +} |
| + |
| +// orphanRefusal is the operator door's precondition: acct is an account |
| +// this console has, and acct/app has no live or trashed console row, no |
| +// trash marker and no instance or sidecar record. Anything it cannot read |
| +// refuses. nil when the app is an orphan the door may act on. |
| +func (s *Server) orphanRefusal(ctx context.Context, acct, app, name string) *orphanRefusedError { |
| + channel := release.RungCanary + "/" + name |
| + a, err := s.store.AccountBySqid(acct) |
| + if err != nil { |
| + return &orphanRefusedError{http.StatusInternalServerError, fmt.Sprintf(textRetireCheck, channel), err} |
| + } |
| + if a == nil { |
| + // An account only the bucket holds: the console has no deletion |
| + // evidence for it (recentRecordDeletion), so it never says unused. |
| + return &orphanRefusedError{status: http.StatusConflict, msg: fmt.Sprintf(textRetireNoAccount, acct, app)} |
| + } |
| + live, err := s.store.HasAppInContext(ctx, a.ID, app) |
| + if err != nil { |
| + return &orphanRefusedError{http.StatusInternalServerError, fmt.Sprintf(textRetireCheck, channel), err} |
| + } |
| + if live { |
| + return &orphanRefusedError{status: http.StatusConflict, msg: fmt.Sprintf(textRetireHasApp, acct, app, acct, app, name)} |
| + } |
| + trashed, err := s.store.HasTrashedAppInContext(ctx, a.ID, app) |
| + if err != nil { |
| + return &orphanRefusedError{http.StatusInternalServerError, fmt.Sprintf(textRetireCheck, channel), err} |
| + } |
| + if trashed { |
| + return &orphanRefusedError{status: http.StatusConflict, msg: fmt.Sprintf(textRetireTrashed, acct, app)} |
| + } |
| + tomb, err := release.ReadAppTombstone(ctx, s.cfg.Releases, acct, app) |
| + if err != nil { |
| + return &orphanRefusedError{http.StatusBadGateway, textRetireStore, err} |
| + } |
| + if tomb != nil { |
| + return &orphanRefusedError{status: http.StatusConflict, msg: fmt.Sprintf(textRetireTrashed, acct, app)} |
| + } |
| + stamps, err := s.recordStamps(ctx, acct, app) |
| + if err != nil { |
| + return &orphanRefusedError{http.StatusBadGateway, textRetireStore, err} |
| + } |
| + if len(stamps) > 0 { |
| + return &orphanRefusedError{status: http.StatusConflict, msg: fmt.Sprintf(textRetireHasRecords, acct, app)} |
| + } |
| + return nil |
| +} |
| + |
| +// lockOrphanName takes the lock the operator's channel retire holds from |
| +// its last no-row check through its delete, and a claim's app row insert |
| +// takes around the insert (createClaimAppRow), so an owner adopting the |
| +// name either lands first, and the retire refuses, or after the pointer is |
| +// gone. Nothing else takes it. Both take it after any app lock they hold, |
| +// never before. |
| +func (s *Server) lockOrphanName(sqid, app string) func() { |
| + v, _ := s.orphanNames.LoadOrStore(sqid+"/"+app, &sync.Mutex{}) |
| + mu := v.(*sync.Mutex) |
| + mu.Lock() |
| + return mu.Unlock |
| +} |
| + |
| +// orphanRetireMutation is deleteRetiredCanary's mutate for an app this |
| +// console has no row for: no demo claim can hold an app with no row, so the |
| +// bucket's app mutation alone, as the relay's per-app walks take it. The |
| +// door refuses up front where that mutation needs an app id (host claims). |
| +func (s *Server) orphanRetireMutation(acct, app string) func(context.Context, func(context.Context) error) error { |
| + return func(ctx context.Context, fn func(context.Context) error) error { |
| + return release.WithAppMutation(ctx, s.cfg.Releases, acct, app, "canary-retire-orphan", fn) |
| + } |
| +} |
| + |
| +// writeRouteAbsence answers the box-report refusal, and reports whether err |
| +// was one. |
| +func writeRouteAbsence(w http.ResponseWriter, err error, acct, app string) bool { |
| + var e *routeAbsenceError |
| + if !errors.As(err, &e) { |
| + return false |
| + } |
| + switch { |
| + case e.Incomplete: |
| + jsonError(w, http.StatusConflict, textRetireReports) |
| + case e.Silent: |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(textRetireSilent, e.Box)) |
| + case !e.DarkSince.IsZero(): |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(textRetireDark, e.Box, e.DarkSince.UTC().Format(time.RFC3339), acct, app, |
| + e.DarkSince.Add(routeDarkHorizon).UTC().Format(time.DateOnly))) |
| + default: |
| + jsonError(w, http.StatusConflict, fmt.Sprintf(textRetireRoute, e.Box, acct, app, e.Channel)) |
| + } |
| + return true |
| +} |
| + |
| +// handleAPISystemRetireChannel is POST /api/cli/system/channels/retire, |
| +// `carlos channels retire --account-id <sqid> --app <a> canary/<name>` |
| +// (#1634): a platform operator retires a canary pointer of an app this |
| +// console has no row for, which no member door can reach. canary/* only. |
| +// |
| +// The app has no records to name its followers, so beside the member |
| +// door's guard it asks every box report (routeAbsence): every report read, |
| +// every fresh box naming the apps it runs routes of (managed or not, so a |
| +// hand-made named-unit route counts), no box dark within routeDarkHorizon, |
| +// and no route of the app on any box. It refuses an account the console |
| +// does not have, an app with a live or trashed row, a trash marker, any |
| +// instance or sidecar record, and a console running host claims, whose |
| +// app mutation needs an app id an app with no row does not have. It asks |
| +// the no-row precondition again last, under the app lock and the lock a |
| +// claim's row insert takes, deletes with CAS, and writes a platform audit |
| +// row. |
| +func (s *Server) handleAPISystemRetireChannel(w http.ResponseWriter, r *http.Request) { |
| + addr, _, ok := s.apiSystemRoller(w, r) |
| + if !ok { |
| + return |
| + } |
| + if !s.systemBucket(w) { |
| + return |
| + } |
| + p, _ := principalFrom(r.Context()) |
| + if !s.allowWrite(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, textTooManyRequests) |
| + return |
| + } |
| + var req struct { |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Channel string `json:"channel"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + if !release.ValidAccount(req.Account) || !release.ValidApp(req.App) { |
| + jsonError(w, http.StatusBadRequest, textRetireBadTarget) |
| + return |
| + } |
| + if !validRetireChannel(req.Channel) { |
| + jsonError(w, http.StatusBadRequest, fmt.Sprintf(textRetireBadChannel, req.Channel)) |
| + return |
| + } |
| + if len(s.cfg.Key) == 0 { |
| + jsonError(w, http.StatusServiceUnavailable, textNoReleaseKey) |
| + return |
| + } |
| + if _, gated := s.cfg.Releases.(release.AppMutationRunner); gated { |
| + jsonError(w, http.StatusConflict, textRetireHostClaims) |
| + return |
| + } |
| + acct, app, channel := req.Account, req.App, req.Channel |
| + name := strings.TrimPrefix(channel, release.RungCanary+"/") |
| + ctx := r.Context() |
| + if ref := s.orphanRefusal(ctx, acct, app, name); ref != nil { |
| + if ref.err != nil { |
| + log.Printf("console: api system retire %s/%s %s: %v", acct, app, channel, ref.err) |
| + } |
| + jsonError(w, ref.status, ref.msg) |
| + return |
| + } |
| + chk, err := s.checkCanaryRetire(ctx, acct, app, channel) |
| + if writeRetireRefusal(w, err, acct, app, channel) { |
| + return |
| + } |
| + if err := s.remoteFacts(ctx, acct, app).routeAbsence(); writeRouteAbsence(w, err, acct, app) { |
| + log.Printf("console: api system retire %s/%s %s: %v", acct, app, channel, err) |
| + return |
| + } |
| + guard := func(ctx context.Context) (func(), error) { |
| + unlock := s.lockOrphanName(acct, app) |
| + if ref := s.orphanRefusal(ctx, acct, app, name); ref != nil { |
| + unlock() |
| + return nil, ref |
| + } |
| + return unlock, nil |
| + } |
| + err = s.deleteRetiredCanary(ctx, chk, s.orphanRetireMutation(acct, app), guard) |
| + var ref *orphanRefusedError |
| + switch { |
| + case errors.As(err, &ref): |
| + if ref.err != nil { |
| + log.Printf("console: api system retire %s/%s %s: %v", acct, app, channel, ref.err) |
| + } |
| + jsonError(w, ref.status, ref.msg) |
| + return |
| + case errors.Is(err, errRetireUnsettled): |
| + writeRetireRefusal(w, err, acct, app, channel) |
| + return |
| + case err != nil: |
| + log.Printf("console: api system retire %s/%s %s: %v", acct, app, channel, err) |
| + jsonError(w, http.StatusBadGateway, fmt.Sprintf(textRetireFailed, channel)) |
| + return |
| + } |
| + s.auditSystem(addr, "canary-retire-orphan", fmt.Sprintf(textRetireOrphanDone, channel, acct, app)) |
| + writeJSON(w, http.StatusOK, map[string]string{"result": "retired", "channel": channel}) |
| +} |
diff --git a/internal/console/canary_retire_orphan_test.go b/internal/console/canary_retire_orphan_test.go| new file mode 100644 |
| index 000000000..4f983a375 |
| --- /dev/null |
| +++ b/internal/console/canary_retire_orphan_test.go |
| @@ -0,0 +1,263 @@ |
| +package console |
| + |
| +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/status" |
| +) |
| + |
| +// The operator's channel retire (#1634): `carlos channels retire` for a |
| +// canary pointer of an app the console has no row for. |
| + |
| +func orphanRetireURL(tb *twoBoxes) string { |
| + return tb.fx.ts.URL + "/api/cli/system/channels/retire" |
| +} |
| + |
| +func orphanBody(tb *twoBoxes, app, channel string) string { |
| + b, _ := json.Marshal(map[string]string{"account": tb.sqid, "app": app, "channel": channel}) |
| + return string(b) |
| +} |
| + |
| +// writeRawBox writes a box report as given, for a box this test cannot |
| +// build through CollectBox: a binary from before route channels, or one |
| +// that stopped reporting. |
| +func writeRawBox(t *testing.T, tb *twoBoxes, b status.Box) { |
| + t.Helper() |
| + if err := status.WriteBox(context.Background(), tb.fx.rel, b); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.fx.srv.boxReports.expire() |
| +} |
| + |
| +// The operator door deletes an orphan's canary pointer only once no box |
| +// report names any route of the app, and then only that pointer: a |
| +// named-unit hand route on box B, which has no rollout entry and so was |
| +// invisible to the member door's box check, holds the retire. Then the |
| +// pointer goes, the app's other channel and its releases stay, and the |
| +// platform audit names it. |
| +func TestAPISystemRetireChannel(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "canary/rc") |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "stable") |
| + |
| + if err := tb.regB.Upsert(registry.Route{Host: "unit.old.example.com", Kind: "instance", App: "old", Account: tb.sqid, |
| + Channel: "canary/rc", Version: "v1", Unit: "old-worker", Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, orphanBody(tb, "old", "canary/rc")) |
| + if status != http.StatusConflict || !strings.Contains(out, "still runs a route of "+tb.sqid+"/old (channel canary/rc)") || !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatalf("orphan retire with a named-unit route of the app on box B = %d %s", status, out) |
| + } |
| + |
| + if err := tb.regB.Delete("unit.old.example.com"); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + status, _, out = rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, orphanBody(tb, "old", "canary/rc")) |
| + if status != http.StatusOK { |
| + t.Fatalf("orphan retire = %d %s", status, out) |
| + } |
| + if pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatal("the orphan's canary pointer is still there") |
| + } |
| + if !pointerExists(t, tb, "old", "stable") { |
| + t.Fatal("the orphan retire took another channel with it") |
| + } |
| + if _, err := release.GetManifest(context.Background(), tb.fx.rel, tb.sqid, "old", "v1"); err != nil { |
| + t.Fatalf("orphan retire touched a shipped release: %v", err) |
| + } |
| + found := false |
| + for _, e := range roleAudits(t, tb.fx) { |
| + found = found || (e.Action == "canary-retire-orphan" && strings.Contains(e.Detail, "canary/rc of "+tb.sqid+"/old")) |
| + } |
| + if !found { |
| + t.Fatal("no platform audit row for the orphan retire") |
| + } |
| +} |
| + |
| +// A route of the app on ANY channel holds the retire, not only one on the |
| +// channel being retired: an app still running somewhere is not an orphan. |
| +func TestAPISystemRetireChannelRefusesARouteOnAnotherChannel(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "canary/rc") |
| + if err := tb.regB.Upsert(registry.Route{Host: "backed.old.example.com", Kind: "instance", App: "old", Account: tb.sqid, |
| + Backing: registry.BackingUnit, Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fx.srv.boxReports.expire() |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, orphanBody(tb, "old", "canary/rc")) |
| + if status != http.StatusConflict || !strings.Contains(out, "(channel stable)") || !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatalf("orphan retire with a stable route of the app = %d %s", status, out) |
| + } |
| +} |
| + |
| +// Box reports that cannot say hold the retire: a fresh box on a binary |
| +// from before route channels, and a box that went dark within the |
| +// horizon. A box dark for longer than the horizon is taken as gone. |
| +func TestAPISystemRetireChannelNeedsEveryBoxToSay(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "canary/rc") |
| + post := func() (int, string) { |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, orphanBody(tb, "old", "canary/rc")) |
| + return status, out |
| + } |
| + |
| + old := status.Box{GeneratedAt: time.Now().UTC(), Label: status.Label("box-old"), Metrics: &status.BoxMetrics{Release: "v0.44.2"}} |
| + writeRawBox(t, tb, old) |
| + if st, out := post(); st != http.StatusConflict || !strings.Contains(out, "box "+old.Label+" runs a CARLOS version too old to report") { |
| + t.Fatalf("orphan retire with a box on an older binary = %d %s", st, out) |
| + } |
| + |
| + old.Metrics.RouteChannelsReported = true |
| + writeRawBox(t, tb, old) |
| + dark := status.Box{GeneratedAt: time.Now().Add(-48 * time.Hour).UTC(), Label: status.Label("box-dark"), |
| + Metrics: &status.BoxMetrics{RouteChannelsReported: true}} |
| + writeRawBox(t, tb, dark) |
| + if st, out := post(); st != http.StatusConflict || !strings.Contains(out, "box "+dark.Label+" has not reported since") { |
| + t.Fatalf("orphan retire with a box dark for two days = %d %s", st, out) |
| + } |
| + if !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatal("a refused retire deleted the pointer") |
| + } |
| + |
| + dark.GeneratedAt = time.Now().Add(-routeDarkHorizon - time.Hour).UTC() |
| + writeRawBox(t, tb, dark) |
| + if st, out := post(); st != http.StatusOK { |
| + t.Fatalf("orphan retire with the dark box past the horizon = %d %s", st, out) |
| + } |
| +} |
| + |
| +// Every refusal of the operator door, each leaving the pointer in place: a |
| +// channel outside canary/*, an app the console has (the member door's), a |
| +// console row in the trash with no bucket marker, a bucket trash marker, |
| +// an app with instance records, an account the console does not have, and |
| +// a member who is not a platform operator. |
| +func TestAPISystemRetireChannelRefusals(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + ctx := context.Background() |
| + shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc") |
| + for _, app := range []string{"old", "rowbinned", "binned", "recorded"} { |
| + shipAndPromote(t, tb.fx, tb.sqid, app, "v1", "canary/rc") |
| + } |
| + if _, err := tb.fx.st.CreateAppIn(5151, "rowbinned", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := tb.fx.st.TrashAppRow(5151, "rowbinned", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.TrashApp(ctx, tb.fx.rel, tb.sqid, "binned", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.CreateRecord(ctx, tb.fx.rel, provision.Record{Schema: 1, Host: "x.recorded.example.com", Slug: "x", |
| + App: "recorded", Account: tb.sqid, Pool: "shop", Region: "uk", Channel: "stable", CreatedAt: time.Now()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + const stranger = "zqx" |
| + shipAndPromote(t, tb.fx, stranger, "old", "v1", "canary/rc") |
| + post := func(token, acct, app, channel string) (int, string) { |
| + body, _ := json.Marshal(map[string]string{"account": acct, "app": app, "channel": channel}) |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), token, string(body)) |
| + return status, out |
| + } |
| + cases := []struct { |
| + acct, app, channel string |
| + status int |
| + says string |
| + }{ |
| + {tb.sqid, "old", "stable", http.StatusBadRequest, "is not a canary channel"}, |
| + {tb.sqid, "shop", "canary/rc", http.StatusConflict, "use carlos canary retire --account " + tb.sqid + " --app shop --name rc"}, |
| + {tb.sqid, "rowbinned", "canary/rc", http.StatusConflict, "is in the trash"}, |
| + {tb.sqid, "binned", "canary/rc", http.StatusConflict, "is in the trash"}, |
| + {tb.sqid, "recorded", "canary/rc", http.StatusConflict, "still has instance records"}, |
| + {stranger, "old", "canary/rc", http.StatusConflict, "account zqx is not on this console"}, |
| + } |
| + for _, c := range cases { |
| + status, out := post(tb.token, c.acct, c.app, c.channel) |
| + if status != c.status || !strings.Contains(out, c.says) { |
| + t.Fatalf("orphan retire of %s/%s %s = %d %s, want %d saying %q", c.acct, c.app, c.channel, status, out, c.status, c.says) |
| + } |
| + } |
| + for _, app := range []string{"shop", "rowbinned", "binned", "recorded"} { |
| + if !pointerExists(t, tb, app, "canary/rc") { |
| + t.Fatalf("a refused retire deleted %s's canary/rc", app) |
| + } |
| + } |
| + if _, _, err := tb.fx.rel.Get(ctx, release.ChannelKey(stranger, "old", "canary/rc")); err != nil { |
| + t.Fatalf("a refused retire deleted the bucket-only account's pointer: %v", err) |
| + } |
| + member := cliToken(t, tb.fx, "alice@keymail.dev", "code-orphan-member") |
| + if status, out := post(member, tb.sqid, "old", "canary/rc"); status != http.StatusNotFound { |
| + t.Fatalf("orphan retire by a non-operator = %d %s, want 404", status, out) |
| + } |
| + if !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatal("a non-operator retired the orphan's canary") |
| + } |
| +} |
| + |
| +// A console row created for the app after the first no-row check (an |
| +// owner adopting the name) is seen by the last one, under the lock, and |
| +// the refusal names the real cause. |
| +func TestAPISystemRetireChannelRefusesAnAppCreatedDuringTheCheck(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + settledApp(t, tb) |
| + shipAndPromote(t, tb.fx, tb.sqid, "old", "v1", "canary/rc") |
| + tb.fx.srv.retireBeforeDeleteHook = func() { |
| + if _, err := tb.fx.st.CreateAppIn(5151, "old", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + status, _, out := rawReq(t, http.MethodPost, orphanRetireURL(tb), tb.token, orphanBody(tb, "old", "canary/rc")) |
| + if status != http.StatusConflict || !strings.Contains(out, "is an app on this console") || !pointerExists(t, tb, "old", "canary/rc") { |
| + t.Fatalf("orphan retire with an app created during the check = %d %s", status, out) |
| + } |
| +} |
| + |
| +// The claim's row insert waits for the lock the retire holds through its |
| +// delete, so an adoption cannot land between the last check and the |
| +// delete. |
| +func TestClaimRowInsertWaitsForTheOrphanRetire(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + unlock := tb.fx.srv.lockOrphanName(tb.sqid, "old") |
| + acct, err := tb.fx.st.AccountBySqid(tb.sqid) |
| + if err != nil || acct == nil { |
| + t.Fatalf("account: %v", err) |
| + } |
| + inserted := make(chan error, 1) |
| + go func() { |
| + _, err := tb.fx.srv.insertClaimAppRow(context.Background(), acct, "old", func(st *Store) (bool, error) { |
| + return st.CreateAppIn(acct.ID, "old", "paul@keymail.dev", time.Now()) |
| + }, nil) |
| + inserted <- err |
| + }() |
| + select { |
| + case err := <-inserted: |
| + t.Fatalf("the insert did not wait for the retire's lock: %v", err) |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + if live, _ := tb.fx.st.HasAppIn(acct.ID, "old"); live { |
| + t.Fatal("a row was inserted while the retire held the lock") |
| + } |
| + unlock() |
| + if err := <-inserted; err != nil { |
| + t.Fatal(err) |
| + } |
| + if live, _ := tb.fx.st.HasAppIn(acct.ID, "old"); !live { |
| + t.Fatal("no row after the lock was released") |
| + } |
| +} |
diff --git a/internal/console/claim_app_enroll.go b/internal/console/claim_app_enroll.go| index e365ab6c1..fa99e04dd 100644 |
| --- a/internal/console/claim_app_enroll.go |
| +++ b/internal/console/claim_app_enroll.go |
| @@ -79,6 +79,11 @@ func (s *Server) insertClaimAppRow(ctx context.Context, acct *Account, app strin |
| return false, err |
| } |
| } |
| + // The operator's channel retire of an app with no row holds this |
| + // from its last no-row check through its delete (#1634), so an |
| + // owner adopting the name lands wholly before or after it. Under |
| + // host claims that door refuses, so only this branch takes it. |
| + defer s.lockOrphanName(acct.Sqid, app)() |
| return insert(s.store) |
| } |
| w, err := s.claimControl() |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 5f8717bd2..3678d580f 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1041,6 +1041,15 @@ var claimFixtures = map[string]claimFixture{ |
| status: http.StatusConflict, |
| msg: copyLinkedHostClaim, |
| }}, |
| + // The operator's channel retire of an app with no row (#1634): its |
| + // bucket mutation needs an app id such an app does not have under host |
| + // claims, so it refuses before any store read. |
| + "route POST /api/cli/system/channels/retire": {refused: &claimRefusalFixture{ |
| + apps: claimRefs("bab/titogo"), |
| + do: claimRefusedAPI(http.MethodPost, "/api/cli/system/channels/retire", `{"account":"bab","app":"orphan","channel":"canary/old"}`), |
| + status: http.StatusConflict, |
| + msg: textRetireHostClaims, |
| + }}, |
| "route POST /api/cli/system/shares/stop": {refused: &claimRefusalFixture{ |
| apps: claimRefs("bab/titogo"), |
| do: claimRefusedAPI(http.MethodPost, "/api/cli/system/shares/stop", `{"host":"titogo.bab.apps.example.com"}`), |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index ff810e20b..fc8e85f1c 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -137,6 +137,8 @@ var claimUnsupported = map[string]string{ |
| "which no claim operation covers; all four doors refuse after apiAccountApp and before they read the store record", |
| claimRenameUnsupportedMsg: "rename rewrites the app's identity (SQL rows, prefixes, admission key); " + |
| "no operation gates the old and new names together, so every rename is refused", |
| + textRetireHostClaims: "the operator's channel retire acts on an app with no row, whose app mutation needs an app id only a row " + |
| + "or an admission gives (#1634); it refuses after its operator gate and before it reads anything", |
| claimTransferUnsupportedMsg: "account transfer rewrites the app's identity under another account; " + |
| "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 " + |
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go| index 735991dd4..519f34395 100644 |
| --- a/internal/console/remoteinstances.go |
| +++ b/internal/console/remoteinstances.go |
| @@ -25,6 +25,7 @@ package console |
| // is not joined at all (the R18 rule boxJoin.rollout applies). |
| import ( |
| + "cmp" |
| "context" |
| "errors" |
| "fmt" |
| @@ -255,8 +256,37 @@ type fleetReports struct { |
| // complete is whether every box's report was read. Only a complete read |
| // can say "no box serves this host". |
| complete bool |
| + // routes is every fresh box's word about which apps it runs routes of, |
| + // managed or not (status BoxMetrics.RouteChannels, #1634); silent is |
| + // each fresh box whose report cannot say (no Metrics, or a binary from |
| + // before RouteChannelsReported); dark is each box whose last report is |
| + // stale but younger than routeDarkHorizon, which may come back still |
| + // running whatever it ran. Only routeAbsence reads them. |
| + routes []boxRoute |
| + silent []string |
| + dark []darkBox |
| } |
| +// boxRoute is one fresh box's report of one account/app/channel it runs a |
| +// route of. |
| +type boxRoute struct { |
| + box string |
| + rc status.RouteChannel |
| +} |
| + |
| +// darkBox is a box whose report went stale recently. |
| +type darkBox struct { |
| + box string |
| + at time.Time |
| +} |
| + |
| +// routeDarkHorizon is how long after its last report a stale box still |
| +// counts as one that may come back running its routes (#1634). Box reports |
| +// are never deleted, so a box terminated long ago leaves a stale report |
| +// for ever; past this horizon it is taken as gone. A week covers a box |
| +// stopped for maintenance, a weekend outage and a slow replacement. |
| +const routeDarkHorizon = 7 * 24 * time.Hour |
| + |
| // foldFleetReports folds box reports into per-host reports. Stale boxes are |
| // left out under the fleet's one staleness rule (status.BoxStale), as every |
| // other box join does. Only remoteFacts calls it. |
| @@ -264,7 +294,19 @@ func foldFleetReports(boxes []status.Box, complete bool, now time.Time) fleetRep |
| f := fleetReports{byHost: map[string][]hostReport{}, complete: complete} |
| for _, b := range boxes { |
| m := b.Metrics |
| - if m == nil || status.BoxStale(b, now, status.SnapshotPeriod) { |
| + stale := status.BoxStale(b, now, status.SnapshotPeriod) |
| + switch { |
| + case stale && now.Sub(b.GeneratedAt) < routeDarkHorizon: |
| + f.dark = append(f.dark, darkBox{box: b.Label, at: b.GeneratedAt}) |
| + case stale: |
| + case m == nil || !m.RouteChannelsReported: |
| + f.silent = append(f.silent, b.Label) |
| + default: |
| + for _, rc := range m.RouteChannels { |
| + f.routes = append(f.routes, boxRoute{box: b.Label, rc: rc}) |
| + } |
| + } |
| + if m == nil || stale { |
| continue |
| } |
| reps := map[string]*hostReport{} |
| @@ -359,6 +401,59 @@ func (f appFacts) host(rec provision.Record) *hostReport { |
| // complete is whether every box's report was read. |
| func (f appFacts) complete() bool { return f.reports.complete } |
| +// routeAbsenceError is routeAbsence's answer when the box reports cannot |
| +// show that no box runs a route of the app. Exactly one of its fields |
| +// says why; Box names the box when there is one. |
| +type routeAbsenceError struct { |
| + Incomplete bool // not every box report could be read |
| + Silent bool // Box's fresh report cannot say which apps it runs |
| + DarkSince time.Time // Box stopped reporting at DarkSince, within the horizon |
| + Channel string // Box runs a route of the app on Channel |
| + Box string |
| +} |
| + |
| +func (e *routeAbsenceError) Error() string { |
| + switch { |
| + case e.Incomplete: |
| + return "not every box report could be read" |
| + case e.Silent: |
| + return "box " + e.Box + " does not report its routes' apps" |
| + case !e.DarkSince.IsZero(): |
| + return "box " + e.Box + " has not reported since " + e.DarkSince.UTC().Format(time.RFC3339) |
| + } |
| + return "box " + e.Box + " runs a route of the app on " + e.Channel |
| +} |
| + |
| +// routeAbsence reports whether the box reports show that no box runs any |
| +// route of acct/app, on any channel, managed or not (#1634): nil only when |
| +// every report was read, every fresh box says which apps it runs, no box |
| +// went dark within routeDarkHorizon, and none names the app. Anything |
| +// else is a *routeAbsenceError; boxes are taken in label order, so the |
| +// answer is stable. |
| +func (f appFacts) routeAbsence() error { |
| + r := f.reports |
| + if !r.complete { |
| + return &routeAbsenceError{Incomplete: true} |
| + } |
| + silent := slices.Sorted(slices.Values(r.silent)) |
| + if len(silent) > 0 { |
| + return &routeAbsenceError{Silent: true, Box: silent[0]} |
| + } |
| + dark := slices.SortedFunc(slices.Values(r.dark), func(a, b darkBox) int { return cmp.Compare(a.box, b.box) }) |
| + if len(dark) > 0 { |
| + return &routeAbsenceError{DarkSince: dark[0].at, Box: dark[0].box} |
| + } |
| + routes := slices.SortedFunc(slices.Values(r.routes), func(a, b boxRoute) int { |
| + return cmp.Or(cmp.Compare(a.box, b.box), cmp.Compare(a.rc.Channel, b.rc.Channel)) |
| + }) |
| + for _, br := range routes { |
| + if br.rc.Account == f.acct && br.rc.App == f.app { |
| + return &routeAbsenceError{Channel: br.rc.Channel, Box: br.box} |
| + } |
| + } |
| + return nil |
| +} |
| + |
| // seen reports whether any fresh box report names host at all, whoever it |
| // says the host belongs to: a host some box serves is not "not minted |
| // anywhere", even when nothing about it can be joined. |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index fdc4f36a8..e0616af22 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -1301,6 +1301,9 @@ var routeDecls = []routeDecl{ |
| {Pattern: "GET /api/cli/system/hosts-used/status", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIHostsUsedStatus}, |
| {Pattern: "GET /api/cli/system/pointer-digests", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemPointerDigests}, |
| {Pattern: "POST /api/cli/system/pointer-digests", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemPointerDigests}, |
| + // `carlos channels retire` (#1634): a canary pointer of an app with no |
| + // row on this console. apiSystemRoller, like pointer digests. |
| + {Pattern: "POST /api/cli/system/channels/retire", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemRetireChannel}, |
| // The anonymous demos (apidemo.go): registered on a console with demos |
| // on or one in demo box mode (gateDemo). |
diff --git a/internal/console/server.go b/internal/console/server.go| index dae16932b..9c69f1c3f 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1762,6 +1762,10 @@ type Server struct { |
| // the follower check and the final record comparison, holding the app |
| // lock. Tests only. |
| retireBeforeDeleteHook func() |
| + // orphanNames holds, per "<sqid>/<app>", the lock the operator's |
| + // channel retire holds from its last no-row check through the delete, |
| + // and a claim's app row insert takes (lockOrphanName, #1634). |
| + orphanNames sync.Map |
| // gsBeforeCompleteHook, when set, runs on the account home between the |
| // Getting started marks read and the completion write. Tests only. |
| gsBeforeCompleteHook func() |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index dbfdadb24..23f44da5d 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -401,6 +401,9 @@ var closedDoors = []string{ |
| // root-signed, the same cut as the update doors. |
| "GET /api/cli/system/pointer-digests", |
| "POST /api/cli/system/pointer-digests", |
| + // The channel retire of an app with no row (#1634): an operator's |
| + // deployment-wide act, the same cut as pointer digests. |
| + "POST /api/cli/system/channels/retire", |
| // 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", |
| @@ -1946,8 +1949,8 @@ func walkClosedDoors(t *testing.T, fx *consoleFixture, tok string) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 124 { |
| - t.Errorf("walked %d closed doors, want all %d (and 124 today: three domain purchase doors, two domain transfer doors, the account's domains list, four saved-contact doors, the domain point door, the transfer resolve door, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, 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, seven fleets, the instance label door, the fleet secrets key door, the two person link doors (list and unlink), the share mint, the operator's share stop, the six home link doors, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, eleven system doors, three deployment-wide antivirus, the PDF status door, the media status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, the canary retire (#1634), two release authorize doors, four store-entitlement doors, the store versioning setter, two account plan doors, three platform grant doors, two billing problem doors, the billing revenue and payments doors, the billing house door, three account subdomain doors, the subdomain inventory, the two certificate import doors (#1429), the two platform update hold doors (#1442), and the claimed source door)", |
| + if seen != len(closedDoors) || seen != 125 { |
| + t.Errorf("walked %d closed doors, want all %d (and 125 today: three domain purchase doors, two domain transfer doors, the account's domains list, four saved-contact doors, the domain point door, the transfer resolve door, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, 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, seven fleets, the instance label door, the fleet secrets key door, the two person link doors (list and unlink), the share mint, the operator's share stop, the six home link doors, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, eleven system doors, three deployment-wide antivirus, the PDF status door, the media status door, three platform geoip doors, two pointer digest doors, the operator channel retire (#1634), the hostname history status, the channel resign, the canary retire (#1634), two release authorize doors, four store-entitlement doors, the store versioning setter, two account plan doors, three platform grant doors, two billing problem doors, the billing revenue and payments doors, the billing house door, three account subdomain doors, the subdomain inventory, the two certificate import doors (#1429), the two platform update hold doors (#1442), and the claimed source door)", |
| seen, len(closedDoors)) |
| } |
| } |
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt| index a20f26bb5..0bfeedbc9 100644 |
| --- a/internal/console/testdata/claim-authority-sites.txt |
| +++ b/internal/console/testdata/claim-authority-sites.txt |
| @@ -164,3 +164,4 @@ hacapacity_observe.go|dirPage|os.Open(filepath.Join(s.directory, filepath.FromSl |
| demo_claim_seed.go|publishDemoClaimSeed|os.Open(path) |
| managedseed.go|openManagedSeed|o.Open(ctx, key) |
| oplegal.go|legalFoldLogo|files[0].Open() |
| +canary_retire.go|orphanRetireMutation|release.WithAppMutation(ctx, s.cfg.Releases, acct, app, "canary-retire-orphan", fn) |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 8b36b19e3..5540ce5b3 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -403,6 +403,7 @@ route POST /api/cli/system/hold/release |
| route POST /api/cli/system/layout |
| route POST /api/cli/system/legacy-routes |
| route POST /api/cli/system/lifetimes/cutover |
| +route POST /api/cli/system/channels/retire |
| route POST /api/cli/system/pointer-digests |
| route POST /api/cli/system/rollback |
| route POST /api/cli/system/seeds-floor |
diff --git a/internal/provision/canary_retire_orphan_1634_census_test.go b/internal/provision/canary_retire_orphan_1634_census_test.go| new file mode 100644 |
| index 000000000..06e4ca324 |
| --- /dev/null |
| +++ b/internal/provision/canary_retire_orphan_1634_census_test.go |
| @@ -0,0 +1,28 @@ |
| +package provision |
| + |
| +// canaryRetireOrphan1634WriteCensusInventory is the operator channel |
| +// retire's review of the record-write census (#1634, branch 1). The route |
| +// table gains POST /api/cli/system/channels/retire, a route pattern, never |
| +// a record key. The door deletes one canary pointer, conditional on the |
| +// etag its check read, and writes no record; the box report's new route |
| +// channels name no record key. Kinds and class unchanged, only the digest |
| +// moves. |
| +func canaryRetireOrphan1634WriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), privateStoreScan1653WriteCensusInventory()...) |
| + reviewed := []censusEntry{ |
| + {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "1e780cfb91e3284ba4e97af4fae1823cce31519ac4753a9b621c2d0bc6cce172"}, |
| + } |
| + for _, r := range reviewed { |
| + replaced := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], replaced = r, true |
| + break |
| + } |
| + } |
| + if !replaced { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 2c2b4e86e..d9694934a 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := privateStoreScan1653WriteCensusInventory() |
| + inventory := canaryRetireOrphan1634WriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/release/adopt.go b/internal/release/adopt.go| index 3fb3eda9c..c0631a52f 100644 |
| --- a/internal/release/adopt.go |
| +++ b/internal/release/adopt.go |
| @@ -1404,6 +1404,10 @@ func CapabilityRoute(rt registry.Route) bool { |
| } |
| // routeChannel is the channel a route follows; "" means stable. |
| +// RouteChannel is the channel a route follows, as the adopt pass reads it: |
| +// its own, else stable. The status report names it per route (#1634). |
| +func RouteChannel(rt registry.Route) string { return routeChannel(rt) } |
| + |
| func routeChannel(rt registry.Route) string { |
| if rt.Channel == "" { |
| return "stable" |
diff --git a/internal/status/contract_test.go b/internal/status/contract_test.go| index 60631882d..3069529a8 100644 |
| --- a/internal/status/contract_test.go |
| +++ b/internal/status/contract_test.go |
| @@ -83,7 +83,7 @@ var allowedBoxKeys = map[string][]string{ |
| "routes": {"static", "resident", "hibernating", "awake", "asleep"}, |
| "replication": {"healthy", "lag_seconds"}, |
| // capabilities names supported protocols only, in the bucket-private metrics. |
| - "metrics": {"capabilities", "mem_total_bytes", "mem_avail_bytes", "load1", "disk_free_bytes", "release", "tunnel", "route_versions", "upstreams", "layout", "config_refusals", "config_refusals_total", "release_refusals", "proof_waits", "config_guard", "build_states", "build_states_err", "update_settings", "updates", "egress", "size_committed_mib", "offline_move", "demo_disk"}, |
| + "metrics": {"capabilities", "mem_total_bytes", "mem_avail_bytes", "load1", "disk_free_bytes", "release", "tunnel", "route_versions", "upstreams", "layout", "config_refusals", "config_refusals_total", "release_refusals", "proof_waits", "config_guard", "build_states", "build_states_err", "update_settings", "updates", "egress", "size_committed_mib", "offline_move", "demo_disk", "route_channels", "route_channels_reported"}, |
| "metrics.route_versions": {wildcardAnyKey}, |
| "metrics.upstreams": {wildcardAnyKey}, |
| "metrics.upstreams.*[]": {"addr", "up", "since", "fails", "last_error"}, |
| @@ -97,6 +97,10 @@ var allowedBoxKeys = map[string][]string{ |
| // release_refusals (D1) names the host and build the box rolled back, in |
| // the private block only, pinned to the field level for the same reason. |
| "metrics.release_refusals[]": {"host", "version", "reason", "refused_at", "kind", "recovery_error"}, |
| + // route_channels (#1634) names each route's account, app and channel, |
| + // once each and with no host, in the private block only, pinned to the |
| + // field level. |
| + "metrics.route_channels[]": {"account", "app", "channel"}, |
| // proof_waits (D3) names the host and build the box is holding for a dev |
| // proof, in the private block only, pinned to the field level too. |
| "metrics.proof_waits[]": {"host", "version", "sha256", "prover", "reason", "since"}, |
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go| index 4321238fa..53a627421 100644 |
| --- a/internal/status/snapshot.go |
| +++ b/internal/status/snapshot.go |
| @@ -24,12 +24,14 @@ |
| package status |
| import ( |
| + "cmp" |
| "context" |
| "crypto/sha256" |
| "encoding/binary" |
| "encoding/json" |
| "errors" |
| "os" |
| + "slices" |
| "time" |
| "github.com/carlosframework/platform/internal/consolefleet" |
| @@ -692,6 +694,31 @@ type SystemState struct { |
| At time.Time `json:"at"` |
| } |
| +// sortedRouteChannels is the set as BoxMetrics carries it: once each, by |
| +// account, app, channel; nil for an empty set. |
| +func sortedRouteChannels(set map[RouteChannel]bool) []RouteChannel { |
| + if len(set) == 0 { |
| + return nil |
| + } |
| + out := make([]RouteChannel, 0, len(set)) |
| + for rc := range set { |
| + out = append(out, rc) |
| + } |
| + slices.SortFunc(out, func(a, b RouteChannel) int { |
| + return cmp.Or(cmp.Compare(a.Account, b.Account), cmp.Compare(a.App, b.App), cmp.Compare(a.Channel, b.Channel)) |
| + }) |
| + return out |
| +} |
| + |
| +// RouteChannel is one entry of BoxMetrics.RouteChannels: the |
| +// account its app's bucket keys live under (release.RouteAccount), the app, |
| +// and the channel the adopt pass follows for it (release.RouteChannel). |
| +type RouteChannel struct { |
| + Account string `json:"account"` |
| + App string `json:"app"` |
| + Channel string `json:"channel"` |
| +} |
| + |
| // BoxMetrics is the raw, PRIVATE block: real numbers, never banded. It lives |
| // in status/boxes/<label>.json — which only fleet-status machinery and |
| // operators read — and is deliberately NOT copied into FleetBox, so the |
| @@ -792,6 +819,19 @@ type BoxMetrics struct { |
| // has seen the key, so it is the proxy. Absent (false) on every box |
| // with no key, and on every box from before the field. |
| MailerArmed bool `json:"mailer_armed,omitempty"` |
| + // RouteChannels is the account, app and channel of every non-platform |
| + // route this box carries, managed or not, once each and sorted (#1634): |
| + // a named-unit or unit-backed route has no rollout entry, yet root's |
| + // adopt pass follows its channel all the same. Built from the routes |
| + // this report already lists. It names no host: the console asks only |
| + // whether any route of an app is still here, and on which channel. |
| + // Omitted when the box has no such route. |
| + RouteChannels []RouteChannel `json:"route_channels,omitempty"` |
| + // RouteChannelsReported is true from the first binary that builds |
| + // RouteChannels, so an absent map on a box that says so means "no |
| + // routes", and on one that does not means "this binary cannot say". The |
| + // console's channel retire refuses while any fresh box cannot say. |
| + RouteChannelsReported bool `json:"route_channels_reported,omitempty"` |
| // RouteVersions is host -> registry.Route.Version for every non-platform |
| // route this box carries with a Version the adopt pass has stamped |
| // (issue #78's staged_version chip) — a hostname-keyed map, which is |
| @@ -1220,6 +1260,10 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| // routeDBBytes is Metrics.RouteDBBytes, built in the same loop and nil |
| // until the first entry, like routeVersions. |
| var routeDBBytes map[string]int64 |
| + // routeChannels is Metrics.RouteChannels (#1634): every non-platform |
| + // route's account, app and channel, from the same routes, as a set. |
| + // Nil until the first entry, like routeVersions. |
| + var routeChannels map[RouteChannel]bool |
| for _, r := range routes { |
| // Platform-minted routes (internal/domains) are additional NAMES for |
| @@ -1233,6 +1277,12 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| if r.Platform { |
| continue |
| } |
| + if r.App != "" { |
| + if routeChannels == nil { |
| + routeChannels = map[RouteChannel]bool{} |
| + } |
| + routeChannels[RouteChannel{Account: release.RouteAccount(r), App: r.App, Channel: release.RouteChannel(r)}] = true |
| + } |
| if r.Version != "" { |
| if routeVersions == nil { |
| routeVersions = map[string]string{} |
| @@ -1370,7 +1420,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| if p.MemTotalBytes != nil || p.MemAvailBytes != nil || p.Load1 != nil || |
| p.DiskFreeBytes != nil || p.DiskFullETAHours != nil || p.Release != "" || p.PrevRelease != "" || p.ApplyFinished || p.Tunnel != "" || |
| p.InstanceID != "" || p.Platform != "" || p.SystemChannel != "" || p.System != nil || |
| - len(routeVersions) > 0 || len(routeServing) > 0 || len(aliasReadings) > 0 || p.AliasesRead || len(p.Upstreams) > 0 || len(p.ReplicaCopies) > 0 || |
| + len(routeVersions) > 0 || len(routeServing) > 0 || len(routeChannels) > 0 || len(aliasReadings) > 0 || p.AliasesRead || len(p.Upstreams) > 0 || len(p.ReplicaCopies) > 0 || |
| len(routeDBBytes) > 0 || p.Layout != nil || len(p.ConfigRefusals) > 0 || len(p.ReleaseRefusals) > 0 || len(p.ProofWaits) > 0 || p.Rollout != nil || p.ConfigGuard != "" || |
| p.Alerts != nil || p.GeoIP != nil || p.HeldStreams != nil || len(p.BuildStates) > 0 || p.BuildStatesErr != "" || |
| p.DemoClaimSeedReady || p.DemoMovedReady || p.UpdateSettings != 0 || len(p.Updates) > 0 || len(p.Egress) > 0 || p.SizeCommittedMiB != nil || |
| @@ -1406,8 +1456,12 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| Alerts: p.Alerts, |
| RouteVersions: routeVersions, |
| RouteServing: routeServing, |
| - Aliases: aliasReadings, |
| - AliasesRead: p.AliasesRead, |
| + // Every box that attaches Metrics says whether it reports route |
| + // channels: this binary always does (#1634). |
| + RouteChannels: sortedRouteChannels(routeChannels), |
| + RouteChannelsReported: true, |
| + Aliases: aliasReadings, |
| + AliasesRead: p.AliasesRead, |
| // Carried through as the prober handed it over: proberSet.State |
| // already returns a fresh copy per call, so there is nothing here |
| // for a later probe tick to mutate under the marshaller. An empty |
diff --git a/internal/status/snapshot_test.go b/internal/status/snapshot_test.go| index 500b33c42..9f83aa2c1 100644 |
| --- a/internal/status/snapshot_test.go |
| +++ b/internal/status/snapshot_test.go |
| @@ -381,7 +381,7 @@ func TestCollectBoxCarriesAliasesRead(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if !strings.Contains(string(out), `"metrics":{"aliases_read":true}`) { |
| + if !strings.Contains(string(out), `"metrics":{"route_channels_reported":true,"aliases_read":true}`) { |
| t.Fatalf("json lacks the aliases_read-only metrics block: %s", out) |
| } |
| off := CollectBox(nil, Probes{Release: "v1"}, at) |
diff --git a/internal/status/status_test.go b/internal/status/status_test.go| index b5e0f2bc9..0d15b26d3 100644 |
| --- a/internal/status/status_test.go |
| +++ b/internal/status/status_test.go |
| @@ -2,11 +2,13 @@ package status_test |
| import ( |
| "bytes" |
| + "cmp" |
| "context" |
| "encoding/json" |
| "errors" |
| "fmt" |
| "reflect" |
| + "slices" |
| "strings" |
| "testing" |
| "time" |
| @@ -386,6 +388,67 @@ func TestCollectBoxCarriesRouteVersions(t *testing.T) { |
| } |
| } |
| +// TestCollectBoxCarriesRouteChannels (#1634): every non-platform route with |
| +// an app is listed by account, app and channel, once each (two routes of |
| +// shop on canary/rc are one entry), managed or not: a |
| +// named-unit route and a unit-backed one count as much as an activator |
| +// route, since root's adopt pass follows their channels too. A legacy row |
| +// with no account reads as the ops account, an empty channel as stable, as |
| +// the adopt pass reads them. A platform alias is a second name, not a |
| +// route, and the field stays private like route_versions. |
| +func TestCollectBoxCarriesRouteChannels(t *testing.T) { |
| + routes := []registry.Route{ |
| + {Host: "a.shop.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "shop", Channel: "canary/rc"}, |
| + {Host: "unit.shop.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "shop", Channel: "canary/old", Unit: "shop-worker"}, |
| + {Host: "backed.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "old", Backing: registry.BackingUnit}, |
| + {Host: "legacy.example.com", Kind: "instance", Status: "ready", App: "legacy", Channel: "beta"}, |
| + {Host: "b.shop.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "shop", Channel: "canary/rc"}, |
| + {Host: "alias.example.com", Kind: "instance", Status: "ready", Account: "bab", App: "alias", Channel: "canary/rc", Platform: true}, |
| + {Host: "noapp.example.com", Kind: "static", Status: "ready"}, |
| + } |
| + b := status.CollectBox(routes, status.Probes{MachineID: "m"}, time.Now()) |
| + if b.Metrics == nil || !b.Metrics.RouteChannelsReported { |
| + t.Fatalf("metrics = %+v, want route channels reported", b.Metrics) |
| + } |
| + want := []status.RouteChannel{ |
| + {Account: release.OpsAccount, App: "legacy", Channel: "beta"}, |
| + {Account: "bab", App: "old", Channel: "stable"}, |
| + {Account: "bab", App: "shop", Channel: "canary/old"}, |
| + {Account: "bab", App: "shop", Channel: "canary/rc"}, |
| + } |
| + slices.SortFunc(want, func(a, b status.RouteChannel) int { |
| + return cmp.Or(cmp.Compare(a.Account, b.Account), cmp.Compare(a.App, b.App), cmp.Compare(a.Channel, b.Channel)) |
| + }) |
| + if fmt.Sprint(b.Metrics.RouteChannels) != fmt.Sprint(want) { |
| + t.Fatalf("route_channels = %v, want %v", b.Metrics.RouteChannels, want) |
| + } |
| + |
| + s := teststore(t) |
| + ctx := context.Background() |
| + f, err := status.BuildFleet(ctx, s, routes, time.Now(), 5*time.Minute) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fj, err := json.Marshal(f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(fj), "shop") || strings.Contains(string(fj), "canary/") { |
| + t.Errorf("fleet.json leaked a route channel: %s", fj) |
| + } |
| +} |
| + |
| +// A box with routes but none with an app still says it reports channels |
| +// whenever its Metrics block attaches, so "no entries" reads as "no |
| +// routes", never as an older binary. |
| +func TestCollectBoxRouteChannelsReportedWithNoAppRoutes(t *testing.T) { |
| + routes := []registry.Route{{Host: "h.test", Kind: "instance", Status: "ready", Version: "v1"}} |
| + b := status.CollectBox(routes, status.Probes{MachineID: "m"}, time.Now()) |
| + if b.Metrics == nil || !b.Metrics.RouteChannelsReported || len(b.Metrics.RouteChannels) != 0 { |
| + t.Fatalf("metrics = %+v, want reported with no entries", b.Metrics) |
| + } |
| +} |
| + |
| // TestCollectBoxRouteVersionsEmptyOmitsField proves a box with no versioned |
| // route contributes no route_versions key at all — omitted, not an empty |
| // object — matching the same "unknown/absent stays absent" convention every |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index d857c528f..55701e6a3 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -228,6 +228,7 @@ op-instance-policy operator operator apps set [--egress-allow,--size] ; instance |
| op-upstreams operator operator instances set-upstreams ; instances create [--addr] TCP backends are set by an operator. |
| op-digests operator operator channels digests [on, off] The digest signing switch. |
| channels-digests operator operator channels digests [report] Operator only: the report needs a system operator (apiSystemRoller). Shows which channel pointers are digest-signed. |
| +channels-retire operator operator channels retire Operator only. Requires a system operator (apiSystemRoller). Retires a canary pointer of an app with no console row, which no member door reaches. |
| op-releases-authorize operator operator releases authorize Signs a promotion record for an old build. |
| op-relay-rotate operator operator relay rotate Rotates a region's relay master. |
| op-move-lost operator operator move resolve [--declare-lost] Declares a box lost in the middle of a move. |