cli: carlos instances label
The client of the console's label door (fleet record labels spec §5, #1008 option B). A positional host, trimmed and lowercased; --box and --dry-run; no --box is a dry run. It prints the door's evidence and verdict in the spec §9 drafts (C01-C17, C19-C38, each marked for copy review), prints "tied" only when applied is true, and exits non-zero on every why_not. A write whose request was sent and got no answer (a timeout, a lost connection, a 502 or 504) prints C38. The clireg node makes the parity row instances-label pass; parity/cli.tsv regenerated by make parity-doc.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
cli.go+1 −0instances_cli.go+319 −0instances_cli_label_test.go+404 −0parity/cli.tsv+1 −0
Intent
<task-notification> <task-id>a530ae3a8ab355f07</task-id> <tool-use-id>toolu_01BXzPCsizW8xdFwfRTSR6Xv</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ac77363b-5830-422c-9f38-d7f2540dd398/tasks/a530ae3a8ab355f07.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: writer and owner door" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS. One test, `TestParityCLIPaths` in `internal/parity`, fails at this commit until Task 5 adds the command (concern 1). - **Commit:** `1b913161` "console: owner ties an unlabelled fleet record to its serving box" (not pushed). - **Tests:** 15 writer tests and 26 door tests failed first (undefined, then failing against a stub), then all pass. A `-race` run of the barrier tests passed. The console route and parity tests pass. The root `TestParity` matches no tests. The darwin build, `go vet` and `gofmt` are clean. - **Concerns:** 1. The `instances-label` parity row must name the `instances label` CLI command, which Task 5 adds. You can keep the row here or move it into Task 5's commit. 2. When a record write fails with an untyped error (such as a store 5xx), the door answers 502 with C38, because the write may have landed. C38's words "the console did not answer in time" don't quite fit that case. 3. The single `labelled` code covers both C20 (already tied) and C34 (another request tied it first), so the CLI can't tell them apart from the code. 4. The stateless `runtime` check can't fire today, because the record floor v0.35.4 is above the stateless runtime floor v0.34.0. I kept it as a guard. 5. Console tests can't reach `firstLabelBeforeWrite`, so the door's race tests use two new console seams, `labelAfterRead` and `labelBeforeMark`. The report lists the other check-order choices the spec left open. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-record-labels/.superpowers/sdd/2026-11-14-fleet-record-labels/task-4-report.md (it is git-excluded, not committed).</result> <usage><subagent_tokens>262788</subagent_tokens><tool_uses>88</tool_uses><duration_ms>1866628</duration_ms></usage> </task-notification>
Attributed to this commit: 5.40 g CO₂e (663,495 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fleet-record-labels-m2, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/cli.go b/cli.go| index a914c06cf..f2c718282 100644 |
| --- a/cli.go |
| +++ b/cli.go |
| @@ -600,6 +600,7 @@ func instancesCommand() *clireg.Node { |
| raw("set-assets", cust, runInstancesSetAssets), |
| raw("set-pages", cust, runInstancesSetPages), |
| raw("retry", cust, runInstancesRetry), |
| + raw("label", cust, runInstancesLabel), |
| }, |
| DefaultLeaf: &clireg.Node{Audience: clireg.BoxLocal, Run: clireg.RawArgs(runInstances)}, |
| DefaultOn: clireg.OnAbsent | clireg.OnFlag | clireg.OnWord, |
diff --git a/instances_cli.go b/instances_cli.go| index 31b0b1845..d62d65011 100644 |
| --- a/instances_cli.go |
| +++ b/instances_cli.go |
| @@ -29,12 +29,14 @@ import ( |
| "fmt" |
| "io" |
| "log" |
| + "net" |
| "net/http" |
| "net/url" |
| "os" |
| "regexp" |
| "slices" |
| "strings" |
| + "time" |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/provision" |
| @@ -230,6 +232,7 @@ var instancesRecordsUsage = `usage: carlos instances create --app <a> --host <h> |
| carlos instances set-assets --app <a> <host> on|off |
| carlos instances set-pages --app <a> <host> on|off |
| carlos instances retry --app <a> <host> |
| + ` + instancesLabelUsageLine + ` |
| ` + updatewords.Text("settings.cli.instances-usage-lines") + ` |
| Signed-in only (carlos auth login): instance records are console-authorized |
| @@ -253,6 +256,8 @@ retry clears the failure hold on one instance: the build that failed on its |
| box is tried again there, as a canary. "carlos promote --retry <version> |
| <channel>" does the same on every box. |
| +` + instancesLabelHelp + ` |
| + |
| ` + updatewords.Text("settings.cli.instances-usage-para") + ` |
| --environment binds a route to one of the app's named config bundles |
| @@ -1247,3 +1252,317 @@ func runInstancesRetry(args []string) { |
| } |
| fmt.Fprintf(stdout, instancesRetryDone+"\n", host, res.Version) |
| } |
| + |
| +// `carlos instances label` (fleet record labels spec §5 and §9, #1008 |
| +// option B): the client of the console's label door. Its strings are the |
| +// spec's drafts, each marked with its key until Paul's copy review. |
| +const ( |
| + instancesLabelUsageLine = "carlos instances label --app <a> <host> [--box <b>] [--dry-run]" // draft for copy review (C01) |
| + instancesLabelHelp = "label ties an instance on a fleet to the box serving it now. without --box, or with --dry-run, it only shows what it found and changes nothing" // draft for copy review (C02) |
| + instancesLabelFlagBox = "the box to tie it to. it must be the box serving it now" // draft for copy review (C03) |
| + instancesLabelFlagDry = "show what would happen and change nothing" // draft for copy review (C04) |
| + instancesLabelOneHost = "name one instance host" // draft for copy review (C05) |
| + |
| + labelNotTied = "%s is not tied to a box of fleet %s" // draft for copy review (C06) |
| + labelNothingToDo = "%s is already tied to %s. nothing to do" // draft for copy review (C07) |
| + labelBindingSeen = "last binding reported: %s (%s ago)" // draft for copy review (C08) |
| + labelNoBinding = "no box has reported a binding for it since it was created" // draft for copy review (C09) |
| + labelHubBox = "the hub sends its requests to %s" // draft for copy review (C10) |
| + labelNoHubBox = "the hub has no box for it yet" // draft for copy review (C10) |
| + labelAgree = "these agree: %s looks like the box serving it" // draft for copy review (C11) |
| + labelDisagree = "these disagree. wait for it to settle, or open it once, then try again in about 10 minutes" // draft for copy review (C12) |
| + labelNotProof = "this is what the boxes reported, not proof of which box runs it now" // draft for copy review (C13) |
| + labelCanTake = "%s can take it. tie it with carlos instances label --app %s %s --box %s" // draft for copy review (C14) |
| + labelIfWrong = "if the report is wrong, tying it moves it: it stops on the box that runs it and starts on %s from its last saved copy" // draft for copy review (C15) |
| + labelDryRun = "dry run. nothing changed" // draft for copy review (C16) |
| + labelTied = "tied %s to %s. the other boxes stop carrying it once they update, usually within seconds" // draft for copy review (C17) |
| + labelNotOnFleet = "%s is not on a fleet" // draft for copy review (C19) |
| + labelAlreadyTied = "%s is already tied to %s. to move it, drain that box with carlos fleets drain" // draft for copy review (C20) |
| + labelCopies = "%s runs as copies, so placement chooses its boxes" // draft for copy review (C21) |
| + labelMoving = "%s has a move in progress. finish it before tying it to a box" // draft for copy review (C22) |
| + labelImporting = "%s has an import in progress. finish it before tying it to a box" // draft for copy review (C23) |
| + labelCoordinated = "%s is coordinated by %s right now. try again in a few minutes" // draft for copy review (C24) |
| + labelNotActive = "%s is not an active box of fleet %s" // draft for copy review (C25) |
| + labelDraining = "%s is draining. it cannot take an instance" // draft for copy review (C26) |
| + labelStale = "%s has not reported in recently" // draft for copy review (C27) |
| + labelRuntime = "%s cannot run this app's runtime yet" // draft for copy review (C28) |
| + labelFloor = "%s runs %s. every box of fleet %s needs %s or later before instances can be tied to boxes" // draft for copy review (C29) |
| + labelNotServing = "%s is not the box serving it now. only that box can be named for now" // draft for copy review (C30) |
| + labelUnmovable = "%s cannot be tied to one box: %s" // draft for copy review (C31) |
| + labelSidecars = "fleet %s has sidecars, so its instances cannot be tied to boxes yet" // draft for copy review (C32) |
| + labelCompetingWrite = "another change tied %s to %s first. nothing more changed" // draft for copy review (C34) |
| + labelChanged = "%s changed while it was being tied, so it was not tied. try again" // draft for copy review (C35) |
| + labelMarkFailed = "could not mark %s for this instance, so it was not tied. try again" // draft for copy review (C36) |
| + labelReadFailed = "could not read the instance and its fleet, so it was not tied. try again" // draft for copy review (C37) |
| + labelUnknown = "the result is unknown: the console did not answer in time. run carlos instances label --app %s %s to see whether it is tied" // draft for copy review (C38) |
| +) |
| + |
| +// labelUnmovableReasons are C31's reasons, by the door's unmovable:<reason>. |
| +var labelUnmovableReasons = map[string]string{ |
| + "static": "every box serves a static site", // draft for copy review (C31) |
| + "addr": "it is served from an address the platform does not manage", // draft for copy review (C31) |
| + "always_on": "it never sleeps and keeps a local database", // draft for copy review (C31) |
| + "unit": "it runs as a system unit", // draft for copy review (C31) |
| + "ha": "it is a high availability instance", // draft for copy review (C31) |
| + "demo": "it is a demo", // draft for copy review (C31) |
| +} |
| + |
| +// labelUnstatedCoordinator and labelUnstatedRelease fill C24's and C29's |
| +// second blanks: the door's answer carries neither the coordinating box nor |
| +// the release a box runs (task 5 report, concerns). |
| +const ( |
| + labelUnstatedCoordinator = "another box" |
| + labelUnstatedRelease = "an older release" |
| +) |
| + |
| +// instanceLabelBinding mirrors the door's labelBinding. |
| +type instanceLabelBinding struct { |
| + Box string `json:"box"` |
| + BoundAt int64 `json:"bound_at"` // milliseconds |
| + AfterCreate bool `json:"after_create"` |
| +} |
| + |
| +// instanceLabelAnswer mirrors the door's instanceLabelAnswer |
| +// (internal/console/instancelabel.go), its one answer shape past the gate. |
| +// Applied is true only after the record write committed: a 200 is not |
| +// "applied". |
| +type instanceLabelAnswer struct { |
| + Host string `json:"host"` |
| + Fleet string `json:"fleet"` |
| + Label string `json:"label"` |
| + Binding *instanceLabelBinding `json:"binding"` |
| + HubBox string `json:"hub_box"` |
| + Agree bool `json:"agree"` |
| + ServingBox string `json:"serving_box"` |
| + Box string `json:"box"` |
| + Eligible bool `json:"eligible"` |
| + WhyNot string `json:"why_not"` |
| + Applied bool `json:"applied"` |
| +} |
| + |
| +// instanceLabelHTTPTimeout outlasts the door's own 30-second bound |
| +// (labelDoorTimeout), so the door, not this client, says when it gave up. |
| +const instanceLabelHTTPTimeout = 40 * time.Second |
| + |
| +// errLabelOutcomeUnknown is a write whose request was sent and whose answer |
| +// never came: a timeout, a lost connection, an unreadable answer, or a |
| +// gateway's 502 or 504. The record may or may not have changed. |
| +var errLabelOutcomeUnknown = errors.New("label: outcome unknown") |
| + |
| +// instanceLabel is the door's request. With box empty, or dryRun, nothing |
| +// is written and the door says so (dry_run true). A write that was sent and |
| +// got no readable answer is errLabelOutcomeUnknown; a request that never |
| +// left (the dial failed) is its own error. |
| +func (s *apiSession) instanceLabel(ctx context.Context, acct apiAcct, app, host, box string, dryRun bool) (*instanceLabelAnswer, error) { |
| + clone, client := *s, *s.c |
| + httpc := *s.c.httpc |
| + httpc.Timeout = instanceLabelHTTPTimeout |
| + client.httpc = &httpc |
| + clone.c = &client |
| + |
| + write := box != "" && !dryRun |
| + in := struct { |
| + Box string `json:"box"` |
| + DryRun bool `json:"dry_run"` |
| + }{box, !write} |
| + status, body, err := clone.postJSON(ctx, apiPath(acct, app, "/instances/"+url.PathEscape(host)+"/label"), in) |
| + switch { |
| + case err != nil && write && (status == http.StatusOK || status == 0 && !labelNotSent(err)): |
| + return nil, errLabelOutcomeUnknown |
| + case err != nil: |
| + return nil, err |
| + case write && (status == http.StatusBadGateway || status == http.StatusGatewayTimeout): |
| + return nil, errLabelOutcomeUnknown |
| + case status != http.StatusOK: |
| + return nil, apiErrorFromBody(status, body) |
| + } |
| + var out instanceLabelAnswer |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + if write { |
| + return nil, errLabelOutcomeUnknown |
| + } |
| + return nil, fmt.Errorf("instances label: unreadable response: %w", err) |
| + } |
| + return &out, nil |
| +} |
| + |
| +// labelNotSent reports whether err is a request that never reached the |
| +// console: the connection was never made. |
| +func labelNotSent(err error) bool { |
| + var op *net.OpError |
| + return errors.As(err, &op) && op.Op == "dial" |
| +} |
| + |
| +// instancesLabel asks the door and prints its answer to w. The error is the |
| +// line the verb exits non-zero on: a refusal's copy, C38 for an unknown |
| +// outcome, or the console's own refusal (owner only, not found). |
| +func instancesLabel(ctx context.Context, w io.Writer, s *apiSession, acct apiAcct, app, host, box string, dryRun bool, now time.Time) error { |
| + ans, err := s.instanceLabel(ctx, acct, app, host, box, dryRun) |
| + if errors.Is(err, errLabelOutcomeUnknown) { |
| + return fmt.Errorf(labelUnknown, app, host) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + return renderInstanceLabel(w, app, host, box != "" && !dryRun, ans, now) |
| +} |
| + |
| +// renderInstanceLabel prints one answer. Tied (C17) is printed only when |
| +// applied is true. The evidence (C06, C08-C11, C13) is printed for every |
| +// answer the door judged; the record refusals it answers before reading |
| +// the fleet carry none. |
| +func renderInstanceLabel(w io.Writer, app, host string, write bool, a *instanceLabelAnswer, now time.Time) error { |
| + if a.Host != "" { |
| + host = a.Host |
| + } |
| + if a.Applied { |
| + fmt.Fprintf(w, labelTied+"\n", host, a.Label) |
| + return nil |
| + } |
| + if a.WhyNot == labelWhyLabelled { |
| + // The door answers labelled both for a record tied before it was |
| + // read (an early answer, with no evidence) and for a competing |
| + // label that won the write (judged, so it carries the evidence). |
| + switch { |
| + case write && a.ServingBox != "": |
| + return fmt.Errorf(labelCompetingWrite, host, a.Label) |
| + case a.Box != "" && a.Box != a.Label: |
| + return fmt.Errorf(labelAlreadyTied, host, a.Label) |
| + } |
| + fmt.Fprintf(w, labelNothingToDo+"\n", host, a.Label) |
| + return nil |
| + } |
| + if a.Fleet != "" && !(labelEarlyRefusal(a.WhyNot) && !a.Agree) { |
| + fmt.Fprintf(w, labelNotTied+"\n", host, a.Fleet) |
| + if b := a.Binding; b != nil && b.AfterCreate { |
| + age := now.Sub(time.UnixMilli(b.BoundAt)) |
| + if age < 0 { |
| + age = 0 |
| + } |
| + fmt.Fprintf(w, " "+labelBindingSeen+"\n", b.Box, fmtDur(age)) |
| + } else { |
| + fmt.Fprintln(w, " "+labelNoBinding) |
| + } |
| + if a.HubBox != "" { |
| + fmt.Fprintf(w, " "+labelHubBox+"\n", a.HubBox) |
| + } else { |
| + fmt.Fprintln(w, " "+labelNoHubBox) |
| + } |
| + if a.Agree { |
| + fmt.Fprintf(w, " "+labelAgree+"\n", a.ServingBox) |
| + } |
| + mutedf(w, " "+labelNotProof+"\n") |
| + } |
| + if a.WhyNot != "" { |
| + return errors.New(labelRefusal(host, a)) |
| + } |
| + if write { |
| + // Eligible and asked to write, yet not applied: the door's |
| + // contract never answers this, so the outcome is not known. |
| + return fmt.Errorf(labelUnknown, app, host) |
| + } |
| + fmt.Fprintf(w, labelCanTake+"\n", a.Box, app, host, a.Box) |
| + fmt.Fprintf(w, labelIfWrong+"\n", a.Box) |
| + fmt.Fprintln(w, labelDryRun) |
| + return nil |
| +} |
| + |
| +// The door's why_not codes (internal/console/instancelabel.go), mirrored. |
| +const ( |
| + labelWhyLabelled = "labelled" |
| + labelWhyUnmovPfx = "unmovable:" |
| +) |
| + |
| +// labelEarlyRefusal is a code the door can answer from the record alone, |
| +// before it reads the fleet's evidence. assigned, move and import are also |
| +// the writer's refusals after a judged read; those carry agree. |
| +func labelEarlyRefusal(code string) bool { |
| + switch code { |
| + case "not_fleet", labelWhyLabelled, "assigned", "move", "import", labelWhyUnmovPfx + "static": |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// labelRefusal is the copy for a why_not other than labelled. A code this |
| +// binary does not know is named as it came. |
| +func labelRefusal(host string, a *instanceLabelAnswer) string { |
| + switch a.WhyNot { |
| + case "not_fleet": |
| + return fmt.Sprintf(labelNotOnFleet, host) |
| + case "assigned": |
| + return fmt.Sprintf(labelCopies, host) |
| + case "move": |
| + return fmt.Sprintf(labelMoving, host) |
| + case "import": |
| + return fmt.Sprintf(labelImporting, host) |
| + case "coordinated": |
| + return fmt.Sprintf(labelCoordinated, host, labelUnstatedCoordinator) |
| + case "not_active": |
| + return fmt.Sprintf(labelNotActive, a.Box, a.Fleet) |
| + case "draining": |
| + return fmt.Sprintf(labelDraining, a.Box) |
| + case "stale": |
| + return fmt.Sprintf(labelStale, a.Box) |
| + case "runtime": |
| + return fmt.Sprintf(labelRuntime, a.Box) |
| + case "floor": |
| + return fmt.Sprintf(labelFloor, a.Box, labelUnstatedRelease, a.Fleet, release.FleetRecordLabelFloor) |
| + case "not_serving": |
| + return fmt.Sprintf(labelNotServing, a.Box) |
| + case "disagree": |
| + return labelDisagree |
| + case "no_evidence": |
| + if b := a.Binding; b == nil || !b.AfterCreate { |
| + return labelNoBinding |
| + } |
| + return labelNoHubBox |
| + case "sidecars": |
| + return fmt.Sprintf(labelSidecars, a.Fleet) |
| + case "incomplete": |
| + return labelReadFailed |
| + case "changed": |
| + return fmt.Sprintf(labelChanged, host) |
| + case "mark_failed": |
| + return fmt.Sprintf(labelMarkFailed, a.Box) |
| + } |
| + if reason, ok := strings.CutPrefix(a.WhyNot, labelWhyUnmovPfx); ok { |
| + if text, ok := labelUnmovableReasons[reason]; ok { |
| + reason = text |
| + } |
| + return fmt.Sprintf(labelUnmovable, host, reason) |
| + } |
| + return host + ": " + a.WhyNot |
| +} |
| + |
| +// runInstancesLabel is `carlos instances label <host>` (fleet record labels |
| +// spec §5). The host may come first or after the flags. Without --box it |
| +// is a dry run. |
| +func runInstancesLabel(args []string) { |
| + host, args := leadingArg(args) |
| + fs := flag.NewFlagSet("instances label", flag.ExitOnError) |
| + app := appFlag(fs, "app the instance belongs to") |
| + box := fs.String("box", "", instancesLabelFlagBox) |
| + dryRun := fs.Bool("dry-run", false, instancesLabelFlagDry) |
| + consoleFlag := consoleOption(fs, "console to act through (default: the only logged-in one)") |
| + acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)") |
| + acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY — supersedes --account") |
| + fs.Usage = flagUsage(fs, instancesRecordsUsage) |
| + fs.Parse(args) |
| + if host == "" && fs.NArg() == 1 { |
| + host = strings.TrimSpace(fs.Arg(0)) |
| + } else if fs.NArg() != 0 { |
| + host = "" |
| + } |
| + if host == "" { |
| + log.Fatalf("%s\nusage: %s", instancesLabelOneHost, instancesLabelUsageLine) |
| + } |
| + host = strings.ToLower(host) |
| + sess := requireAPISession("label", *consoleFlag) |
| + printUsing(stdout, sess) |
| + acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| + app2 := resolvedApp(sess, acct, *app, instancesRecordsUsage) |
| + if err := instancesLabel(context.Background(), stdout, sess, acct, app2, host, strings.TrimSpace(*box), *dryRun, time.Now()); err != nil { |
| + log.Fatal(err) |
| + } |
| +} |
diff --git a/instances_cli_label_test.go b/instances_cli_label_test.go| new file mode 100644 |
| index 000000000..74fe07034 |
| --- /dev/null |
| +++ b/instances_cli_label_test.go |
| @@ -0,0 +1,404 @@ |
| +// Tests for `carlos instances label`, the client of the console's label door |
| +// (fleet record labels spec §5 and §9, internal/console/instancelabel.go). |
| +// The verb runs as a real subprocess against an httptest console stub: |
| +// refusals exit non-zero through log.Fatal, and every subprocess goes |
| +// through carlosTestEnv with cmd.Dir set to scratch (AGENTS.md). The one |
| +// in-process case is the unknown outcome's deadline, which needs the test |
| +// to end the request's context at a channel barrier. |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// labelStub is a console that answers the label door with a canned body |
| +// and status, and keeps the path and body of the last request. |
| +type labelStub struct { |
| + ts *httptest.Server |
| + mu sync.Mutex |
| + status int |
| + answer string // the JSON body |
| + path string |
| + body map[string]any |
| + calls int |
| +} |
| + |
| +func newLabelStub(t *testing.T, status int, answer string) *labelStub { |
| + t.Helper() |
| + s := &labelStub{status: status, answer: answer} |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("POST /api/cli/apps/{account}/{app}/instances/{host}/label", func(w http.ResponseWriter, r *http.Request) { |
| + var body map[string]any |
| + json.NewDecoder(r.Body).Decode(&body) |
| + s.mu.Lock() |
| + s.path, s.body, s.calls = r.URL.Path, body, s.calls+1 |
| + s.mu.Unlock() |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(s.status) |
| + io.WriteString(w, s.answer) |
| + }) |
| + s.ts = httptest.NewServer(mux) |
| + t.Cleanup(s.ts.Close) |
| + return s |
| +} |
| + |
| +func (s *labelStub) last() (string, map[string]any, int) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.path, s.body, s.calls |
| +} |
| + |
| +// runLabelCLI runs `carlos instances label <args>` against console, signed |
| +// in with a credential written to a scratch home. It returns the combined |
| +// output and whether the process exited 0. |
| +func runLabelCLI(t *testing.T, console string, args ...string) (string, bool) { |
| + t.Helper() |
| + bin := buildCarlos(t) |
| + scratch := t.TempDir() |
| + creds := filepath.Join(scratch, "credentials") |
| + writeTestCredential(t, creds, console) |
| + cmd := exec.Command(bin, append([]string{"instances", "label"}, args...)...) |
| + cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "HOME="+scratch) |
| + cmd.Dir = scratch |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + var ee *exec.ExitError |
| + if !errors.As(err, &ee) { |
| + t.Fatalf("carlos did not run: %v", err) |
| + } |
| + } |
| + return string(out), err == nil |
| +} |
| + |
| +// labelAnswerJSON is an eligible dry-run answer for shop.example.com on |
| +// fleet pi, with agreeing evidence for box-1, then the overrides. |
| +func labelAnswerJSON(t *testing.T, over map[string]any) string { |
| + t.Helper() |
| + a := map[string]any{ |
| + "host": "shop.example.com", "fleet": "pi", "label": "", |
| + "binding": map[string]any{"box": "box-1", "bound_at": time.Now().Add(-3 * time.Minute).UnixMilli(), "after_create": true}, |
| + "hub_box": "box-1", "agree": true, "serving_box": "box-1", "box": "box-1", |
| + "eligible": true, "why_not": "", "applied": false, |
| + } |
| + for k, v := range over { |
| + a[k] = v |
| + } |
| + raw, err := json.Marshal(a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return string(raw) |
| +} |
| + |
| +const ( |
| + labelC13 = "this is what the boxes reported, not proof of which box runs it now" |
| + labelC16 = "dry run. nothing changed" |
| + labelC17 = "tied shop.example.com to box-1. the other boxes stop carrying it once they update, usually within seconds" |
| + labelC38 = "the result is unknown: the console did not answer in time. run carlos instances label --app shop shop.example.com to see whether it is tied" |
| +) |
| + |
| +// With no --box the request is a dry run, and the answer's evidence is |
| +// printed with what it is not (C13) and that nothing changed (C16). |
| +func TestInstancesLabelDryRunByDefault(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusOK, labelAnswerJSON(t, nil)) |
| + out, ok := runLabelCLI(t, stub.ts.URL, "--app", "shop", "--account", "bab", "shop.example.com") |
| + if !ok { |
| + t.Fatalf("exited non-zero:\n%s", out) |
| + } |
| + path, body, _ := stub.last() |
| + if path != "/api/cli/apps/bab/shop/instances/shop.example.com/label" { |
| + t.Fatalf("path = %q", path) |
| + } |
| + if body["dry_run"] != true || body["box"] != "" { |
| + t.Fatalf("body = %v, want dry_run true and no box", body) |
| + } |
| + for _, want := range []string{ |
| + "shop.example.com is not tied to a box of fleet pi", |
| + "last binding reported: box-1 (", |
| + "the hub sends its requests to box-1", |
| + "these agree: box-1 looks like the box serving it", |
| + labelC13, |
| + "box-1 can take it. tie it with carlos instances label --app shop shop.example.com --box box-1", |
| + "if the report is wrong, tying it moves it: it stops on the box that runs it and starts on box-1 from its last saved copy", |
| + labelC16, |
| + } { |
| + if !strings.Contains(out, want) { |
| + t.Errorf("output missing %q:\n%s", want, out) |
| + } |
| + } |
| + if strings.Contains(out, "the other boxes stop carrying it") { |
| + t.Errorf("a dry run printed C17:\n%s", out) |
| + } |
| +} |
| + |
| +// --box with --dry-run is still a dry run, naming the box. |
| +func TestInstancesLabelBoxDryRunSendsBoth(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusOK, labelAnswerJSON(t, nil)) |
| + out, ok := runLabelCLI(t, stub.ts.URL, "shop.example.com", "--app", "shop", "--account", "bab", "--box", "box-1", "--dry-run") |
| + if !ok { |
| + t.Fatalf("exited non-zero:\n%s", out) |
| + } |
| + _, body, _ := stub.last() |
| + if body["dry_run"] != true || body["box"] != "box-1" { |
| + t.Fatalf("body = %v, want dry_run true and box box-1", body) |
| + } |
| + if !strings.Contains(out, labelC16) { |
| + t.Fatalf("output missing C16:\n%s", out) |
| + } |
| +} |
| + |
| +// An applied answer prints C17, and only C17. |
| +func TestInstancesLabelAppliedPrintsTied(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusOK, labelAnswerJSON(t, map[string]any{"applied": true, "label": "box-1"})) |
| + out, ok := runLabelCLI(t, stub.ts.URL, "--app", "shop", "--account", "bab", "--box", "box-1", "shop.example.com") |
| + if !ok { |
| + t.Fatalf("exited non-zero:\n%s", out) |
| + } |
| + _, body, _ := stub.last() |
| + if body["dry_run"] != false || body["box"] != "box-1" { |
| + t.Fatalf("body = %v, want a write to box-1", body) |
| + } |
| + if !strings.Contains(out, labelC17) { |
| + t.Fatalf("output missing C17:\n%s", out) |
| + } |
| + if strings.Contains(out, labelC16) || strings.Contains(out, "is not tied to a box") { |
| + t.Fatalf("an applied write printed dry-run lines:\n%s", out) |
| + } |
| +} |
| + |
| +// A 200 is not "applied": without applied true, C17 never prints, for a |
| +// write or a dry run. A write the door answered eligible but not applied |
| +// has an unknown outcome. |
| +func TestInstancesLabelUnappliedIsNotTied(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusOK, labelAnswerJSON(t, map[string]any{"applied": false})) |
| + for _, tc := range []struct { |
| + args []string |
| + write bool |
| + }{ |
| + {[]string{"--app", "shop", "--account", "bab", "--box", "box-1", "shop.example.com"}, true}, |
| + {[]string{"--app", "shop", "--account", "bab", "shop.example.com"}, false}, |
| + {[]string{"--app", "shop", "--account", "bab", "--box", "box-1", "--dry-run", "shop.example.com"}, false}, |
| + } { |
| + out, ok := runLabelCLI(t, stub.ts.URL, tc.args...) |
| + if strings.Contains(out, "the other boxes stop carrying it") || strings.Contains(out, "tied shop.example.com to") { |
| + t.Errorf("%v printed C17 without applied:\n%s", tc.args, out) |
| + } |
| + if tc.write && (ok || !strings.Contains(out, labelC38)) { |
| + t.Errorf("%v: a write not applied exited 0 or missed C38:\n%s", tc.args, out) |
| + } |
| + if !tc.write && !ok { |
| + t.Errorf("%v: an eligible dry run exited non-zero:\n%s", tc.args, out) |
| + } |
| + } |
| +} |
| + |
| +// Every why_not code prints its copy and exits non-zero. |
| +func TestInstancesLabelRefusalExitsNonZero(t *testing.T) { |
| + refused := func(code string, over map[string]any) map[string]any { |
| + m := map[string]any{"why_not": code, "eligible": false} |
| + for k, v := range over { |
| + m[k] = v |
| + } |
| + return m |
| + } |
| + early := map[string]any{"binding": nil, "hub_box": "", "agree": false, "serving_box": ""} |
| + withEarly := func(code string, extra map[string]any) map[string]any { |
| + m := refused(code, early) |
| + for k, v := range extra { |
| + m[k] = v |
| + } |
| + return m |
| + } |
| + write := []string{"--box", "box-1"} |
| + for _, tc := range []struct { |
| + name string |
| + over map[string]any |
| + args []string |
| + want string |
| + }{ |
| + {"not_fleet", withEarly("not_fleet", map[string]any{"fleet": ""}), nil, "shop.example.com is not on a fleet"}, |
| + {"labelled before the read", withEarly("labelled", map[string]any{"label": "box-2"}), write, |
| + "shop.example.com is already tied to box-2. to move it, drain that box with carlos fleets drain"}, |
| + {"labelled by a competing write", refused("labelled", map[string]any{"label": "box-2"}), write, |
| + "another change tied shop.example.com to box-2 first. nothing more changed"}, |
| + {"assigned", withEarly("assigned", nil), nil, "shop.example.com runs as copies, so placement chooses its boxes"}, |
| + {"move", withEarly("move", nil), nil, "shop.example.com has a move in progress. finish it before tying it to a box"}, |
| + {"import", withEarly("import", nil), nil, "shop.example.com has an import in progress. finish it before tying it to a box"}, |
| + {"coordinated", refused("coordinated", nil), nil, "shop.example.com is coordinated by"}, |
| + {"not_active", refused("not_active", nil), nil, "box-1 is not an active box of fleet pi"}, |
| + {"draining", refused("draining", nil), nil, "box-1 is draining. it cannot take an instance"}, |
| + {"stale", refused("stale", nil), nil, "box-1 has not reported in recently"}, |
| + {"runtime", refused("runtime", nil), nil, "box-1 cannot run this app's runtime yet"}, |
| + {"floor", refused("floor", nil), nil, "before instances can be tied to boxes"}, |
| + {"not_serving", refused("not_serving", map[string]any{"box": "box-2"}), []string{"--box", "box-2"}, |
| + "box-2 is not the box serving it now. only that box can be named for now"}, |
| + {"disagree", refused("disagree", map[string]any{"hub_box": "box-2", "agree": false, "serving_box": "", "box": ""}), nil, |
| + "these disagree. wait for it to settle, or open it once, then try again in about 10 minutes"}, |
| + {"no_evidence: no binding", refused("no_evidence", map[string]any{"binding": nil, "agree": false, "serving_box": "", "box": ""}), nil, |
| + "no box has reported a binding for it since it was created"}, |
| + {"no_evidence: no hub row", refused("no_evidence", map[string]any{"hub_box": "", "agree": false, "serving_box": "", "box": ""}), nil, |
| + "the hub has no box for it yet"}, |
| + {"unmovable:static", withEarly("unmovable:static", nil), nil, "shop.example.com cannot be tied to one box: every box serves a static site"}, |
| + {"unmovable:addr", refused("unmovable:addr", nil), nil, "shop.example.com cannot be tied to one box: it is served from an address the platform does not manage"}, |
| + {"unmovable:always_on", refused("unmovable:always_on", nil), nil, "shop.example.com cannot be tied to one box: it never sleeps and keeps a local database"}, |
| + {"unmovable:unit", refused("unmovable:unit", nil), nil, "shop.example.com cannot be tied to one box: it runs as a system unit"}, |
| + {"unmovable:ha", refused("unmovable:ha", nil), nil, "shop.example.com cannot be tied to one box: it is a high availability instance"}, |
| + {"unmovable:demo", refused("unmovable:demo", nil), nil, "shop.example.com cannot be tied to one box: it is a demo"}, |
| + {"sidecars", refused("sidecars", nil), nil, "fleet pi has sidecars, so its instances cannot be tied to boxes yet"}, |
| + {"incomplete", refused("incomplete", nil), nil, "could not read the instance and its fleet, so it was not tied. try again"}, |
| + {"changed", refused("changed", nil), write, "shop.example.com changed while it was being tied, so it was not tied. try again"}, |
| + {"mark_failed", refused("mark_failed", nil), write, "could not mark box-1 for this instance, so it was not tied. try again"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusOK, labelAnswerJSON(t, tc.over)) |
| + args := append([]string{"--app", "shop", "--account", "bab"}, tc.args...) |
| + out, ok := runLabelCLI(t, stub.ts.URL, append(args, "shop.example.com")...) |
| + if ok { |
| + t.Fatalf("exited 0 on why_not %s:\n%s", tc.name, out) |
| + } |
| + if !strings.Contains(out, tc.want) { |
| + t.Fatalf("output missing %q:\n%s", tc.want, out) |
| + } |
| + if strings.Contains(out, labelC16) || strings.Contains(out, "can take it") { |
| + t.Fatalf("a refusal printed the eligible lines:\n%s", out) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Asking again about an instance already tied (the re-run C38 points to) |
| +// says so and exits 0: the state asked about holds. |
| +func TestInstancesLabelAlreadyTiedIsNothingToDo(t *testing.T) { |
| + ans := labelAnswerJSON(t, map[string]any{"why_not": "labelled", "eligible": false, "label": "box-1", |
| + "binding": nil, "hub_box": "", "agree": false, "serving_box": ""}) |
| + stub := newLabelStub(t, http.StatusOK, ans) |
| + for _, args := range [][]string{ |
| + {"--app", "shop", "--account", "bab", "shop.example.com"}, |
| + {"--app", "shop", "--account", "bab", "--box", "box-1", "shop.example.com"}, |
| + } { |
| + out, ok := runLabelCLI(t, stub.ts.URL, args...) |
| + if !ok || !strings.Contains(out, "shop.example.com is already tied to box-1. nothing to do") { |
| + t.Errorf("%v: want C07 and exit 0, got ok=%v:\n%s", args, ok, out) |
| + } |
| + } |
| +} |
| + |
| +// A write whose outcome is unknown prints C38 and exits non-zero: the |
| +// context ending while the console holds the request (the deadline), the |
| +// connection lost after the request was sent, and the door's own 502. |
| +func TestInstancesLabelUnknownOutcome(t *testing.T) { |
| + // hanging is a console that, once it has read the whole request, holds |
| + // it until the client goes away: arrived is the barrier. |
| + hanging := func(t *testing.T) (*httptest.Server, chan struct{}) { |
| + arrived := make(chan struct{}, 1) |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + io.Copy(io.Discard, r.Body) |
| + arrived <- struct{}{} |
| + <-r.Context().Done() |
| + })) |
| + t.Cleanup(ts.Close) |
| + return ts, arrived |
| + } |
| + |
| + t.Run("deadline", func(t *testing.T) { |
| + ts, arrived := hanging(t) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + go func() { |
| + <-arrived |
| + cancel() // the deadline passes while the console holds the write |
| + }() |
| + var out bytes.Buffer |
| + err := instancesLabel(ctx, &out, newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", "shop.example.com", "box-1", false, time.Now()) |
| + if err == nil || err.Error() != labelC38 { |
| + t.Fatalf("err = %v, want C38", err) |
| + } |
| + if strings.Contains(out.String(), "tied shop.example.com to") { |
| + t.Fatalf("printed C17:\n%s", out.String()) |
| + } |
| + }) |
| + |
| + t.Run("dry run past the deadline is not C38", func(t *testing.T) { |
| + ts, arrived := hanging(t) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + go func() { |
| + <-arrived |
| + cancel() |
| + }() |
| + var out bytes.Buffer |
| + err := instancesLabel(ctx, &out, newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", "shop.example.com", "", true, time.Now()) |
| + if err == nil || err.Error() == labelC38 { |
| + t.Fatalf("err = %v, want a plain error (nothing was written)", err) |
| + } |
| + }) |
| + |
| + t.Run("connection lost after the write was sent", func(t *testing.T) { |
| + ts, arrived := hanging(t) |
| + go func() { |
| + <-arrived |
| + ts.CloseClientConnections() |
| + }() |
| + out, ok := runLabelCLI(t, ts.URL, "--app", "shop", "--account", "bab", "--box", "box-1", "shop.example.com") |
| + if ok || !strings.Contains(out, labelC38) { |
| + t.Fatalf("want C38 and a non-zero exit, got ok=%v:\n%s", ok, out) |
| + } |
| + }) |
| + |
| + t.Run("the door's 502", func(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusBadGateway, `{"error":"`+labelC38+`"}`) |
| + out, ok := runLabelCLI(t, stub.ts.URL, "--app", "shop", "--account", "bab", "--box", "box-1", "shop.example.com") |
| + if ok || !strings.Contains(out, labelC38) { |
| + t.Fatalf("want C38 and a non-zero exit, got ok=%v:\n%s", ok, out) |
| + } |
| + }) |
| +} |
| + |
| +// The host is trimmed and lowercased before it reaches the path (plan |
| +// review focus), as instances retry does. |
| +func TestInstancesLabelNormalisesTheHost(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusOK, labelAnswerJSON(t, nil)) |
| + for _, args := range [][]string{ |
| + {" Shop.Example.COM ", "--app", "shop", "--account", "bab"}, |
| + {"--app", "shop", "--account", "bab", " SHOP.example.com "}, |
| + } { |
| + out, ok := runLabelCLI(t, stub.ts.URL, args...) |
| + if !ok { |
| + t.Fatalf("%q exited non-zero:\n%s", args, out) |
| + } |
| + if path, _, _ := stub.last(); path != "/api/cli/apps/bab/shop/instances/shop.example.com/label" { |
| + t.Fatalf("%q: path = %q", args, path) |
| + } |
| + } |
| +} |
| + |
| +// No host, or two, is C05, and nothing is sent. |
| +func TestInstancesLabelArgErrors(t *testing.T) { |
| + stub := newLabelStub(t, http.StatusOK, labelAnswerJSON(t, nil)) |
| + for _, args := range [][]string{ |
| + {"--app", "shop", "--account", "bab"}, |
| + {"--app", "shop", "--account", "bab", "shop.example.com", "other.example.com"}, |
| + {"shop.example.com", "--app", "shop", "--account", "bab", "other.example.com"}, |
| + {" ", "--app", "shop", "--account", "bab"}, |
| + } { |
| + out, ok := runLabelCLI(t, stub.ts.URL, args...) |
| + if ok || !strings.Contains(out, "name one instance host") { |
| + t.Errorf("%q: want C05 and a non-zero exit, got ok=%v:\n%s", args, ok, out) |
| + } |
| + } |
| + if _, _, calls := stub.last(); calls != 0 { |
| + t.Fatalf("the console saw %d requests, want 0", calls) |
| + } |
| +} |
diff --git a/parity/cli.tsv b/parity/cli.tsv| index 8afcf425e..da3891c35 100644 |
| --- a/parity/cli.tsv |
| +++ b/parity/cli.tsv |
| @@ -132,6 +132,7 @@ instances enable customer - - - - - |
| instances import customer - - - - - |
| instances import abort customer - - - - - |
| instances import commit customer - - - - - |
| +instances label customer - - - - - |
| instances list customer - - - - - |
| instances retry customer - - - - - |
| instances set customer - - - - - |