carlos / platform Public

Managed fleets 1b task 6b: the relabel worker, the two-step drain and the drain rule

FleetRelabel (every 5 minutes, started from serve; off on a host-claim
console) takes each fleet under its lock from one loadFleetView:

- A fleet with labels and a box reporting a release below the label
  floor is paused: an ERROR line names fleet, box and release, and
  nothing else happens for it. `carlos fleets ls` shows LABELS PAUSED
  from the same test (labelsPausedBy).
- Read whole, a record on a draining, lost (no heartbeat for
  fleetBoxLostAfter = lease.LeaseTTL + 5m) or detached box moves to
  chooseDestination(rootfs, its box). Moves need no open gate (ruling 1).
- With the gate open, an unlabelled record is labelled to the box its
  binding names, when the binding was written for this record (same
  fleet and host, after CreatedAt) and the box is a valid destination.
  No binding: it stays unlabelled; the console never picks a box for an
  existing record (ruling 5).

Reads come first; a binding that cannot be read writes nothing. Every
write marks the box labelled, then SetRecordFleetBox with what the pass
read; ErrFleetBoxImportInFlight (checked first, ruling 4) and
ErrFleetBoxMoved are left for a later pass. One log line per move: host,
from, to, reason.

`carlos fleets drain` (POST .../boxes/{label}/drain, zero service roles,
refused on a host-claim console) moves every record the box runs or
refuses up front naming the apps, with nothing written: an unlabelled
record (every box runs it), one movable refuses (Addr/Addrs, never
hibernates, HA: ruling 3) or one with no other box. Then the box is
marked draining and its records relabelled; the worker finishes any
the drain could not move at once.

drainDone(hb, drainingSince) is the drain rule: a heartbeat composed
after the drain began, from a release at the label floor (an older box
reports no leases at all), with no resident, hibernating or sidecar
routes, no held leases and no failed final replications (ruling 2).
Static routes do not count. Both detach doors ask it, under the fleet
lock, of every box the console ever named on a record, with no
exception for a silent box; a box never named detaches at once.

Create-time labelling (Task 2) marks the box labelled before the record
write. movable refuses an HA record. fleets ls carries labels_paused and
a box's draining flag; the CLI adds `drain`, LABELS PAUSED and a
draining STATUS. docs/site/cli.md documents drain, the refusal, the
completion and detach after a drain, and revises the leaked-key advice
to drain first, then detach and rotate. FSK-C12 and FSK-C62 are struck
in the fleet secrets copy deck; their new text goes to Task 8's Luna
pass.

Census: claim-routes.txt, a refused fixture and a claimUnsupported entry
for the drain door, a read fixture and log probe for the worker, the
closed-door list (74), jobLabels and jobPassFuncs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev caccae9926537a680c9fd6169a3cfe1d86707bec parent 788df20
24 files changed, +1,555 −49
  • apimode.go +22 −0
  • approved_fleet_secrets_copy_test.go +4 −2
  • cmd/console/claimworkers_started_test.go +8 −1
  • cmd/console/main.go +5 −0
  • docs/site/cli.md +33 −2
  • docs/superpowers/plans/2026-10-29-fleet-secrets-key-copy.md +8 −2
  • fleets.go +59 −8
  • fleets_cli_test.go +54 −0
  • fleets_secrets_key_cli_test.go +1 −1
  • internal/console/apiinstances.go +11 −1
  • internal/console/authcli.go +1 −0
  • internal/console/claim_invariant_fixtures_test.go +10 −0
  • internal/console/claim_invariant_probes_worker_test.go +1 −0
  • internal/console/claim_invariant_test.go +2 −0
  • internal/console/claim_workers.go +1 −0
  • internal/console/fleetbox.go +64 −29
  • internal/console/fleetrelabel.go +570 −0
  • internal/console/fleetrelabel_test.go +589 −0
  • internal/console/fleets.go +103 −1
  • internal/console/jobs.go +1 −0
  • internal/console/jobs_test.go +1 −0
  • internal/console/svcroutes_test.go +3 −2
  • internal/console/testdata/claim-routes.txt +2 −0
  • internal/console/view.go +2 −0
diff --git a/apimode.go b/apimode.go
index 0f0d248bf..6edab210a 100644
--- a/apimode.go
+++ b/apimode.go
@@ -5053,6 +5053,9 @@ type apiFleetBox struct {
Label string `json:"label"`
Status string `json:"status"`
Tags string `json:"tags,omitempty"`
+ // Draining is present for a box `carlos fleets drain` has begun
+ // draining (managed fleets 1b).
+ Draining bool `json:"draining,omitempty"`
}
type apiFleetView struct {
@@ -5065,6 +5068,10 @@ type apiFleetView struct {
// count when nothing is stale.
SecretsKeyFP string `json:"secrets_key_fp,omitempty"`
StaleSecrets int `json:"stale_secrets,omitempty"`
+ // LabelsPaused is present while the console has stopped moving the
+ // fleet's instances between boxes because a box runs a release below
+ // the floor (managed fleets 1b, rule 8).
+ LabelsPaused bool `json:"labels_paused,omitempty"`
}
// fleetKeyStale is one app's line of the secrets key door's stale report:
@@ -5236,6 +5243,21 @@ func (s *apiSession) detachFleetBox(ctx context.Context, a apiAcct, fleet, label
return nil
}
+// drainFleetBox asks the console to move every instance off a box and give
+// it no new ones: `carlos fleets drain`. A refusal names the apps whose
+// instances have nowhere to go (handleAPIFleetDrainBox).
+func (s *apiSession) drainFleetBox(ctx context.Context, a apiAcct, fleet, label string) error {
+ status, body, err := s.postJSON(ctx,
+ fleetPath(a, "/"+url.PathEscape(fleet)+"/boxes/"+url.PathEscape(label)+"/drain"), struct{}{})
+ if err != nil {
+ return err
+ }
+ if status != http.StatusOK {
+ return apiErrorFromBody(status, body)
+ }
+ return nil
+}
+
// place asks the console to repoint where app's routes — and its
// already-provisioned instances — should run: `carlos apps place`. target ""
// clears placement back to platform-served/unconstrained; any other value
diff --git a/approved_fleet_secrets_copy_test.go b/approved_fleet_secrets_copy_test.go
index 2d4a9eb06..e99cf25df 100644
--- a/approved_fleet_secrets_copy_test.go
+++ b/approved_fleet_secrets_copy_test.go
@@ -57,10 +57,12 @@ var fleetSecretsCopyStatuses = []string{"pending", "approved", "struck"}
// row is approved. Task 3 built the door, BYO page and fleet page rows; Task 4 the CLI rows;
// Task 5 sealKeyFor's refusals and the config door's; Task 6a the store and
// email doors' keyless-fleet refusals; Task 6b the relay's; Task 7 the move refusal; Task 9 the REASON cells; Task 10 the docs.
+// FSK-C12 and FSK-C62 are struck and no longer built (managed fleets 1b
+// Task 6: the drain verb and drain-first leak advice replaced them).
var fleetSecretsCopyBuilt = []string{
"FSK-C01", "FSK-C02", "FSK-C03", "FSK-C04",
"FSK-C05", "FSK-C06", "FSK-C07", "FSK-C08",
- "FSK-C09", "FSK-C10", "FSK-C11", "FSK-C12",
+ "FSK-C09", "FSK-C10", "FSK-C11",
"FSK-C13", "FSK-C14", "FSK-C15", "FSK-C16",
"FSK-C17", "FSK-C18", "FSK-C19", "FSK-C20",
"FSK-C21", "FSK-C22", "FSK-C23", "FSK-C24",
@@ -72,7 +74,7 @@ var fleetSecretsCopyBuilt = []string{
"FSK-C45", "FSK-C46", "FSK-C47", "FSK-C48", "FSK-C49", "FSK-C50",
"FSK-C51", "FSK-C52", "FSK-C53", "FSK-C54", "FSK-C55",
"FSK-C56", "FSK-C57", "FSK-C58", "FSK-C59", "FSK-C60",
- "FSK-C61", "FSK-C62", "FSK-C63", "FSK-C64", "FSK-C65",
+ "FSK-C61", "FSK-C63", "FSK-C64", "FSK-C65",
"FSK-C66", "FSK-C67", "FSK-C68", "FSK-C69", "FSK-C70",
"FSK-C71", "FSK-C72",
}
diff --git a/cmd/console/claimworkers_started_test.go b/cmd/console/claimworkers_started_test.go
index 8e44fd76c..ee20d0aa4 100644
--- a/cmd/console/claimworkers_started_test.go
+++ b/cmd/console/claimworkers_started_test.go
@@ -27,9 +27,16 @@ func TestEveryRegisteredClaimWorkerIsStarted(t *testing.T) {
for _, m := range regexp.MustCompile(`RunClaimWorker\(context\.Background\(\), "([A-Za-z]+)"\)`).FindAllSubmatch(main, -1) {
started[string(m[1])] = true
}
+ names := map[string]bool{}
for _, m := range registered {
- if name := string(m[1]); !started[name] {
+ name := string(m[1])
+ names[name] = true
+ if !started[name] {
t.Errorf("claim worker %s is registered but serve never starts it", name)
}
}
+ // Managed fleets 1b, Task 6: the relabel worker is one of them.
+ if !names["FleetRelabel"] || !started["FleetRelabel"] {
+ t.Error("the FleetRelabel worker is not registered and started")
+ }
}
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 6a3ddddcd..be5b3eeb8 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -762,6 +762,11 @@ func serve() {
// Spec §5.7: after any roll, list possible placement discrepancies for
// operator review. Read-only; never blocks startup.
go srv.RunClaimWorker(context.Background(), "LogPlacementDiscrepancies")
+ // Managed fleets 1b (rules 2, 4, 5, 8): every 5 minutes, label existing
+ // fleet records to the box their binding names, move records off lost
+ // and draining boxes, and pause with an alert while a fleet box is below
+ // the label floor. Off on a host-claim console.
+ go srv.RunClaimWorker(context.Background(), "FleetRelabel")
addr := envOr("CONSOLE_ADDR", "127.0.0.1:8090")
ln, err := net.Listen("tcp", addr)
if err != nil {
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 7554e1071..afdfceb5e 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2151,7 +2151,38 @@ will only refuse the label. Put it straight into the box's credential store.
Rotation is not revocation. A fresh token refuses the box's next dial-in with
the old one, but it does not evict a channel the box is already holding. If a
credential may be compromised, `detach-box` is the command that actually
-stops it.
+stops it. A box that has run instances needs a drain first, as the next
+section says.
+
+On a fleet with two or more boxes, the console picks the box each instance
+runs on. To take a box out, drain it, then detach it:
+
+```sh
+carlos fleets drain acme pi-1
+carlos fleets detach-box acme pi-1
+```
+
+`drain` moves every instance on the box to the fleet's other boxes and gives
+the box no new ones. If any instance has nowhere to go, nothing changes and the
+command names its apps. That happens when no other box is ready for it, when
+the platform does not run its process (it has an upstream address, or never
+hibernates), or when the console has not placed it on a box yet. A placed
+instance is one that has woken on some box since it was created. The box keeps
+its access while its instances leave, so it can stop them and upload their
+last writes.
+
+`detach-box` waits for the box to say it is done. The console detaches a box
+that has run instances only when the box's newest report, sent after the drain
+began, shows no instances, no held leases and no failed final uploads. Until
+then the command refuses and says to drain first. A box that has gone silent
+stays attached: its instances still move to other boxes after 20 minutes, but
+it cannot be detached until it reports again. A box that has never run an
+instance detaches at once.
+
+In `carlos fleets ls`, a draining box shows `draining` in STATUS. LABELS
+PAUSED reads `yes` while a box of the fleet runs a release too old for the
+console to move instances between boxes. The console stops moving them and
+logs an alert until that box is updated.
An app on a fleet cannot hold a secret until the fleet has its own secrets key. The key is a pair. The private half stays on your fleet's boxes and the platform never sees it. The public half goes to the console, which seals every secret and credential for the fleet's apps to it.
@@ -2165,7 +2196,7 @@ If apps on the fleet already hold sealed values, the command lists them. They we
To check that a box holds the registered key, run `carlos secrets fingerprint` on the box. Its answer should start with the characters in the SECRETS KEY column of `carlos fleets ls`, which shows the first 12 after `sha256:`.
-You can replace a fleet's key only while none of its apps holds a sealed value. Unset those apps' secrets, register the new key, set the secrets again and rotate the credentials the console minted. If a key may have leaked, first run `carlos fleets detach-box <fleet> <label>`. A detached box stops reading the platform's store.
+You can replace a fleet's key only while none of its apps holds a sealed value. Unset those apps' secrets, register the new key, set the secrets again and rotate the credentials the console minted. If a key may have leaked, take the box off the fleet first. A box that holds nothing can be detached at once with `carlos fleets detach-box <fleet> <label>`. Otherwise drain it with `carlos fleets drain <fleet> <label>`, then detach it once it is done, then rotate. The drain needs the box's current token: rotating first would cut the box off before it sees its instances leave. A detached box stops reading the platform's store.
### carlos services
diff --git a/docs/superpowers/plans/2026-10-29-fleet-secrets-key-copy.md b/docs/superpowers/plans/2026-10-29-fleet-secrets-key-copy.md
index 543faa151..80c6ab921 100644
--- a/docs/superpowers/plans/2026-10-29-fleet-secrets-key-copy.md
+++ b/docs/superpowers/plans/2026-10-29-fleet-secrets-key-copy.md
@@ -11,6 +11,12 @@ Every row is `approved`: by delegation, a Luna copy pass (2026-10-29, `luna-1.md
writes a row that is not `approved`, and each adds its ids to
`fleetSecretsCopyBuilt` in the commit that writes them.
+FSK-C12 and FSK-C62 are struck (2026-10-31, managed fleets 1b Task 6): the
+usage line now names `drain`, and the leaked-key advice drains a box that
+holds instances before it is detached. Their new text is in the managed
+fleets 1b copy pass (plan `2026-10-30-managed-fleets-1b-box-per-instance.md`,
+Task 8).
+
The rules:
- The file cell is the exact repo-relative file the owning task writes the
@@ -67,7 +73,7 @@ console-minted names on their own line.
| id | file | text | status |
|---|---|---|---|
-| FSK-C12 | fleets.go (a fragment of fleetsUsage, the first line; Task 4) | usage: carlos fleets <create\|add-box\|rotate-token\|tag-box\|detach-box\|secrets-key\|ls> [flags] | approved |
+| FSK-C12 | fleets.go (a fragment of fleetsUsage, the first line; Task 4) | usage: carlos fleets <create\|add-box\|rotate-token\|tag-box\|detach-box\|secrets-key\|ls> [flags] | struck |
| FSK-C13 | fleets.go (a fragment of fleetsUsage, the secrets-key entry; Task 4) | secrets-key [--account <sqid\|name>] [--file <path>] <fleet> [<pubkey>]\n register the public half of the fleet's secrets key. every secret\n and credential for an app placed on the fleet is sealed to it.\n keep the private half in each box's host.env as CARLOS_SECRETS_KEY\n and nowhere else. make a pair with "carlos secrets genkey". only an\n account owner can run this. --file reads a CARLOS_SECRETS_PUBKEY=\n line or a bare key. | approved |
| FSK-C14 | fleets.go (a fragment of fleetsUsage, the ls entry; Task 4) | list every fleet the account owns, with its secrets key fingerprint and each box's label,\n status and tags. STALE counts the sealed values its boxes cannot\n open yet. | approved |
| FSK-C15 | fleets.go (Task 4) | registered the secrets key for <fleet>. fingerprint <fp> | approved |
@@ -151,7 +157,7 @@ The fleets page of the plan is the `carlos fleets` section of `docs/site/cli.md`
| FSK-C59 | docs/site/cli.md (carlos fleets; Task 10) | A key belongs to one fleet only, and it cannot be the platform's own. Registering the same key on the same fleet again changes nothing. | approved |
| FSK-C60 | docs/site/cli.md (carlos fleets; Task 10) | If apps on the fleet already hold sealed values, the command lists them. They were sealed to another key, so the fleet's boxes cannot open them. Set each secret again with `carlos secrets set`, and run `carlos store rotate` or `carlos email rotate` for a credential the console minted. The STALE column of `carlos fleets ls` counts what is left. | approved |
| FSK-C61 | docs/site/cli.md (carlos fleets; Task 10) | To check that a box holds the registered key, run `carlos secrets fingerprint` on the box. Its answer should start with the characters in the SECRETS KEY column of `carlos fleets ls`, which shows the first 12 after `sha256:`. | approved |
-| FSK-C62 | docs/site/cli.md (carlos fleets; Task 10) | You can replace a fleet's key only while none of its apps holds a sealed value. Unset those apps' secrets, register the new key, set the secrets again and rotate the credentials the console minted. If a key may have leaked, first run `carlos fleets detach-box <fleet> <label>`. A detached box stops reading the platform's store. | approved |
+| FSK-C62 | docs/site/cli.md (carlos fleets; Task 10) | You can replace a fleet's key only while none of its apps holds a sealed value. Unset those apps' secrets, register the new key, set the secrets again and rotate the credentials the console minted. If a key may have leaked, first run `carlos fleets detach-box <fleet> <label>`. A detached box stops reading the platform's store. | struck |
| FSK-C63 | docs/site/cli.md (carlos apps; Task 10) | `carlos apps place` refuses an app whose sealed values were sealed to a different key from the target's, and `carlos apps create --place` does the same for an app that already has config. The message lists the values. Unset them, place the app, then set them again and rotate any credential the console minted. | approved |
| FSK-C64 | docs/site/cli.md (carlos secrets; Task 10) | An app placed on a fleet is sealed to the fleet's key, which `carlos secrets set` takes from the console. Leave `CARLOS_SECRETS_PUBKEY` unset in your terminal for it, and use a `carlos` CLI that knows about fleet keys, because the console refuses a secret from an older one. | approved |
| FSK-C65 | docs/site/cli.md (carlos secrets; Task 10) | In direct-bucket mode, `carlos secrets set` refuses for any account that owns a fleet, because it cannot tell which key an app needs. Unset `CARLOS_DEPLOYMENT_BUCKET` and `CARLOS_DEPLOYMENT_DIR`, sign in with `carlos auth login`, and run `carlos secrets set` through the console. | approved |
diff --git a/fleets.go b/fleets.go
index d5e62d552..c83618ac4 100644
--- a/fleets.go
+++ b/fleets.go
@@ -31,7 +31,7 @@ import (
"github.com/carlosframework/platform/internal/registry"
)
-const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|detach-box|secrets-key|ls> [flags]
+const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|drain|detach-box|secrets-key|ls> [flags]
create --bucket <bucket> [--account <sqid|name>] <name>
mint an account-owned fleet: a named group of remote boxes
@@ -70,11 +70,19 @@ const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|d
--tags "" clears every tag. This is a full replace, not a
merge — the tags sent are exactly the tags that land.
+ drain [--account <sqid|name>] <fleet> <label>
+ move every instance on the box to the fleet's other boxes
+ and give it no new ones. if any instance has nowhere to go,
+ nothing changes and the apps are named. the box keeps its
+ access while its instances leave. detach it with
+ detach-box once it reports it holds nothing.
+
detach-box [--account <sqid|name>] <fleet> <label>
the hard revocation rotate-token is not: flips the box to
"detached", which refuses its next dial-in AND closes any
- channel it already holds. This is what a compromised box
- needs.
+ channel it already holds. a box that ever ran instances the
+ console placed on it is detached only after a drain, once
+ the box reports it holds nothing.
secrets-key [--account <sqid|name>] [--file <path>] <fleet> [<pubkey>]
register the public half of the fleet's secrets key. every secret
@@ -87,7 +95,8 @@ const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|d
ls [--account <sqid|name>]
list every fleet the account owns, with its secrets key fingerprint and each box's label,
status and tags. STALE counts the sealed values its boxes cannot
- open yet.
+ open yet. LABELS PAUSED is yes while a box runs a release too old
+ for the console to move instances between boxes.
--account <sqid|name> account the fleet belongs to (default: your only
account, or the configured/chosen one) —
@@ -117,6 +126,8 @@ func RunFleets(args []string) {
runFleetsRotateToken(args[1:])
case "tag-box":
runFleetsTagBox(args[1:])
+ case "drain":
+ runFleetsDrain(args[1:])
case "detach-box":
runFleetsDetachBox(args[1:])
case "secrets-key":
@@ -337,6 +348,39 @@ func runFleetsTagBox(args []string) {
}
}
+// runFleetsDrain is `carlos fleets drain`, the first of the two steps that
+// take a box out of a fleet (managed fleets 1b, rule 5): the console moves
+// every instance on the box to another box, or refuses naming the apps
+// with nowhere to go. detach-box is the second step.
+func runFleetsDrain(args []string) {
+ fs := flag.NewFlagSet("fleets drain", flag.ExitOnError)
+ acctRaw := fs.String("account", "", "account (sqid or name) the fleet 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")
+ consoleFlag := consoleOption(fs, "console to drain through (default: the only logged-in one)")
+ const drainUsage = "usage: carlos fleets drain [--account <sqid|name>] [--account-id <sqid>] [--console <origin>] <fleet> <label>"
+ fs.Usage = flagUsage(fs, drainUsage)
+ fs.Parse(args)
+ if fs.NArg() != 2 {
+ log.Fatal(drainUsage)
+ }
+ fleet, label := strings.TrimSpace(fs.Arg(0)), strings.TrimSpace(fs.Arg(1))
+ if err := validFleetName(fleet); err != nil {
+ log.Fatalf("fleets drain: %v", err)
+ }
+ if err := validBoxLabel(label); err != nil {
+ log.Fatalf("fleets drain: %v", err)
+ }
+
+ sess := fleetsSignedInSession(*consoleFlag)
+ fmt.Fprintf(stdout, "using %s as %s\n", sess.console, sess.address)
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ if err := sess.drainFleetBox(context.Background(), acct, fleet, label); err != nil {
+ log.Fatalf("fleets drain: %v", err)
+ }
+ fmt.Fprintf(stdout, "draining %s/%s. its instances are moving to the fleet's other boxes\n", fleet, label)
+ fmt.Fprintf(stdout, " when the box reports it holds nothing, detach it: carlos fleets detach-box %s %s\n", fleet, label)
+}
+
func runFleetsDetachBox(args []string) {
fs := flag.NewFlagSet("fleets detach-box", flag.ExitOnError)
acctRaw := fs.String("account", "", "account (sqid or name) the fleet belongs to (default: your only account, or the configured/chosen one)")
@@ -385,17 +429,20 @@ func runFleetsList(args []string) {
return
}
w := tabwriter.NewWriter(stdout, 0, 4, 2, ' ', 0)
- fmt.Fprintln(w, "FLEET\tBUCKET\tSECRETS KEY\tSTALE\tBOX\tSTATUS\tTAGS")
+ fmt.Fprintln(w, "FLEET\tBUCKET\tSECRETS KEY\tSTALE\tLABELS PAUSED\tBOX\tSTATUS\tTAGS")
for _, f := range fleets {
- key, stale := "-", "-"
+ key, stale, paused := "-", "-", "-"
if hex := strings.TrimPrefix(f.SecretsKeyFP, "sha256:"); hex != "" {
key = hex[:min(len(hex), 12)]
}
if f.StaleSecrets > 0 {
stale = strconv.Itoa(f.StaleSecrets)
}
+ if f.LabelsPaused {
+ paused = "yes"
+ }
if len(f.Boxes) == 0 {
- fmt.Fprintf(w, "%s\t%s\t%s\t%s\t-\t-\t-\n", f.Name, f.Bucket, key, stale)
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t-\t-\t-\n", f.Name, f.Bucket, key, stale, paused)
continue
}
for _, b := range f.Boxes {
@@ -403,7 +450,11 @@ func runFleetsList(args []string) {
if tags == "" {
tags = "-"
}
- fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", f.Name, f.Bucket, key, stale, b.Label, b.Status, tags)
+ st := b.Status
+ if b.Draining && st == "active" {
+ st = "draining"
+ }
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", f.Name, f.Bucket, key, stale, paused, b.Label, st, tags)
}
}
w.Flush()
diff --git a/fleets_cli_test.go b/fleets_cli_test.go
index 273965c81..a259d72ed 100644
--- a/fleets_cli_test.go
+++ b/fleets_cli_test.go
@@ -28,6 +28,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "slices"
"strings"
"sync/atomic"
"testing"
@@ -337,6 +338,7 @@ type fakeFleetsConsole struct {
lastCreatePlace atomic.Value // string
lastPlaceTarget atomic.Value // string
lastDetachPath atomic.Value // string
+ lastDrainPath atomic.Value // string
lastTagPath atomic.Value // string
lastTagBody atomic.Value // string
}
@@ -361,6 +363,9 @@ func newFakeFleetsConsole(t *testing.T) *fakeFleetsConsole {
{"label": "pi-1", "status": "active", "tags": "office,free"},
{"label": "pi-2", "status": "detached"},
}},
+ {"name": "pi", "bucket": "pi-data", "labels_paused": true, "boxes": []map[string]any{
+ {"label": "pi-3", "status": "active", "draining": true},
+ }},
},
})
})
@@ -380,6 +385,10 @@ func newFakeFleetsConsole(t *testing.T) *fakeFleetsConsole {
fc.lastDetachPath.Store(r.URL.Path)
json.NewEncoder(w).Encode(map[string]any{})
})
+ mux.HandleFunc("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/drain", func(w http.ResponseWriter, r *http.Request) {
+ fc.lastDrainPath.Store(r.URL.Path)
+ json.NewEncoder(w).Encode(map[string]any{})
+ })
mux.HandleFunc("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags", func(w http.ResponseWriter, r *http.Request) {
var req struct{ Tags string }
json.NewDecoder(r.Body).Decode(&req)
@@ -542,6 +551,51 @@ func TestRunFleetsDetachBoxHitsRightPath(t *testing.T) {
}
}
+// TestRunFleetsDrainHitsRightPath: `carlos fleets drain` reaches the drain
+// door and says what comes next (managed fleets 1b, rule 5).
+func TestRunFleetsDrainHitsRightPath(t *testing.T) {
+ fc := fleetsCLIFixture(t)
+ buf := captureStdout(t)
+
+ RunFleets([]string{"drain", "-account", "bab", "acme", "pi-1"})
+
+ if got := fc.lastDrainPath.Load(); got != "/api/cli/fleets/bab/acme/boxes/pi-1/drain" {
+ t.Fatalf("drain path = %v, want the labelled drain door", got)
+ }
+ out := buf.String()
+ if !strings.Contains(out, "draining acme/pi-1") || !strings.Contains(out, "carlos fleets detach-box acme pi-1") {
+ t.Fatalf("stdout = %q, want the drain confirmed and the detach step named", out)
+ }
+}
+
+// TestRunFleetsListShowsLabelsPausedAndDraining: the LABELS PAUSED column
+// reads yes for a paused fleet and - otherwise, and a draining box's status
+// reads draining.
+func TestRunFleetsListShowsLabelsPausedAndDraining(t *testing.T) {
+ fleetsCLIFixture(t)
+ buf := captureStdout(t)
+
+ RunFleets([]string{"ls", "-account", "bab"})
+
+ out := buf.String()
+ if !strings.Contains(out, "LABELS PAUSED") {
+ t.Fatalf("fleets ls has no LABELS PAUSED column:\n%s", out)
+ }
+ for _, line := range strings.Split(out, "\n") {
+ f := strings.Fields(line)
+ switch {
+ case strings.Contains(line, "pi-3"):
+ if !slices.Contains(f, "yes") || !slices.Contains(f, "draining") {
+ t.Fatalf("pi-3 row = %q, want labels paused yes and status draining", line)
+ }
+ case strings.Contains(line, "pi-1"):
+ if slices.Contains(f, "yes") {
+ t.Fatalf("pi-1 row = %q, want labels not paused", line)
+ }
+ }
+ }
+}
+
// TestRunFleetsListPrintsEveryBox: `carlos fleets ls` prints one row per
// box, including a detached one, from the fake console's fixed listing —
// and a TAGS column: the tagged box's tags verbatim, the untagged box's "-".
diff --git a/fleets_secrets_key_cli_test.go b/fleets_secrets_key_cli_test.go
index fba190c3b..f3edff3c8 100644
--- a/fleets_secrets_key_cli_test.go
+++ b/fleets_secrets_key_cli_test.go
@@ -249,7 +249,7 @@ func TestFleetsLsShowsSecretsKey(t *testing.T) {
}
out := ls()
- if h := strings.Fields(out[strings.Index(out, "FLEET"):strings.Index(out, "\n"+row(out, "home")[0])]); strings.Join(h, " ") != "FLEET BUCKET SECRETS KEY STALE BOX STATUS TAGS" {
+ if h := strings.Fields(out[strings.Index(out, "FLEET"):strings.Index(out, "\n"+row(out, "home")[0])]); strings.Join(h, " ") != "FLEET BUCKET SECRETS KEY STALE LABELS PAUSED BOX STATUS TAGS" {
t.Fatalf("header = %q", h)
}
// No key: both columns read "-".
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 02c3e06a4..fe9ebf7fe 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -2312,9 +2312,19 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// record the platform cannot move (rule 11) are left unlabelled. No box
// to choose leaves it unlabelled too; a rootfs create never gets here
// without one (rootfsChosenBoxRefusal).
+ //
+ // The box is marked labelled in the registry first (Task 6): from then
+ // on its detach waits for the drain rule. A mark that fails leaves the
+ // record unlabelled, as on main.
if fleetActive != nil && fleetLabelsRecord(rec) && movable(rec) {
if box := fleetActive.chooseDestination(rec.Runtime == provision.RuntimeRootfsV1, ""); box != "" {
- rec.FleetBox, rec.FleetBoxAt = box, time.Now().UTC().Format(time.RFC3339Nano)
+ fleet, _ := registry.FleetPlacement(placed)
+ now := time.Now()
+ if err := reg.MarkFleetBoxLabelled(fleet, box, now.UnixNano()); err != nil {
+ log.Printf("console: api instances create %s/%s/%s: mark %s/%s labelled: %v; created unlabelled", acct.Sqid, app, host, fleet, box, err)
+ } else {
+ rec.FleetBox, rec.FleetBoxAt = box, now.UTC().Format(time.RFC3339Nano)
+ }
} else {
log.Printf("console: api instances create %s/%s/%s: fleet %s has no box to label it to; created unlabelled", acct.Sqid, app, host, placed)
}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index ea30fe561..8ae5ecac8 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -948,6 +948,7 @@ func (s *Server) registerCLIRoutes() {
s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes", svcrole.Set{}, s.handleAPIFleetAddBox)
s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate", svcrole.Set{}, s.handleAPIFleetRotateBox)
s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach", svcrole.Set{}, s.handleAPIFleetDetachBox)
+ s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/drain", svcrole.Set{}, s.handleAPIFleetDrainBox)
s.cliRoute("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags", svcrole.Set{}, s.handleAPIFleetTagBox)
// The fleet's secrets key (fleetsecretskey.go): whoever sets it decides
// who can read the fleet's future secrets, so the zero Set here too, and
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 03b99df60..d45c1bd05 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1374,6 +1374,15 @@ var claimFixtures = map[string]claimFixture{
"route POST /api/cli/fleets/{account}/new": claimNonApp("creates a customer fleet in the registry"),
"route POST /api/cli/fleets/{account}/{fleet}/boxes": claimNonApp("enrolls a fleet box"),
"route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach": claimNonApp("detaches a fleet box"),
+ // The drain relabels instance records (managed fleets 1b, rule 5), and
+ // no claim operation gates that: a host-claim console refuses it.
+ "route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/drain": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/titogo"),
+ setup: func(t *testing.T, cx *claimCase) { cx.fleetBoxWorld(t) },
+ do: claimRefusedAPI(http.MethodPost, "/api/cli/fleets/bab/pi/boxes/pi-1/drain", `{}`),
+ status: http.StatusConflict,
+ msg: claimFleetDrainUnsupportedMsg,
+ }},
"route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate": claimNonApp("rotates a fleet box's credential"),
"route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags": claimNonApp("tags a fleet box"),
"route PUT /api/cli/fleets/{account}/{fleet}/secrets-key": claimNonApp("registers a fleet's secrets key: the registry row and an append to the fleet owner record; names no app"),
@@ -2164,6 +2173,7 @@ var claimFixtures = map[string]claimFixture{
// ---- workers ----
"worker LogPlacementDiscrepancies": claimRead("logs region drift between the registry and instance records; writes nothing"),
+ "worker FleetRelabel": claimRead("off on a host-claim console, where no claim operation gates a relabel: it logs that and writes nothing"),
"worker PublishMovesConsole": claimNonApp("the moves console record (control/moves-console.json): the platform's moves protocol and key fingerprint; no app, and nothing with the moves switch off and no secrets key"),
"worker ReportApexSquats": claimRead("logs apex squats found in the registry; writes nothing"),
"worker StartRunSweep": claimRead("off on a host-claim console, where every run route refuses: it logs that and writes nothing"),
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go
index 9fc914ba0..6bc14d785 100644
--- a/internal/console/claim_invariant_probes_worker_test.go
+++ b/internal/console/claim_invariant_probes_worker_test.go
@@ -79,6 +79,7 @@ var claimWorkerProbes = map[string]claimProbe{
App: "kass", Account: "bab", Addr: "127.0.0.1:9301"})
}, "apex squat", "titogo.bab.oncarlos.com"),
"worker StartRunSweep": claimLogWorkerProbe("StartRunSweep", nil, "run sweep", "host-claim console"),
+ "worker FleetRelabel": claimLogWorkerProbe("FleetRelabel", nil, "fleet relabel", "host-claim console"),
"worker StartSeedsPass": claimLogWorkerProbe("StartSeedsPass", nil, "seeds pass", "host-claim console"),
"worker StartLifetimesCutoverWatch": claimLogWorkerProbe("StartLifetimesCutoverWatch", nil, "lifetimes cutover watch", "host-claim console"),
"worker StartLifetimeRecoveryPass": claimLogWorkerProbe("StartLifetimeRecoveryPass", nil, "lifetime recovery pass", "host-claim console"),
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index cb7beb8a6..f54ea9c6f 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -123,6 +123,8 @@ var claimUnsupported = map[string]string{
"both doors refuse after their caller gates and before they read or write anything",
placementsHostClaimMsg: "a regional claim is written by SetClaimPlacements, which no host-claim operation gates (#447 plan note 9); " +
"the placements PUT refuses after its caller gates and before it reads or writes anything",
+ claimFleetDrainUnsupportedMsg: "a drain relabels the box's instance records (managed fleets 1b, rule 5), which no claim operation gates; " +
+ "the drain door refuses after its caller gates and before it reads the fleet or writes anything",
seedClaimConsoleRefusal().Msg: "seeded instances need nested boxes, and the claim-armed path waits for #250 (seeded-instances spec §3.4); " +
"every import door refuses before it reads the record, and the legacy route assignment before it reads anything",
}
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go
index bee9c5330..07dc0dcca 100644
--- a/internal/console/claim_workers.go
+++ b/internal/console/claim_workers.go
@@ -30,6 +30,7 @@ func (s *Server) registerClaimWorkers() {
"ReportApexSquats": s.ReportApexSquats,
"LogPlacementDiscrepancies": s.LogPlacementDiscrepancies,
"PublishMovesConsole": s.publishMovesConsoleWorker,
+ "FleetRelabel": s.StartFleetRelabel,
} {
s.jobs.declare(name)
e := claimEntry{Kind: "worker", Pattern: name, Handler: claimHandlerName(h)}
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go
index 33a7a5e4b..31d77d934 100644
--- a/internal/console/fleetbox.go
+++ b/internal/console/fleetbox.go
@@ -42,22 +42,74 @@ import (
// at or above release.FleetBoxLabelFloor, from a complete listing, and
// every active box of the fleet has a heartbeat (gates c and d). Unmovable: some record on the fleet fails movable (rule 11).
// Load counts the fleet's records by the box they are labelled to. Static
-// records count toward neither (fleetLabelsRecord).
+// records count toward neither (fleetLabelsRecord). Records is the
+// inventory the view was built from (every record placed on the fleet,
+// static ones included), read only when the fleet has two or more active
+// boxes; the relabel worker and the drain act on it.
type fleetView struct {
Boxes []fleetBoxView
Active, HasSidecars, DeploymentCurrent bool
Unmovable bool
Load map[string]int
+ Records []provision.Record
}
// fleetBoxView is one active box of the fleet (registry status "active"),
// with what its newest heartbeat says. A box with no heartbeat is not
-// fresh and has a zero LastSeen. Draining is false until the drain column
-// exists (Task 6).
+// fresh and has a zero LastSeen and an empty Release (the release that
+// heartbeat names). Draining and DrainingSince are the registry's drain
+// mark (Task 6), Labelled whether the console ever named the box on a
+// record.
type fleetBoxView struct {
Label string
Fresh, Draining, RootfsReady, AtRootfsFloor, AtLabelFloor bool
- LastSeen time.Time
+ Labelled bool
+ LastSeen, DrainingSince time.Time
+ Release string
+}
+
+// fleetBoxViewOf is an active registry box before its heartbeat is read.
+func fleetBoxViewOf(b registry.FleetBox) fleetBoxView {
+ v := fleetBoxView{Label: b.Label, Labelled: b.LabelledAt != 0}
+ if b.DrainingSince != 0 {
+ v.Draining, v.DrainingSince = true, time.Unix(0, b.DrainingSince)
+ }
+ return v
+}
+
+// joinBeats fills each box's heartbeat facts from hbs, as of now, and
+// reports whether some box has no heartbeat at all.
+func joinBeats(boxes []fleetBoxView, hbs []status.Box, now time.Time) (unheard bool) {
+ beat := make(map[string]status.Box, len(hbs))
+ for _, b := range hbs {
+ beat[b.Label] = b
+ }
+ for i := range boxes {
+ b, ok := beat[boxes[i].Label]
+ if !ok {
+ unheard = true
+ continue
+ }
+ boxes[i].Fresh = !status.BoxStale(b, now, status.SnapshotPeriod)
+ boxes[i].RootfsReady = boxRootfsReady(b)
+ boxes[i].AtRootfsFloor = boxAtRootfsFloor(b)
+ boxes[i].AtLabelFloor = boxAtLabelFloor(b)
+ boxes[i].LastSeen = b.GeneratedAt
+ if b.Metrics != nil {
+ boxes[i].Release = b.Metrics.Release
+ }
+ }
+ return unheard
+}
+
+// destinationFor is chooseDestination's test of one box: fresh, not
+// draining, at the label floor, and, for a rootfs record, rootfs-ready at
+// the rootfs floor.
+func (b fleetBoxView) destinationFor(rootfs bool) bool {
+ if !b.Fresh || b.Draining || !b.AtLabelFloor {
+ return false
+ }
+ return !rootfs || (b.RootfsReady && b.AtRootfsFloor)
}
// labelActive is the activation gate: the console labels this fleet's
@@ -76,10 +128,7 @@ func (v fleetView) labelActive() bool {
func (v fleetView) chooseDestination(rootfs bool, exclude string) string {
best, bestLoad := "", 0
for _, b := range v.Boxes {
- if b.Label == exclude || !b.Fresh || b.Draining || !b.AtLabelFloor {
- continue
- }
- if rootfs && !(b.RootfsReady && b.AtRootfsFloor) {
+ if b.Label == exclude || !b.destinationFor(rootfs) {
continue
}
load := v.Load[b.Label]
@@ -102,9 +151,11 @@ func fleetLabelsRecord(rec provision.Record) bool {
// movable reports whether rec is a process the platform runs and can stop
// on one box and start on another by relabelling: no upstream address the
// platform does not manage (Addr, Addrs), and either a rootfs runtime or a
-// hibernation that is not switched off.
+// hibernation that is not switched off. An HA record is never movable: HA
+// hosts are outside 1b's move machinery (controller ruling 3, Task 6), so a
+// fleet holding one is never labelled and a drain refuses it.
func movable(rec provision.Record) bool {
- if rec.Addr != "" || len(rec.Addrs) > 0 {
+ if rec.Addr != "" || len(rec.Addrs) > 0 || rec.HA {
return false
}
return rec.Runtime == provision.RuntimeRootfsV1 || rec.Hibernate == nil || *rec.Hibernate
@@ -211,7 +262,7 @@ func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, er
}
for _, b := range regBoxes {
if b.Status == "active" {
- v.Boxes = append(v.Boxes, fleetBoxView{Label: b.Label})
+ v.Boxes = append(v.Boxes, fleetBoxViewOf(b))
}
}
slices.SortFunc(v.Boxes, func(a, b fleetBoxView) int { return strings.Compare(a.Label, b.Label) })
@@ -231,27 +282,10 @@ func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, er
log.Printf("console: fleet %s view: heartbeats: complete %v, %v", fleet, hbComplete, err)
whole = false
}
- beat := make(map[string]status.Box, len(hbs))
- for _, b := range hbs {
- beat[b.Label] = b
- }
- now := time.Now()
// Every active box must have said which release it runs: one with no
// heartbeat at all (attached and never reported, or silent past the
// listing's horizon) is a version the gate cannot read.
- unheard := false
- for i := range v.Boxes {
- b, ok := beat[v.Boxes[i].Label]
- if !ok {
- unheard = true
- continue
- }
- v.Boxes[i].Fresh = !status.BoxStale(b, now, status.SnapshotPeriod)
- v.Boxes[i].RootfsReady = boxRootfsReady(b)
- v.Boxes[i].AtRootfsFloor = boxAtRootfsFloor(b)
- v.Boxes[i].AtLabelFloor = boxAtLabelFloor(b)
- v.Boxes[i].LastSeen = b.GeneratedAt
- }
+ unheard := joinBeats(v.Boxes, hbs, time.Now())
deploy, deployComplete, err := s.loadDeploymentBoxesComplete(ctx)
if err != nil || !deployComplete {
@@ -269,6 +303,7 @@ func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, er
log.Printf("console: fleet %s view: inventory: complete %v, %v", fleet, invComplete, err)
whole = false
}
+ v.Records = recs
for _, rec := range recs {
if !fleetLabelsRecord(rec) {
continue
diff --git a/internal/console/fleetrelabel.go b/internal/console/fleetrelabel.go
new file mode 100644
index 000000000..fcdb83ccf
--- /dev/null
+++ b/internal/console/fleetrelabel.go
@@ -0,0 +1,570 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// Managed fleets 1b, Task 6 (spec "1b addendum", rules 2, 4, 5, 8, 11).
+//
+// The relabel worker, FleetRelabel, runs one pass every five minutes. Per
+// fleet, under the fleet's lock and from one loadFleetView:
+//
+// - When the fleet has labels and one of its boxes reports a release
+// below release.FleetBoxLabelFloor, the pass logs an ERROR naming the
+// fleet, the box and the release and does nothing else for the fleet
+// (rule 8: paused). `carlos fleets ls` shows LABELS PAUSED from the
+// same test, labelsPausedBy.
+// - Otherwise, when the view was read whole: a record labelled to a box
+// that is draining, lost (no heartbeat for fleetBoxLostAfter) or no
+// longer an active box of the fleet moves to chooseDestination(rootfs,
+// its box) (rules 4 and 5). Moving needs no open activation gate
+// (controller ruling 1).
+// - And when the activation gate is open (labelActive): an unlabelled
+// record is labelled to the box its binding
+// (fleets/<f>/bindings/<host>.json) names, when that binding was
+// written for this record and the box is a valid destination. A record
+// with no such binding stays unlabelled: the console never picks a box
+// for an existing record, since a box that never served it would start
+// it empty (rule 6, controller ruling 5).
+//
+// Every read comes first and any read that is not whole means no write for
+// the fleet. Every write is SetRecordFleetBox, conditional on the region,
+// label and creation time the pass read; a record that changed since
+// (ErrFleetBoxMoved) or whose import has not committed
+// (ErrFleetBoxImportInFlight) is left for a later pass. Before naming a box
+// on a record, the pass marks the box as labelled in the registry, which
+// is what makes the detach doors ask the drain rule of it.
+//
+// The drain (`carlos fleets drain`, drainBox) moves every record the box
+// runs or refuses up front, naming the apps, and marks the box draining in
+// the registry (draining_since). A draining box stays active, so it keeps
+// its fleet access and can see its records leave. The worker finishes any
+// move the drain could not make at once. The detach doors refuse a box the
+// console ever named on a record until drainDone says, from the box's own
+// newest heartbeat, that it holds nothing (rule 5, the drain rule).
+
+// fleetRelabelInterval is the worker's period.
+const fleetRelabelInterval = 5 * time.Minute
+
+// fleetBoxLostAfter is how long a box may go without a heartbeat before
+// its records move (rule 4): the lease's lifetime, past which a box that is
+// only partitioned has lost its leases too, plus a margin.
+const fleetBoxLostAfter = lease.LeaseTTL + 5*time.Minute
+
+// StartFleetRelabel runs fleetRelabelPass every fleetRelabelInterval. It is
+// off on a host-claim console, where no claim operation gates the record
+// writes it makes.
+func (s *Server) StartFleetRelabel(ctx context.Context) {
+ if s.cfg.HostClaim {
+ log.Printf("console: fleet relabel: off on a host-claim console, where no claim operation gates a relabel")
+ return
+ }
+ lifetimesWorker(ctx, fleetRelabelInterval, func(ctx context.Context) {
+ // Each pass is a unit of record work (lifetimes_cutover.go).
+ s.lifetimesIteration(ctx, "fleet relabel", true, false, func(ctx context.Context) {
+ _ = s.jobs.Run(ctx, "FleetRelabel", s.fleetRelabelPass)
+ })
+ })
+}
+
+// fleetRelabelPass is one pass over every fleet. A fleet whose view cannot
+// be read is logged and skipped; the others still run. The deployment's
+// heartbeat listing is read once for the whole pass.
+func (s *Server) fleetRelabelPass(ctx context.Context) error {
+ if s.cfg.Releases == nil || s.cfg.Registry == "" {
+ return nil
+ }
+ _, fleets, err := s.systemFleets()
+ if err != nil {
+ return err
+ }
+ ctx = withWriteMemo(ctx)
+ for _, f := range fleets {
+ unlock := s.lockFleet(f.Name)
+ v, err := s.loadFleetView(ctx, f.Name)
+ if err != nil {
+ log.Printf("console: fleet relabel %s: view: %v", f.Name, err)
+ jobFailed(ctx, err)
+ unlock()
+ continue
+ }
+ if _, err := s.relabelFleet(ctx, f.Name, v); err != nil {
+ log.Printf("console: fleet relabel %s: %v", f.Name, err)
+ jobFailed(ctx, err)
+ }
+ unlock()
+ }
+ return nil
+}
+
+// relabel is one planned label write: rec to box to, and why.
+type relabel struct {
+ rec provision.Record
+ to string
+ reason string
+}
+
+// relabelFleet is one fleet's pass, from v (read under the fleet's lock by
+// the caller). moved counts the records written. err is a read that was
+// not whole, which writes nothing; a write that fails is logged and the
+// others still run.
+func (s *Server) relabelFleet(ctx context.Context, fleet string, v fleetView) (moved int, err error) {
+ if box, rel := v.labelsPausedBy(); box != "" {
+ log.Printf("console: ERROR fleet %s: box %s reports release %s, below the label floor %s: relabelling is paused until it is updated",
+ fleet, box, releaseOrUnknown(rel), release.FleetBoxLabelFloor)
+ return 0, nil
+ }
+ if !v.Active {
+ return 0, nil
+ }
+ now := time.Now()
+ var plan []relabel
+ if v.labelActive() {
+ first, err := s.planFirstLabelling(ctx, fleet, v)
+ if err != nil {
+ return 0, err
+ }
+ for _, p := range first {
+ v.Load[p.to]++
+ }
+ plan = append(plan, first...)
+ }
+ for _, rec := range v.Records {
+ if !fleetLabelsRecord(rec) || rec.FleetBox == "" {
+ continue
+ }
+ reason := v.boxGone(rec.FleetBox, now)
+ if reason == "" {
+ continue
+ }
+ if !movable(rec) {
+ log.Printf("console: fleet relabel %s: %s on %s (%s) is not a record the platform can move; left", fleet, rec.Host, rec.FleetBox, reason)
+ continue
+ }
+ to := v.chooseDestination(rec.Runtime == provision.RuntimeRootfsV1, rec.FleetBox)
+ if to == "" {
+ log.Printf("console: fleet relabel %s: %s on %s (%s) has no box to move to; left", fleet, rec.Host, rec.FleetBox, reason)
+ continue
+ }
+ v.Load[to]++
+ v.Load[rec.FleetBox]--
+ plan = append(plan, relabel{rec: rec, to: to, reason: reason})
+ }
+ return s.writeRelabels(ctx, fleet, plan, now), nil
+}
+
+// planFirstLabelling is the first labelling's plan: each unlabelled record
+// whose binding names a valid destination, labelled there. A binding that
+// cannot be read is an error, and the pass writes nothing.
+func (s *Server) planFirstLabelling(ctx context.Context, fleet string, v fleetView) ([]relabel, error) {
+ var plan []relabel
+ for _, rec := range v.Records {
+ if !fleetLabelsRecord(rec) || rec.FleetBox != "" || !movable(rec) {
+ continue
+ }
+ b, ok, err := s.readFleetBinding(ctx, fleet, rec.Host)
+ if err != nil {
+ return nil, fmt.Errorf("binding of %s: %w", rec.Host, err)
+ }
+ // The binding must be this record's: written by a box of this
+ // fleet, for this host, after the record was created (a binding
+ // left by an earlier record at the same host names a box that
+ // served other data).
+ if !ok || b.Fleet != fleet || b.Host != rec.Host || b.BoundAt < rec.CreatedAt.UnixMilli() {
+ continue
+ }
+ if !v.validDestination(b.Box, rec.Runtime == provision.RuntimeRootfsV1) {
+ continue
+ }
+ plan = append(plan, relabel{rec: rec, to: b.Box, reason: "binding"})
+ }
+ return plan, nil
+}
+
+// writeRelabels makes plan's writes, each marking its box labelled first,
+// and answers how many records were written.
+func (s *Server) writeRelabels(ctx context.Context, fleet string, plan []relabel, now time.Time) int {
+ if len(plan) == 0 {
+ return 0
+ }
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ log.Printf("console: fleet relabel %s: registry: %v", fleet, err)
+ jobFailed(ctx, err)
+ return 0
+ }
+ moved := 0
+ for _, p := range plan {
+ if err := reg.MarkFleetBoxLabelled(fleet, p.to, now.UnixNano()); err != nil {
+ log.Printf("console: fleet relabel %s: mark %s labelled: %v; %s left", fleet, p.to, err, p.rec.Host)
+ jobFailed(ctx, err)
+ continue
+ }
+ want := provision.FleetBoxExpect{Region: p.rec.Region, Label: p.rec.FleetBox, CreatedAt: p.rec.CreatedAt}
+ err := provision.SetRecordFleetBox(ctx, s.cfg.Releases, p.rec.Account, p.rec.App, p.rec.Host, want, p.to, now)
+ switch {
+ // ErrFleetBoxImportInFlight wraps a *SeedMoveError, so it is told
+ // apart first (controller ruling 4).
+ case errors.Is(err, provision.ErrFleetBoxImportInFlight):
+ log.Printf("console: fleet relabel %s: %s has an import in flight; left on %q for a later pass", fleet, p.rec.Host, p.rec.FleetBox)
+ case errors.Is(err, provision.ErrFleetBoxMoved):
+ log.Printf("console: fleet relabel %s: %s changed since it was read; left for a later pass", fleet, p.rec.Host)
+ case err != nil:
+ log.Printf("console: fleet relabel %s: %s: %v", fleet, p.rec.Host, err)
+ jobFailed(ctx, err)
+ default:
+ moved++
+ log.Printf("console: fleet relabel %s: %s from %s to %s (%s)", fleet, p.rec.Host, boxOrNone(p.rec.FleetBox), p.to, p.reason)
+ }
+ }
+ return moved
+}
+
+func boxOrNone(label string) string {
+ if label == "" {
+ return "no box"
+ }
+ return label
+}
+
+func releaseOrUnknown(rel string) string {
+ if rel == "" {
+ return "unknown"
+ }
+ return rel
+}
+
+// boxGone is why a record labelled to label must move, or "": the box is
+// draining, lost (its newest heartbeat is older than fleetBoxLostAfter, or
+// it has none), or not an active box of the fleet at all.
+func (v fleetView) boxGone(label string, now time.Time) string {
+ for _, b := range v.Boxes {
+ if b.Label != label {
+ continue
+ }
+ switch {
+ case b.Draining:
+ return "draining"
+ case b.LastSeen.IsZero() || now.Sub(b.LastSeen) > fleetBoxLostAfter:
+ return "lost"
+ }
+ return ""
+ }
+ return "detached"
+}
+
+// validDestination reports whether label is an active box of the fleet
+// that chooseDestination could choose for a record.
+func (v fleetView) validDestination(label string, rootfs bool) bool {
+ for _, b := range v.Boxes {
+ if b.Label == label {
+ return b.destinationFor(rootfs)
+ }
+ }
+ return false
+}
+
+// labelled reports whether the fleet has labels: some record carries one,
+// or the console has named some box on a record.
+func (v fleetView) labelled() bool {
+ for _, b := range v.Boxes {
+ if b.Labelled {
+ return true
+ }
+ }
+ for _, rec := range v.Records {
+ if rec.FleetBox != "" {
+ return true
+ }
+ }
+ return false
+}
+
+// labelsPausedBy is rule 8's pause: on a fleet with labels, the first
+// active box (by label) whose newest heartbeat reports a release below the
+// label floor, or names none, and that release. "" when nothing pauses the
+// fleet. A box with no heartbeat at all reports nothing and does not pause
+// it.
+func (v fleetView) labelsPausedBy() (box, rel string) {
+ if !v.labelled() {
+ return "", ""
+ }
+ for _, b := range v.Boxes {
+ if !b.LastSeen.IsZero() && !b.AtLabelFloor {
+ return b.Label, b.Release
+ }
+ }
+ return "", ""
+}
+
+// fleetBinding is the part of a box's binding object (internal/host's
+// FleetBinding, written by the box that won the host's lease) the first
+// labelling reads.
+type fleetBinding struct {
+ Host string `json:"host"`
+ Fleet string `json:"fleet"`
+ Box string `json:"box"`
+ BoundAt int64 `json:"bound_at"` // unix milliseconds
+}
+
+// fleetBindingMaxBytes bounds a binding object's body.
+const fleetBindingMaxBytes = 4 << 10
+
+// readFleetBinding reads fleets/<fleet>/bindings/<host>.json. ok is false
+// when there is none. A body that will not decode is an error, as is any
+// failed read.
+func (s *Server) readFleetBinding(ctx context.Context, fleet, h string) (fleetBinding, bool, error) {
+ body, _, err := s.cfg.Releases.Get(ctx, "fleets/"+fleet+"/bindings/"+h+".json")
+ if errors.Is(err, os.ErrNotExist) {
+ return fleetBinding{}, false, nil
+ }
+ if err != nil {
+ return fleetBinding{}, false, err
+ }
+ if len(body) > fleetBindingMaxBytes {
+ return fleetBinding{}, false, fmt.Errorf("binding of %s is %d bytes", h, len(body))
+ }
+ var b fleetBinding
+ if err := json.Unmarshal(body, &b); err != nil {
+ return fleetBinding{}, false, err
+ }
+ return b, true, nil
+}
+
+// drainDone is the drain rule (rule 5), the one test of whether a draining
+// box holds nothing and may be detached: its newest heartbeat hb was
+// composed after the drain began (drainingSince, zero when the box is not
+// draining) and reports no routes for the fleet, no held leases and no
+// failed final replications still on its disk. Static routes do not count:
+// every box of the fleet serves them from the bucket, with no process, no
+// lease and no local data. The heartbeat must also come from a release at
+// the label floor, since an older box reports no leases at all and would
+// read as holding none. There is no exception for a silent box.
+func drainDone(hb status.Box, drainingSince time.Time) bool {
+ return !drainingSince.IsZero() &&
+ hb.GeneratedAt.After(drainingSince) &&
+ boxAtLabelFloor(hb) &&
+ hb.Routes.Resident == 0 && hb.Routes.Hibernating == 0 && hb.Sidecars == 0 &&
+ hb.LeasesHeld == 0 && hb.ReplicationFailures == 0
+}
+
+// fleetBoxBeatMaxBytes bounds a heartbeat's body, as status's own reader does.
+const fleetBoxBeatMaxBytes = 1 << 20
+
+// readFleetBoxBeat reads the newest heartbeat of fleet's box label, the one
+// read drain completion makes. ok is false when there is none.
+func (s *Server) readFleetBoxBeat(ctx context.Context, fleet, label string) (status.Box, bool, error) {
+ if s.cfg.Releases == nil {
+ return status.Box{}, false, errors.New("no release store configured")
+ }
+ body, _, err := s.cfg.Releases.Get(ctx, "fleets/"+fleet+"/status/boxes/"+label+".json")
+ if errors.Is(err, os.ErrNotExist) {
+ return status.Box{}, false, nil
+ }
+ if err != nil {
+ return status.Box{}, false, err
+ }
+ if len(body) > fleetBoxBeatMaxBytes {
+ return status.Box{}, false, fmt.Errorf("heartbeat of %s/%s is %d bytes", fleet, label, len(body))
+ }
+ var b status.Box
+ if err := json.Unmarshal(body, &b); err != nil {
+ return status.Box{}, false, err
+ }
+ return b, true, nil
+}
+
+// detachHeld is the detach doors' one check: whether box must stay
+// attached. A box the console never named on a record holds nothing it
+// placed and detaches at once, as on main. Any other box detaches only
+// when drainDone says so of its newest heartbeat: a box that is not
+// draining, or has not reported since its drain began, stays attached.
+// err is a heartbeat that could not be read.
+func (s *Server) detachHeld(ctx context.Context, fleet string, box registry.FleetBox) (bool, error) {
+ if box.Status != "active" || box.LabelledAt == 0 {
+ return false, nil
+ }
+ if box.DrainingSince == 0 {
+ return true, nil
+ }
+ hb, ok, err := s.readFleetBoxBeat(ctx, fleet, box.Label)
+ if err != nil {
+ return false, err
+ }
+ return !ok || !drainDone(hb, time.Unix(0, box.DrainingSince)), nil
+}
+
+// errFleetDrainHostClaim is drainBox's refusal on a host-claim console.
+var errFleetDrainHostClaim = errors.New("fleet drain is off on a host-claim console")
+
+// errFleetDrainIncomplete is drainBox's answer when the fleet could not be
+// read whole: nothing was written.
+var errFleetDrainIncomplete = errors.New("the fleet could not be read whole")
+
+// errFleetBoxNotActive is drainBox's answer for a box that is not an
+// active box of the fleet.
+var errFleetBoxNotActive = errors.New("no active box of that label")
+
+// fleetPausedError is drainBox's refusal on a fleet whose relabelling is
+// paused (rule 8).
+type fleetPausedError struct{ fleet, box, rel string }
+
+func (e *fleetPausedError) Error() string { return msgLabelsPaused(e.fleet, e.box, e.rel) }
+
+// drainBox is `carlos fleets drain <fleet> <label>` (rule 5): under the
+// fleet's lock, it moves every record the box runs to another box, or
+// refuses, answering the apps whose records cannot move, sorted, with
+// nothing written. A record cannot move when it is unlabelled (every box
+// runs it), when the platform cannot move it (movable), or when no other
+// box can take it. Otherwise the box is marked draining (it keeps its
+// fleet access and gets no new assignment) and each record is relabelled
+// to chooseDestination's choice. A record that changed since it was read,
+// or whose import has not committed, is left for the worker, which moves
+// every record of a draining box; so is one whose write failed, which is
+// err.
+func (s *Server) drainBox(ctx context.Context, fleet, label string) (stuck []string, err error) {
+ if s.cfg.HostClaim {
+ return nil, errFleetDrainHostClaim
+ }
+ if s.cfg.Releases == nil {
+ return nil, errors.New("no release store configured")
+ }
+ unlock := s.lockFleet(fleet)
+ defer unlock()
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ return nil, err
+ }
+ box, err := findFleetBox(reg, fleet, label)
+ if err != nil {
+ return nil, err
+ }
+ if box == nil || box.Status != "active" {
+ return nil, errFleetBoxNotActive
+ }
+ v, err := s.loadFleetView(ctx, fleet)
+ if err != nil {
+ return nil, err
+ }
+ if b, rel := v.labelsPausedBy(); b != "" {
+ return nil, &fleetPausedError{fleet: fleet, box: b, rel: rel}
+ }
+ recs := v.Records
+ if len(v.Boxes) < 2 {
+ // A one-box fleet's view reads no inventory: read it here, so the
+ // refusal can name what has nowhere to go.
+ var complete bool
+ recs, _, complete, err = s.fleetInventoryFor(ctx, fleet)
+ if err != nil {
+ return nil, err
+ }
+ if !complete {
+ return nil, errFleetDrainIncomplete
+ }
+ } else if !v.Active {
+ return nil, errFleetDrainIncomplete
+ }
+ strand := map[string]bool{}
+ var plan []relabel
+ for _, rec := range recs {
+ if !fleetLabelsRecord(rec) || (rec.FleetBox != "" && rec.FleetBox != label) {
+ continue
+ }
+ if rec.FleetBox == "" || !movable(rec) {
+ strand[rec.App] = true
+ continue
+ }
+ to := v.chooseDestination(rec.Runtime == provision.RuntimeRootfsV1, label)
+ if to == "" {
+ strand[rec.App] = true
+ continue
+ }
+ v.Load[to]++
+ plan = append(plan, relabel{rec: rec, to: to, reason: "drain"})
+ }
+ if len(strand) > 0 {
+ for app := range strand {
+ stuck = append(stuck, app)
+ }
+ sort.Strings(stuck)
+ return stuck, nil
+ }
+ now := time.Now()
+ since, err := reg.SetFleetBoxDraining(fleet, label, now.UnixNano())
+ if err != nil {
+ return nil, err
+ }
+ log.Printf("console: fleet drain %s/%s: draining since %s, %d records to move", fleet, label, time.Unix(0, since).UTC().Format(time.RFC3339Nano), len(plan))
+ moved := s.writeRelabels(ctx, fleet, plan, now)
+ if moved < len(plan) {
+ log.Printf("console: fleet drain %s/%s: moved %d of %d records; the relabel worker moves the rest", fleet, label, moved, len(plan))
+ }
+ return nil, nil
+}
+
+// labelsPausedFor is `carlos fleets ls`'s LABELS PAUSED: labelsPausedBy of
+// fleet's active boxes and their heartbeats. Only a fleet some box of which
+// the console ever named on a record has labels, so only such a fleet's
+// heartbeats are read.
+func (s *Server) labelsPausedFor(ctx context.Context, fleet string, boxes []registry.FleetBox) (bool, error) {
+ var v fleetView
+ for _, b := range boxes {
+ if b.Status == "active" {
+ v.Boxes = append(v.Boxes, fleetBoxViewOf(b))
+ }
+ }
+ if !v.labelled() || s.cfg.Releases == nil {
+ return false, nil
+ }
+ hbs, _, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+fleet+"/")
+ if err != nil {
+ return false, err
+ }
+ joinBeats(v.Boxes, hbs, time.Now())
+ box, _ := v.labelsPausedBy()
+ return box != "", nil
+}
+
+// msgDrainStrandsApps is the drain's refusal when some record of the box
+// has nowhere to go: apps names their apps. Nothing was changed.
+func msgDrainStrandsApps(fleet, label string, apps []string) string {
+ return fmt.Sprintf("cannot drain %s/%s. no other box can take the instances of %s yet. nothing changed",
+ fleet, label, strings.Join(apps, ", "))
+}
+
+// msgDetachNotDrained is both detach doors' refusal of a box that may
+// still hold instances, leases or unsynced data.
+func msgDetachNotDrained(fleet, label string) string {
+ return fmt.Sprintf("%s/%s may still hold instances. run carlos fleets drain %s %s, then detach it when the box reports it holds nothing",
+ fleet, label, fleet, label)
+}
+
+// msgLabelsPaused is the drain's refusal on a fleet whose box placement is
+// paused because box runs an older release than the floor.
+func msgLabelsPaused(fleet, box, rel string) string {
+ return fmt.Sprintf("box placement on %s is paused. %s runs %s, older than %s. update it, then try again",
+ fleet, box, releaseOrUnknown(rel), release.FleetBoxLabelFloor)
+}
+
+// msgDrainBoxNotActive is the drain's refusal of a detached box.
+func msgDrainBoxNotActive(fleet, label string) string {
+ return fmt.Sprintf("%s/%s is detached. there is nothing to drain", fleet, label)
+}
+
+// claimFleetDrainUnsupportedMsg is the drain door's answer on a host-claim
+// console, where no claim operation gates the record writes a drain makes.
+const claimFleetDrainUnsupportedMsg = "carlos fleets drain is not available on this console"
diff --git a/internal/console/fleetrelabel_test.go b/internal/console/fleetrelabel_test.go
new file mode 100644
index 000000000..be70abdde
--- /dev/null
+++ b/internal/console/fleetrelabel_test.go
@@ -0,0 +1,589 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/host"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// Managed fleets 1b, Task 6: the relabel worker (first labelling from
+// bindings, moves off lost and draining boxes, the pause below the floor),
+// the two-step drain and the one drain rule both detach doors ask. App shop
+// (and blog) in bab, fleet pi, boxes pi-1, pi-2, pi-3, hosts under
+// example.com.
+
+// bindTo publishes the binding a box writes when it wins host's lease
+// (internal/host, the production writer).
+func bindTo(t *testing.T, fx *consoleFixture, h, box string, at time.Time) {
+ t.Helper()
+ if err := host.WriteFleetBinding(context.Background(), fx.rel,
+ host.FleetBinding{Host: h, Fleet: "pi", Box: box, BoundAt: at.UnixMilli()}, true); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// shopRec reads shop's record of h.
+func shopRec(t *testing.T, fx *consoleFixture, h string) *provision.Record {
+ t.Helper()
+ rec, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "shop", h)
+ if err != nil {
+ t.Fatalf("read %s: %v", h, err)
+ }
+ return rec
+}
+
+// relabelPass runs one worker pass.
+func relabelPass(t *testing.T, fx *consoleFixture) {
+ t.Helper()
+ if err := fx.srv.fleetRelabelPass(context.Background()); err != nil {
+ t.Fatalf("relabel pass: %v", err)
+ }
+}
+
+// boxRow is pi's registry row for label.
+func boxRow(t *testing.T, reg *registry.Registry, label string) registry.FleetBox {
+ t.Helper()
+ boxes, err := reg.ListFleetBoxes("pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, b := range boxes {
+ if b.Label == label {
+ return b
+ }
+ }
+ t.Fatalf("no box pi/%s", label)
+ return registry.FleetBox{}
+}
+
+// beat writes box's heartbeat on pi at the label floor, generated at, with
+// mut applied.
+func beat(t *testing.T, fx *consoleFixture, box string, at time.Time, mut func(*status.Box)) {
+ t.Helper()
+ b := status.Box{GeneratedAt: at, Label: box,
+ Metrics: &status.BoxMetrics{Layout: &status.LayoutReport{Mode: "nested"}, RootfsReady: true, Release: release.FleetBoxLabelFloor}}
+ if mut != nil {
+ mut(&b)
+ }
+ if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/pi/"), b); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestFirstLabellingFollowsBindings(t *testing.T) {
+ fx, _, reg := fleetBoxWorld(t, "code-rl-first", "pi-1", "pi-2")
+ for h, box := range map[string]string{"a.example.com": "pi-1", "b.example.com": "pi-1", "c.example.com": "pi-2"} {
+ putFleetRecord(t, fx, "shop", h, nil)
+ bindTo(t, fx, h, box, time.Now())
+ }
+ relabelPass(t, fx)
+ for h, box := range map[string]string{"a.example.com": "pi-1", "b.example.com": "pi-1", "c.example.com": "pi-2"} {
+ wantLabel(t, shopRec(t, fx, h), box)
+ }
+ for _, l := range []string{"pi-1", "pi-2"} {
+ if b := boxRow(t, reg, l); b.LabelledAt == 0 {
+ t.Fatalf("%s was named on a record and not marked labelled", l)
+ }
+ }
+ // Nothing moves on the next pass.
+ before := shopRec(t, fx, "a.example.com").FleetBoxAt
+ relabelPass(t, fx)
+ if r := shopRec(t, fx, "a.example.com"); r.FleetBox != "pi-1" || r.FleetBoxAt != before || r.FleetBoxMoved {
+ t.Fatalf("a second pass changed a: %+v", r)
+ }
+}
+
+func TestFirstLabellingSkipsAnUnboundRecord(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-rl-unbound", "pi-1", "pi-2", "pi-3")
+ putFleetRecord(t, fx, "shop", "free.example.com", nil) // no binding at all
+ putFleetRecord(t, fx, "shop", "old.example.com", nil) // bound before this record was created
+ bindTo(t, fx, "old.example.com", "pi-1", time.Now().Add(-time.Hour))
+ putFleetRecord(t, fx, "shop", "gone.example.com", nil) // bound to a box no longer fresh
+ bindTo(t, fx, "gone.example.com", "pi-3", time.Now())
+ piBeat(t, fx, "pi-3", true, time.Now().Add(-time.Hour), release.FleetBoxLabelFloor)
+ relabelPass(t, fx)
+ for _, h := range []string{"free.example.com", "old.example.com", "gone.example.com"} {
+ wantNoLabel(t, shopRec(t, fx, h))
+ }
+ // Bound now: labelled to the box that serves it, never to a clean one.
+ bindTo(t, fx, "free.example.com", "pi-2", time.Now())
+ relabelPass(t, fx)
+ wantLabel(t, shopRec(t, fx, "free.example.com"), "pi-2")
+}
+
+func TestRelabelPassLeavesAnUngatedFleetAlone(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-rl-ungated", "pi-1", "pi-2")
+ fx.srv.consoleBuild = "v0.32.0" // the console below the floor: gate d
+ putFleetRecord(t, fx, "shop", "a.example.com", nil)
+ bindTo(t, fx, "a.example.com", "pi-1", time.Now())
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+ relabelPass(t, fx)
+ wantNoLabel(t, shopRec(t, fx, "a.example.com"))
+ if n := cs.recordPuts(); n != 0 {
+ t.Fatalf("an ungated pass wrote %d records", n)
+ }
+ if n := cs.getsOf("fleets/pi/bindings/a.example.com.json"); n != 0 {
+ t.Fatalf("an ungated pass read %d bindings", n)
+ }
+}
+
+func TestLostBoxMovesToTheSurvivor(t *testing.T) {
+ fx, _, reg := fleetBoxWorld(t, "code-rl-lost", "pi-1", "pi-2")
+ putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "shop", "b.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "shop", "c.example.com", func(r *provision.Record) { r.FleetBox = "pi-2" })
+ piBeat(t, fx, "pi-1", true, time.Now().Add(-19*time.Minute), release.FleetBoxLabelFloor)
+ relabelPass(t, fx)
+ for _, h := range []string{"a.example.com", "b.example.com"} {
+ if r := shopRec(t, fx, h); r.FleetBox != "pi-1" || r.FleetBoxMoved {
+ t.Fatalf("silent 19 minutes: %s moved to %q", h, r.FleetBox)
+ }
+ }
+ piBeat(t, fx, "pi-1", true, time.Now().Add(-21*time.Minute), release.FleetBoxLabelFloor)
+ var logs bytes.Buffer
+ restore := captureLogTo(&logs)
+ relabelPass(t, fx)
+ restore()
+ for _, h := range []string{"a.example.com", "b.example.com", "c.example.com"} {
+ if r := shopRec(t, fx, h); r.FleetBox != "pi-2" {
+ t.Fatalf("silent 21 minutes: %s is on %q; want pi-2", h, r.FleetBox)
+ }
+ }
+ if r := shopRec(t, fx, "a.example.com"); !r.FleetBoxMoved {
+ t.Fatal("a move did not set FleetBoxMoved")
+ }
+ if !strings.Contains(logs.String(), "a.example.com") || !strings.Contains(logs.String(), "from pi-1 to pi-2") {
+ t.Fatalf("no move line in the log:\n%s", logs.String())
+ }
+ // The silent box keeps its fleet access: it is still active.
+ if b := boxRow(t, reg, "pi-1"); b.Status != "active" {
+ t.Fatalf("the lost box was detached by the pass: %+v", b)
+ }
+
+ // A record on a box that is detached moves too.
+ registerFleetBox(t, reg, "pi", "pi-3")
+ piBeat(t, fx, "pi-3", true, time.Now(), release.FleetBoxLabelFloor)
+ putFleetRecord(t, fx, "shop", "d.example.com", func(r *provision.Record) { r.FleetBox = "pi-9" })
+ relabelPass(t, fx)
+ if r := shopRec(t, fx, "d.example.com"); r.FleetBox != "pi-3" {
+ t.Fatalf("a record on an unknown box is on %q; want the least loaded pi-3", r.FleetBox)
+ }
+}
+
+func TestRelabelLosesToAPlacementChange(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-rl-race", "pi-1", "pi-2")
+ putFleetRecord(t, fx, "shop", "a.example.com", nil)
+ bindTo(t, fx, "a.example.com", "pi-1", time.Now())
+ ctx := context.Background()
+ v, err := fx.srv.loadFleetView(ctx, "pi")
+ if err != nil || !v.labelActive() {
+ t.Fatalf("view %+v, %v", v, err)
+ }
+ // The app moves to another fleet after the pass read the record.
+ if err := provision.SetRecordRegion(ctx, fx.rel, fx.sqid, "shop", "a.example.com", "fleet/other"); err != nil {
+ t.Fatal(err)
+ }
+ moved, err := fx.srv.relabelFleet(ctx, "pi", v)
+ if err != nil || moved != 0 {
+ t.Fatalf("relabelFleet = %d, %v; want nothing moved and no error", moved, err)
+ }
+ r := shopRec(t, fx, "a.example.com")
+ wantNoLabel(t, r)
+ if r.Region != "fleet/other" {
+ t.Fatalf("region %q; want the new fleet kept", r.Region)
+ }
+}
+
+// Ruling 4: a record whose import has not committed keeps its box until a
+// later pass.
+func TestRelabelSkipsAnImportInFlight(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-rl-import", "pi-1", "pi-2")
+ putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) {
+ r.FleetBox = "pi-1"
+ r.Seed = &provision.SeedSource{ID: newSeedID(t), Kind: seeds.KindImport, State: seeds.StateSwapped, At: time.Now().UTC()}
+ })
+ if b := shopRec(t, fx, "a.example.com").Seed.MoveBlock(); b == "" {
+ t.Fatal("the fixture's seed does not block a move")
+ }
+ piBeat(t, fx, "pi-1", true, time.Now().Add(-21*time.Minute), release.FleetBoxLabelFloor)
+ relabelPass(t, fx)
+ if r := shopRec(t, fx, "a.example.com"); r.FleetBox != "pi-1" {
+ t.Fatalf("an import in flight moved to %q", r.FleetBox)
+ }
+}
+
+func TestBelowFloorBoxPausesAndAlerts(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-rl-floor", "pi-1", "pi-2", "pi-3")
+ putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "shop", "b.example.com", nil)
+ bindTo(t, fx, "b.example.com", "pi-2", time.Now())
+ relabelPass(t, fx)
+ wantLabel(t, shopRec(t, fx, "b.example.com"), "pi-2") // labels exist now
+
+ piBeat(t, fx, "pi-1", true, time.Now().Add(-21*time.Minute), release.FleetBoxLabelFloor) // lost
+ piBeat(t, fx, "pi-3", true, time.Now(), "v0.32.0") // rolled back
+ var logs bytes.Buffer
+ restore := captureLogTo(&logs)
+ relabelPass(t, fx)
+ restore()
+ if r := shopRec(t, fx, "a.example.com"); r.FleetBox != "pi-1" {
+ t.Fatalf("a paused fleet moved a to %q", r.FleetBox)
+ }
+ if out := logs.String(); !strings.Contains(out, "ERROR") || !strings.Contains(out, "pi-3") || !strings.Contains(out, "v0.32.0") {
+ t.Fatalf("no alert naming the fleet, box and release:\n%s", out)
+ }
+ if !fleetListPaused(t, fx, token) {
+ t.Fatal("fleets ls does not show labels paused")
+ }
+
+ piBeat(t, fx, "pi-3", true, time.Now(), release.FleetBoxLabelFloor)
+ relabelPass(t, fx)
+ if r := shopRec(t, fx, "a.example.com"); r.FleetBox == "pi-1" {
+ t.Fatal("a resumed fleet did not move a off the lost box")
+ }
+ if fleetListPaused(t, fx, token) {
+ t.Fatal("fleets ls still shows labels paused")
+ }
+}
+
+// fleetListPaused is fleet pi's labels_paused in `carlos fleets ls`.
+func fleetListPaused(t *testing.T, fx *consoleFixture, token string) bool {
+ t.Helper()
+ code, _, raw := rawReq(t, http.MethodGet, fleetsURL(fx, fx.sqid), token, "")
+ if code != http.StatusOK {
+ t.Fatalf("fleets ls = %d %s", code, raw)
+ }
+ return strings.Contains(raw, `"labels_paused":true`)
+}
+
+// drainURL is the drain door for box label of fleet pi.
+func drainURL(fx *consoleFixture, label string) string {
+ return fleetsURL(fx, fx.sqid) + "/pi/boxes/" + label + "/drain"
+}
+
+func TestDrainMovesEverythingOrNothing(t *testing.T) {
+ fx, token, reg := fleetBoxWorld(t, "code-rl-drain", "pi-1", "pi-2")
+ placeBlog(t, fx)
+ putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "blog", "b.example.com", func(r *provision.Record) {
+ alwaysOn := false
+ r.FleetBox, r.Runtime, r.Hibernate = "pi-1", provision.RuntimeRootfsV1, &alwaysOn
+ })
+ piBeat(t, fx, "pi-2", false, time.Now(), release.FleetBoxLabelFloor) // not rootfs-ready
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+
+ code, _, raw := rawReq(t, http.MethodPost, drainURL(fx, "pi-1"), token, `{}`)
+ if code != http.StatusConflict || errorOf(t, raw) != msgDrainStrandsApps("pi", "pi-1", []string{"blog"}) {
+ t.Fatalf("drain with a stranded record = %d %s; want 409 naming blog", code, raw)
+ }
+ if n := cs.recordPuts(); n != 0 {
+ t.Fatalf("a refused drain wrote %d records", n)
+ }
+ if b := boxRow(t, reg, "pi-1"); b.DrainingSince != 0 {
+ t.Fatalf("a refused drain marked the box draining: %+v", b)
+ }
+
+ piBeat(t, fx, "pi-2", true, time.Now(), release.FleetBoxLabelFloor)
+ if code, _, raw := rawReq(t, http.MethodPost, drainURL(fx, "pi-1"), token, `{}`); code != http.StatusOK {
+ t.Fatalf("drain = %d %s", code, raw)
+ }
+ if r := shopRec(t, fx, "a.example.com"); r.FleetBox != "pi-2" || !r.FleetBoxMoved {
+ t.Fatalf("a after the drain: %+v", r)
+ }
+ if r, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "blog", "b.example.com"); err != nil || r.FleetBox != "pi-2" {
+ t.Fatalf("b after the drain: %+v, %v", r, err)
+ }
+ b := boxRow(t, reg, "pi-1")
+ if b.DrainingSince == 0 || b.Status != "active" {
+ t.Fatalf("drained box %+v; want active and draining", b)
+ }
+ // No new assignment goes to a draining box.
+ v, err := fx.srv.loadFleetView(context.Background(), "pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := v.chooseDestination(false, "pi-2"); got != "" {
+ t.Fatalf("a draining box was chosen: %q", got)
+ }
+}
+
+// Rule 11 and ruling 3: a record the platform does not run, and an HA
+// record, cannot move; the drain names their apps and changes nothing. An
+// unlabelled record runs on every box, so it strands the drain too.
+func TestDrainRefusesAnUnmanagedRecord(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ mut func(*provision.Record)
+ }{
+ {"addr", func(r *provision.Record) { r.Addr = "127.0.0.1:9000" }},
+ {"ha", func(r *provision.Record) { r.HA = true; r.FleetBox = "pi-1" }},
+ {"unlabelled", nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx, _, reg := fleetBoxWorld(t, "code-rl-unmanaged-"+tc.name, "pi-1", "pi-2")
+ placeBlog(t, fx)
+ putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "blog", "x.example.com", tc.mut)
+ stuck, err := fx.srv.drainBox(context.Background(), "pi", "pi-1")
+ if err != nil || len(stuck) != 1 || stuck[0] != "blog" {
+ t.Fatalf("drainBox = %v, %v; want blog stranded", stuck, err)
+ }
+ if r := shopRec(t, fx, "a.example.com"); r.FleetBox != "pi-1" {
+ t.Fatalf("a refused drain moved a to %q", r.FleetBox)
+ }
+ if b := boxRow(t, reg, "pi-1"); b.DrainingSince != 0 {
+ t.Fatal("a refused drain marked the box draining")
+ }
+ })
+ }
+ if movable(provision.Record{HA: true}) {
+ t.Fatal("movable admits an HA record")
+ }
+}
+
+// The drain rule, one fact at a time.
+func TestDrainDoneNeedsAPostDrainHeartbeat(t *testing.T) {
+ since := time.Now()
+ empty := status.Box{GeneratedAt: since.Add(-time.Second), Metrics: &status.BoxMetrics{Release: release.FleetBoxLabelFloor}}
+ if drainDone(empty, since) {
+ t.Fatal("an empty heartbeat composed before the drain is done")
+ }
+ empty.GeneratedAt = since.Add(time.Second)
+ if !drainDone(empty, since) {
+ t.Fatal("an empty heartbeat composed after the drain is not done")
+ }
+ if drainDone(empty, time.Time{}) {
+ t.Fatal("a box that is not draining is done")
+ }
+ routes := empty
+ routes.Routes.Hibernating = 1
+ if drainDone(routes, since) {
+ t.Fatal("a heartbeat listing a route for the fleet is done")
+ }
+ side := empty
+ side.Sidecars = 1
+ if drainDone(side, since) {
+ t.Fatal("a heartbeat listing a sidecar is done")
+ }
+ old := empty
+ old.Metrics = &status.BoxMetrics{Release: "v0.32.0"}
+ if drainDone(old, since) {
+ t.Fatal("a box below the floor, which reports no leases, is done")
+ }
+ // Static routes are served from the bucket by every box: no lease, no data.
+ static := empty
+ static.Routes.Static = 2
+ if !drainDone(static, since) {
+ t.Fatal("static routes held the drain open")
+ }
+}
+
+func TestDrainDoneNeedsNoLeases(t *testing.T) {
+ since := time.Now()
+ hb := status.Box{GeneratedAt: since.Add(time.Minute), LeasesHeld: 1, Metrics: &status.BoxMetrics{Release: release.FleetBoxLabelFloor}}
+ if drainDone(hb, since) {
+ t.Fatal("no routes but one lease held is done")
+ }
+ hb.LeasesHeld = 0
+ if !drainDone(hb, since) {
+ t.Fatal("no routes and no leases is not done")
+ }
+}
+
+// drainedPi1 is a world where pi-1 held a.example.com and was drained: its
+// record is on pi-2 and pi-1 is draining.
+func drainedPi1(t *testing.T, code string) (*consoleFixture, string, *registry.Registry) {
+ t.Helper()
+ fx, token, reg := fleetBoxWorld(t, code, "pi-1", "pi-2")
+ putFleetRecord(t, fx, "shop", "a.example.com", nil)
+ bindTo(t, fx, "a.example.com", "pi-1", time.Now())
+ relabelPass(t, fx)
+ wantLabel(t, shopRec(t, fx, "a.example.com"), "pi-1")
+ if code, _, raw := rawReq(t, http.MethodPost, drainURL(fx, "pi-1"), token, `{}`); code != http.StatusOK {
+ t.Fatalf("drain = %d %s", code, raw)
+ }
+ return fx, token, reg
+}
+
+// detachAPI detaches label through the CLI door.
+func detachAPI(t *testing.T, fx *consoleFixture, token, label string) (int, string) {
+ t.Helper()
+ code, _, raw := rawReq(t, http.MethodPost, fleetsURL(fx, fx.sqid)+"/pi/boxes/"+label+"/detach", token, `{}`)
+ return code, raw
+}
+
+// detachPage detaches label through the owner's form and answers the flash
+// the fleet page then shows.
+func detachPage(t *testing.T, fx *consoleFixture, label string) string {
+ t.Helper()
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-rl-page-"+label+"-"+strings.ReplaceAll(t.Name(), "/", "-"))
+ csrf := sessionToken(t, fx, c)
+ st, loc, _ := postForm(t, c, fx.u("/fleets/pi/detach"), url.Values{"csrf": {csrf}, "label": {label}})
+ if st != http.StatusSeeOther || loc != fx.path("/fleets/pi") {
+ t.Fatalf("page detach = %d -> %q", st, loc)
+ }
+ _, _, body := get(t, c, fx.u("/fleets/pi"))
+ return body
+}
+
+func TestDrainDoneNeedsNoFailedReplication(t *testing.T) {
+ fx, token, reg := drainedPi1(t, "code-rl-replfail")
+ // The box stopped a.example.com and released its lease, but the final
+ // sync failed (the box half: TestFailedFinalSyncIsReportedUntilReplicated,
+ // internal/activator): it reports 1.
+ beat(t, fx, "pi-1", time.Now().Add(time.Second), func(b *status.Box) { b.ReplicationFailures = 1 })
+ if code, raw := detachAPI(t, fx, token, "pi-1"); code != http.StatusConflict || errorOf(t, raw) != msgDetachNotDrained("pi", "pi-1") {
+ t.Fatalf("detach with a failed final sync = %d %s; want 409", code, raw)
+ }
+ // A later replication landed and cleared it.
+ beat(t, fx, "pi-1", time.Now().Add(2*time.Second), nil)
+ if code, raw := detachAPI(t, fx, token, "pi-1"); code != http.StatusOK {
+ t.Fatalf("detach of a drained box = %d %s", code, raw)
+ }
+ if b := boxRow(t, reg, "pi-1"); b.Status != "detached" {
+ t.Fatalf("box %+v; want detached", b)
+ }
+}
+
+func TestSilentBoxCannotBeDetached(t *testing.T) {
+ fx, token, reg := fleetBoxWorld(t, "code-rl-silent", "pi-1", "pi-2")
+ putFleetRecord(t, fx, "shop", "a.example.com", nil)
+ bindTo(t, fx, "a.example.com", "pi-1", time.Now())
+ relabelPass(t, fx)
+ piBeat(t, fx, "pi-1", true, time.Now().Add(-21*time.Minute), release.FleetBoxLabelFloor)
+ relabelPass(t, fx)
+ if r := shopRec(t, fx, "a.example.com"); r.FleetBox != "pi-2" {
+ t.Fatalf("the silent box's record is on %q; want pi-2", r.FleetBox)
+ }
+ if code, raw := detachAPI(t, fx, token, "pi-1"); code != http.StatusConflict || errorOf(t, raw) != msgDetachNotDrained("pi", "pi-1") {
+ t.Fatalf("API detach of a silent box = %d %s; want 409", code, raw)
+ }
+ if body := detachPage(t, fx, "pi-1"); !strings.Contains(body, msgDetachNotDrained("pi", "pi-1")) {
+ t.Fatalf("page detach of a silent box shows no refusal:\n%s", body)
+ }
+ // Drained, it is still silent: no heartbeat after the drain.
+ if code, _, raw := rawReq(t, http.MethodPost, drainURL(fx, "pi-1"), token, `{}`); code != http.StatusOK {
+ t.Fatalf("drain = %d %s", code, raw)
+ }
+ if code, raw := detachAPI(t, fx, token, "pi-1"); code != http.StatusConflict {
+ t.Fatalf("API detach of a drained silent box = %d %s; want 409", code, raw)
+ }
+ if b := boxRow(t, reg, "pi-1"); b.Status != "active" {
+ t.Fatalf("box %+v; want still attached", b)
+ }
+}
+
+func TestBothDetachDoorsUseDrainDone(t *testing.T) {
+ for _, door := range []string{"api", "page"} {
+ t.Run(door, func(t *testing.T) {
+ fx, token, reg := drainedPi1(t, "code-rl-doors-"+door)
+ detach := func() (ok bool, said string) {
+ if door == "api" {
+ code, raw := detachAPI(t, fx, token, "pi-1")
+ return code == http.StatusOK, raw
+ }
+ body := detachPage(t, fx, "pi-1")
+ return strings.Contains(body, "Detached pi/pi-1."), body
+ }
+ // A post-drain heartbeat that still holds a lease.
+ beat(t, fx, "pi-1", time.Now().Add(time.Second), func(b *status.Box) { b.LeasesHeld = 1 })
+ if ok, said := detach(); ok || !strings.Contains(said, msgDetachNotDrained("pi", "pi-1")) {
+ t.Fatalf("detach while a lease is held: ok %v\n%s", ok, said)
+ }
+ if b := boxRow(t, reg, "pi-1"); b.Status != "active" {
+ t.Fatal("a refused detach detached the box")
+ }
+ beat(t, fx, "pi-1", time.Now().Add(2*time.Second), nil)
+ if ok, said := detach(); !ok {
+ t.Fatalf("detach of a drained box refused:\n%s", said)
+ }
+ if b := boxRow(t, reg, "pi-1"); b.Status != "detached" {
+ t.Fatalf("box %+v; want detached", b)
+ }
+ })
+ }
+ // A box never named on a record detaches at once, at either door.
+ fx, token, reg := fleetBoxWorld(t, "code-rl-doors-fresh", "pi-1", "pi-2", "pi-3")
+ if code, raw := detachAPI(t, fx, token, "pi-2"); code != http.StatusOK {
+ t.Fatalf("API detach of a box that held nothing = %d %s", code, raw)
+ }
+ if body := detachPage(t, fx, "pi-3"); !strings.Contains(body, "Detached pi/pi-3.") {
+ t.Fatalf("page detach of a box that held nothing:\n%s", body)
+ }
+ if b := boxRow(t, reg, "pi-3"); b.Status != "detached" {
+ t.Fatalf("box %+v; want detached", b)
+ }
+}
+
+// Global Constraints, request budget: an idle labelled fleet costs one
+// heartbeat listing and one read per box, the deployment's listing, one
+// instance and one sidecar listing per placed app, no record reads and no
+// writes.
+func TestIdlePassCostsTheBudget(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-rl-budget", "pi-1", "pi-2")
+ putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "shop", "b.example.com", func(r *provision.Record) { r.FleetBox = "pi-2" })
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+ relabelPass(t, fx) // warms the inventory
+ cs.reset()
+ relabelPass(t, fx)
+ if n := cs.listsOf("fleets/pi/status/boxes/"); n != 1 {
+ t.Fatalf("an idle pass listed pi's heartbeats %d times; want once", n)
+ }
+ for _, b := range []string{"pi-1", "pi-2"} {
+ if n := cs.getsOf("fleets/pi/status/boxes/" + b + ".json"); n != 1 {
+ t.Fatalf("an idle pass read %s's heartbeat %d times; want once", b, n)
+ }
+ }
+ if n := cs.listsOf("status/boxes/"); n != 1 {
+ t.Fatalf("an idle pass listed the platform's heartbeats %d times; want once", n)
+ }
+ if l, s := cs.listsOf(provision.RecordsPrefix(fx.sqid, "shop")), cs.listsOf(provision.SidecarsPrefix(fx.sqid, "shop")); l != 1 || s != 1 {
+ t.Fatalf("an idle pass listed shop's instances %d and sidecars %d times; want once each", l, s)
+ }
+ if n := cs.recordGets(fx.sqid, "shop"); n != 0 {
+ t.Fatalf("an idle pass read %d records; want none", n)
+ }
+ cs.mu.Lock()
+ puts := len(cs.puts)
+ var bindingGets int
+ for k, v := range cs.gets {
+ if strings.Contains(k, "/bindings/") {
+ bindingGets += v
+ }
+ }
+ cs.mu.Unlock()
+ if puts != 0 || bindingGets != 0 {
+ t.Fatalf("an idle pass made %d writes and %d binding reads; want none", puts, bindingGets)
+ }
+}
+
+// The drain and the worker are off on a host-claim console, where no claim
+// operation gates their record writes.
+func TestDrainRefusedOnAHostClaimConsole(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-rl-claim", "pi-1", "pi-2")
+ fx.srv.cfg.HostClaim = true
+ code, _, raw := rawReq(t, http.MethodPost, drainURL(fx, "pi-1"), token, `{}`)
+ if code != http.StatusConflict || errorOf(t, raw) != claimFleetDrainUnsupportedMsg {
+ t.Fatalf("drain on a host-claim console = %d %s", code, raw)
+ }
+ if _, err := fx.srv.drainBox(context.Background(), "pi", "pi-1"); !errors.Is(err, errFleetDrainHostClaim) {
+ t.Fatalf("drainBox on a host-claim console = %v", err)
+ }
+}
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index fafae1c75..0621dcc6e 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -55,6 +55,9 @@ type fleetBoxWire struct {
// untagged box, never a bare "" — existing callers parsing this shape
// before tags existed see nothing new unless a box actually carries some.
Tags string `json:"tags,omitempty"`
+ // Draining is additive (managed fleets 1b, Task 6): present only for a
+ // box `carlos fleets drain` has begun draining.
+ Draining bool `json:"draining,omitempty"`
}
type fleetWire struct {
@@ -68,6 +71,10 @@ type fleetWire struct {
// reads as it always did.
SecretsKeyFP string `json:"secrets_key_fp,omitempty"`
StaleSecrets int `json:"stale_secrets,omitempty"`
+ // LabelsPaused is additive (managed fleets 1b, rule 8): present only
+ // while a box of a fleet with labels reports a release below the label
+ // floor, so the console has stopped moving its instances.
+ LabelsPaused bool `json:"labels_paused,omitempty"`
}
// apiFleet resolves and authorizes one {account}/{fleet} CLI API request:
@@ -313,7 +320,8 @@ func (s *Server) handleAPIFleetNew(w http.ResponseWriter, r *http.Request) {
func fleetBoxViews(boxes []registry.FleetBox) []fleetBoxWire {
bv := make([]fleetBoxWire, 0, len(boxes))
for _, b := range boxes {
- bv = append(bv, fleetBoxWire{Label: b.Label, Status: b.Status, Tags: b.Tags})
+ bv = append(bv, fleetBoxWire{Label: b.Label, Status: b.Status, Tags: b.Tags,
+ Draining: b.Status == "active" && b.DrainingSince != 0})
}
return bv
}
@@ -349,6 +357,12 @@ func (s *Server) handleAPIFleetList(w http.ResponseWriter, r *http.Request) {
return
}
view := fleetWire{Name: f.Name, Bucket: f.Bucket, Boxes: fleetBoxViews(boxes), SecretsKeyFP: f.SecretsKeyFP}
+ // A heartbeat listing that cannot be read costs the column, not the list.
+ paused, err := s.labelsPausedFor(r.Context(), f.Name, boxes)
+ if err != nil {
+ log.Printf("console: fleet list %s: labels paused of %s: %v", acct.Sqid, f.Name, err)
+ }
+ view.LabelsPaused = paused
if f.SecretsKeyFP != "" {
// The stale count repeats the key door's report until it is
// zero (spec §5.1 B2). A bucket that cannot be read costs the
@@ -566,6 +580,20 @@ func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request)
jsonError(w, http.StatusNotFound, "no such box")
return
}
+ // The drain rule (managed fleets 1b, rule 5): under the fleet's lock,
+ // so no create names the box between the check and the write.
+ unlock := s.lockFleet(fleet.Name)
+ defer unlock()
+ held, err := s.detachHeld(r.Context(), fleet.Name, *box)
+ if err != nil {
+ log.Printf("console: fleet detach %s/%s/%s: heartbeat: %v", acct.Sqid, fleet.Name, label, err)
+ jsonError(w, http.StatusServiceUnavailable, "could not read what the box reports. try again")
+ return
+ }
+ if held {
+ jsonError(w, http.StatusConflict, msgDetachNotDrained(fleet.Name, label))
+ return
+ }
if err := reg.SetFleetBoxStatus(fleet.Name, label, "detached"); err != nil {
log.Printf("console: fleet detach %s/%s/%s: %v", acct.Sqid, fleet.Name, label, err)
jsonError(w, http.StatusInternalServerError, "could not detach the box — try again")
@@ -575,6 +603,67 @@ func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, map[string]any{})
}
+// handleAPIFleetDrainBox answers `carlos fleets drain`: the first of the two
+// steps that take a box out of a fleet whose instances it runs (managed
+// fleets 1b, rule 5). It moves every instance of the box to another box,
+// or refuses naming the apps that have nowhere to go, changing nothing,
+// and marks the box draining: it keeps its fleet access and gets no new
+// instances. Detach (handleAPIFleetDetachBox) is the second step, refused
+// until the box reports it holds nothing (drainDone).
+func (s *Server) handleAPIFleetDrainBox(w http.ResponseWriter, r *http.Request) {
+ addr, acct, fleet, reg, ok := s.apiFleet(w, r)
+ if !ok {
+ return
+ }
+ p, _ := principalFrom(r.Context())
+ if !s.allowWrite(p, time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, "too many requests. wait a minute and try again")
+ return
+ }
+ var req struct{}
+ if !readJSON(w, r, &req) {
+ return
+ }
+ label := r.PathValue("label")
+ box, err := findFleetBox(reg, fleet.Name, label)
+ if err != nil {
+ log.Printf("console: fleet drain %s/%s/%s: %v", acct.Sqid, fleet.Name, label, err)
+ jsonError(w, http.StatusInternalServerError, "could not read the box")
+ return
+ }
+ if box == nil {
+ jsonError(w, http.StatusNotFound, "no such box")
+ return
+ }
+ stuck, err := s.drainBox(r.Context(), fleet.Name, label)
+ var paused *fleetPausedError
+ switch {
+ case errors.Is(err, errFleetDrainHostClaim):
+ jsonError(w, http.StatusConflict, claimFleetDrainUnsupportedMsg)
+ return
+ case errors.Is(err, errFleetBoxNotActive):
+ jsonError(w, http.StatusConflict, msgDrainBoxNotActive(fleet.Name, label))
+ return
+ case errors.As(err, &paused):
+ jsonError(w, http.StatusConflict, paused.Error())
+ return
+ case len(stuck) > 0:
+ jsonError(w, http.StatusConflict, msgDrainStrandsApps(fleet.Name, label, stuck))
+ return
+ case err != nil && !errors.Is(err, errFleetDrainIncomplete):
+ // The box may already be draining: the worker finishes the moves.
+ log.Printf("console: fleet drain %s/%s/%s: %v", acct.Sqid, fleet.Name, label, err)
+ jsonError(w, http.StatusServiceUnavailable, "could not drain the box. try again")
+ return
+ case err != nil:
+ log.Printf("console: fleet drain %s/%s/%s: %v", acct.Sqid, fleet.Name, label, err)
+ jsonError(w, http.StatusServiceUnavailable, "could not read the whole fleet. nothing changed. try again")
+ return
+ }
+ s.audit(acct, fleet.Name, addr, "fleet-drain-box", "began draining "+fleet.Name+"/"+label+" (cli)")
+ writeJSON(w, http.StatusOK, map[string]any{})
+}
+
// appPlacement reports an app's fleet placement target ("fleet/<name>"), or
// "" for none.
//
@@ -1476,6 +1565,19 @@ func (s *Server) handleFleetDetachBoxPage(w http.ResponseWriter, r *http.Request
back("err", "No such box.")
return
}
+ // The drain rule, as handleAPIFleetDetachBox asks it.
+ unlock := s.lockFleet(fleet.Name)
+ defer unlock()
+ held, err := s.detachHeld(r.Context(), fleet.Name, *box)
+ if err != nil {
+ log.Printf("console: fleet detach %s/%s/%s: heartbeat: %v", acct.Sqid, fleet.Name, label, err)
+ back("err", "Could not read what the box reports. Try again.")
+ return
+ }
+ if held {
+ back("err", msgDetachNotDrained(fleet.Name, label))
+ return
+ }
if err := reg.SetFleetBoxStatus(fleet.Name, label, "detached"); err != nil {
log.Printf("console: fleet detach %s/%s/%s: %v", acct.Sqid, fleet.Name, label, err)
back("err", "Could not detach the box — try again.")
diff --git a/internal/console/jobs.go b/internal/console/jobs.go
index 0635943e8..c6656cc7e 100644
--- a/internal/console/jobs.go
+++ b/internal/console/jobs.go
@@ -299,6 +299,7 @@ var jobLabels = map[string]string{
"StartLifetimeRecoveryPass": "Lifetime recovery",
"StartIncarnationMigrationPass": "Incarnation migration",
"StartEgressReport": "Outbound transfer report",
+ "FleetRelabel": "Fleet box placement",
}
// The job status words (OPS-80 to OPS-82).
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index c9b17d3a8..5ad6368fe 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -66,6 +66,7 @@ var jobPassFuncs = map[string][]string{
"StartEgressReport": {"egressReportPass"},
"ReportApexSquats": {"apexSquats"},
"LogPlacementDiscrepancies": {"logPlacementDiscrepancies"},
+ "FleetRelabel": {"fleetRelabelPass", "relabelFleet", "planFirstLabelling", "writeRelabels"},
}
// TestJobRegistryRecordsRuns pins the registry's bookkeeping (not
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 7e95bdbcb..d67eaac33 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -163,6 +163,7 @@ var closedDoors = []string{
"POST /api/cli/fleets/{account}/{fleet}/boxes",
"POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate",
"POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach",
+ "POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/drain",
"POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags",
// Setting a fleet's secrets key decides who can read the fleet's future
// secrets. Same cut, and owner-gated inside.
@@ -1134,8 +1135,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 73 {
- t.Errorf("walked %d closed doors, want all %d (and 73 today: 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, six fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
+ if seen != len(closedDoors) || seen != 74 {
+ t.Errorf("walked %d closed doors, want all %d (and 74 today: 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 fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index f750d19fb..2a41521f9 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -278,6 +278,7 @@ route POST /api/cli/billing/problems/{id}/close
route POST /api/cli/fleets/{account}/new
route POST /api/cli/fleets/{account}/{fleet}/boxes
route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach
+route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/drain
route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/rotate
route POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/tags
route POST /api/cli/ops/hosts/{host}/resolve
@@ -329,6 +330,7 @@ route PUT /api/cli/apps/{account}/{app}/version-target
route PUT /api/cli/fleets/{account}/{fleet}/secrets-key
route PUT /api/cli/system/geoip
route PUT /api/cli/system/upload
+worker FleetRelabel
worker LogPlacementDiscrepancies
worker PublishMovesConsole
worker PublishPlansMarker
diff --git a/internal/console/view.go b/internal/console/view.go
index 233b9986d..0e2a557a4 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -538,6 +538,8 @@ type consoleRegistry interface {
SetFleetBoxToken(string, string, string) error
SetFleetBoxTags(string, string, string) error
SetFleetBoxStatus(string, string, string) error
+ SetFleetBoxDraining(fleet, label string, since int64) (int64, error)
+ MarkFleetBoxLabelled(fleet, label string, at int64) error
}
var (