Managed fleets 1b: detach needs the machine gone; heartbeat drain evidence removed (Paul's option 2, branch review R1)
Rule 5 as revised 2026-10-31: drain moves, detach needs the machine gone. - Both detach doors: a box that ever held labelled records (labelled_at) is detached only with terminated: true (API field; the page form's Machine terminated checkbox; carlos fleets detach-box --terminated). Without it the doors refuse and say to drain first and detach with the confirmation once the machine is gone. A box never labelled detaches as before. The fleet lock around detach stays; carlos fleets drain is unchanged. - Removed: drainDone, drainSkewMargin, readFleetBoxBeat and their tests (P1-2 and P1-3 go away with them). - Removed Task 6a's box machinery that only fed the old rule: the heartbeat fields leases_held and replication_failures, the durable awake and failed-sync records and their writes and clears, the wake refusal when an awake record cannot be written, lease.FinalSyncError, Held.Holding, the finalCheckpointBudget seam, internal/host's drainReport, and their tests. Kept: the lease identity seams Task 7 uses (ExecBackend.LeaseIdentity, LeaseTTL, lease.AcquireAs). - Task 7's e2e drain step: refused without terminated, then detached with terminated after pi-2 drops its rows and releases the lease. - P2-1: labelsPausedFor keeps joinBeats' unheard: an active box with no report gives unknown; a box observed below the floor still gives paused (TestLabelsPausedIsUnknownWhenABoxHasNoReport). - P2-2: a labelled fleet down to one active box still has its heartbeats read, so a rollback below the floor pauses and alerts; new activation still needs two boxes (TestOneBoxLabelledFleetStillAlertsOnRollback). - docs/site/cli.md: drain, terminate, detach --terminated; the heartbeat-evidence text and the leaked-key advice rewritten.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
27 files changed,
+318
−1,837
apimode.go+8 −3docs/site/cli.md+14 −12fleets.go+11 −10fleets_cli_test.go+24 −3internal/activator/activator.go+2 −24internal/activator/backend_exec.go+0 −13internal/activator/drainreport.go+0 −511internal/activator/drainreport_linux_test.go+0 −38internal/activator/drainreport_test.go+0 −495internal/activator/maintenance.go+1 −5internal/activator/opset.go+0 −3internal/console/apiinstances.go+2 −1internal/console/fleetbox.go+18 −4internal/console/fleetrelabel.go+30 −77internal/console/fleetrelabel_test.go+160 −136internal/console/fleets.go+16 −20internal/console/templates/fleetdetail.html+1 −0internal/host/agent.go+0 −5internal/host/drainreport.go+0 −35internal/host/drainreport_test.go+0 −167internal/host/fleettwobox_e2e_test.go+12 −22internal/lease/finalsync.go+0 −37internal/lease/finalsync_test.go+0 −158internal/lease/lease.go+1 −4internal/registry/fleets.go+2 −2internal/status/contract_test.go+3 −15internal/status/snapshot.go+13 −37
diff --git a/apimode.go b/apimode.go| index 386543c8b..0c364f827 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -5231,10 +5231,15 @@ func (s *apiSession) tagFleetBox(ctx context.Context, a apiAcct, fleet, label, t |
| // detachFleetBox flips a box to "detached" — the hard revocation rotation is |
| // not: the edge closes an already-connected channel too |
| -// (handleAPIFleetDetachBox). `carlos fleets detach-box`. |
| -func (s *apiSession) detachFleetBox(ctx context.Context, a apiAcct, fleet, label string) error { |
| +// (handleAPIFleetDetachBox). `carlos fleets detach-box`. terminated confirms |
| +// the box's machine is gone, which a box that has run instances needs |
| +// (managed fleets 1b, rule 5). |
| +func (s *apiSession) detachFleetBox(ctx context.Context, a apiAcct, fleet, label string, terminated bool) error { |
| + in := struct { |
| + Terminated bool `json:"terminated,omitempty"` |
| + }{terminated} |
| status, body, err := s.postJSON(ctx, |
| - fleetPath(a, "/"+url.PathEscape(fleet)+"/boxes/"+url.PathEscape(label)+"/detach"), struct{}{}) |
| + fleetPath(a, "/"+url.PathEscape(fleet)+"/boxes/"+url.PathEscape(label)+"/detach"), in) |
| if err != nil { |
| return err |
| } |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index e7c26ecda..3043e3594 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2151,15 +2151,16 @@ 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. A box that has run instances needs a drain first, as the next |
| -section says. |
| +stops it. A box that has run instances is detached only once its machine is |
| +terminated, 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: |
| +runs on. To take a box out, drain it, terminate its machine, then detach it: |
| ```sh |
| carlos fleets drain acme pi-1 |
| -carlos fleets detach-box acme pi-1 |
| +# once its instances have moved, terminate the machine |
| +carlos fleets detach-box --terminated acme pi-1 |
| ``` |
| `drain` moves every instance assigned to the box to the fleet's other boxes |
| @@ -2169,13 +2170,14 @@ is ready for it, when the platform does not manage its process, or when the |
| console has not placed it on a box yet. The box keeps its access while its |
| instances leave, so it can stop them and upload their final 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 can still move to other boxes, but it cannot be |
| -detached until it reports again. A box that has never run an instance detaches |
| -at once. |
| +`--terminated` tells the console that the box's machine is gone. The console |
| +cannot check for itself that a box has uploaded everything, so it detaches a |
| +box that has run instances only with this flag. Without it the command refuses |
| +and says to drain first. Drain before you terminate the machine: writes the |
| +box never uploaded are lost with it. A box that has gone silent is detached the |
| +same way once you know its machine is gone. Its instances move to other boxes |
| +on their own. A box that has never run an instance detaches at once, without |
| +the flag. On the fleet page, tick Machine terminated before you press Detach. |
| 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 |
| @@ -2195,7 +2197,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, take the box off the fleet first. A box that has never run an instance can be detached at once with `carlos fleets detach-box <fleet> <label>`. Otherwise drain it with `carlos fleets drain <fleet> <label>`, then detach it when its report shows no instances, no held leases and no failed final uploads. Rotate the credentials after detaching. 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. |
| +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 has never run an instance can be detached at once with `carlos fleets detach-box <fleet> <label>`. Otherwise drain it with `carlos fleets drain <fleet> <label>`, terminate its machine once its instances have moved, then detach it with `carlos fleets detach-box --terminated <fleet> <label>`. Rotate the credentials after detaching. 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/fleets.go b/fleets.go| index 45fb3f944..e0bd7da48 100644 |
| --- a/fleets.go |
| +++ b/fleets.go |
| @@ -74,17 +74,17 @@ const fleetsUsage = `usage: carlos fleets <create|add-box|rotate-token|tag-box|d |
| 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 no instances, no held leases and |
| - no failed final uploads. |
| + access while its instances leave. once they have moved, |
| + terminate its machine and detach it with |
| + detach-box --terminated. |
| - detach-box [--account <sqid|name>] <fleet> <label> |
| + detach-box [--terminated] [--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. a box that ever ran instances the |
| - console placed on it is detached only after a drain, once |
| - the box reports no instances, no held leases and no failed |
| - final uploads. |
| + console placed on it is detached only with --terminated, |
| + which confirms its machine is gone. drain it before you |
| + terminate the machine. writes it never uploaded are lost. |
| secrets-key [--account <sqid|name>] [--file <path>] <fleet> [<pubkey>] |
| register the public half of the fleet's secrets key. every secret |
| @@ -381,7 +381,7 @@ func runFleetsDrain(args []string) { |
| 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 no instances, no held leases and no failed final uploads, detach it: carlos fleets detach-box %s %s\n", fleet, label) |
| + fmt.Fprintf(stdout, " once they have moved, terminate its machine and detach it: carlos fleets detach-box --terminated %s %s\n", fleet, label) |
| } |
| func runFleetsDetachBox(args []string) { |
| @@ -389,10 +389,11 @@ func runFleetsDetachBox(args []string) { |
| 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 detach through (default: the only logged-in one)") |
| + terminated := fs.Bool("terminated", false, "confirm that the box's machine is terminated. a box that has run instances is detached only with this") |
| fs.Usage = flagUsage(fs, "") |
| fs.Parse(args) |
| if fs.NArg() != 2 { |
| - log.Fatal("usage: carlos fleets detach-box [--account <sqid|name>] [--account-id <sqid>] " + |
| + log.Fatal("usage: carlos fleets detach-box [--terminated] [--account <sqid|name>] [--account-id <sqid>] " + |
| "[--console <origin>] <fleet> <label>") |
| } |
| fleet, label := strings.TrimSpace(fs.Arg(0)), strings.TrimSpace(fs.Arg(1)) |
| @@ -406,7 +407,7 @@ func runFleetsDetachBox(args []string) { |
| sess := fleetsSignedInSession(*consoleFlag) |
| fmt.Fprintf(stdout, "using %s as %s\n", sess.console, sess.address) |
| acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| - if err := sess.detachFleetBox(context.Background(), acct, fleet, label); err != nil { |
| + if err := sess.detachFleetBox(context.Background(), acct, fleet, label, *terminated); err != nil { |
| log.Fatalf("fleets detach-box: %v", err) |
| } |
| fmt.Fprintf(stdout, "detached %s/%s — its next dial-in is refused and any live channel is closed\n", fleet, label) |
diff --git a/fleets_cli_test.go b/fleets_cli_test.go| index 7844afe9d..f754e3e1e 100644 |
| --- a/fleets_cli_test.go |
| +++ b/fleets_cli_test.go |
| @@ -23,6 +23,7 @@ package main |
| import ( |
| "context" |
| "encoding/json" |
| + "io" |
| "net/http" |
| "net/http/httptest" |
| "os" |
| @@ -198,7 +199,7 @@ func TestAPISessionFleetAddBoxRotateDetach(t *testing.T) { |
| } |
| step = "detach" |
| - if err := s.detachFleetBox(context.Background(), acct, "acme", "pi-1"); err != nil { |
| + if err := s.detachFleetBox(context.Background(), acct, "acme", "pi-1", false); err != nil { |
| t.Fatalf("detachFleetBox: %v", err) |
| } |
| if gotPath != "/api/cli/fleets/bab/acme/boxes/pi-1/detach" { |
| @@ -223,7 +224,7 @@ func TestAPISessionFleetDoorsSurfaceServerErrors(t *testing.T) { |
| if _, err := s.rotateFleetBoxToken(context.Background(), acct, "ghost", "x"); err == nil { |
| t.Fatal("rotateFleetBoxToken against a 404 must error") |
| } |
| - if err := s.detachFleetBox(context.Background(), acct, "ghost", "x"); err == nil { |
| + if err := s.detachFleetBox(context.Background(), acct, "ghost", "x", false); err == nil { |
| t.Fatal("detachFleetBox against a 404 must error") |
| } |
| if err := s.tagFleetBox(context.Background(), acct, "ghost", "x", "office"); err == nil { |
| @@ -338,6 +339,7 @@ type fakeFleetsConsole struct { |
| lastCreatePlace atomic.Value // string |
| lastPlaceTarget atomic.Value // string |
| lastDetachPath atomic.Value // string |
| + lastDetachBody atomic.Value // string |
| lastDrainPath atomic.Value // string |
| lastTagPath atomic.Value // string |
| lastTagBody atomic.Value // string |
| @@ -386,6 +388,8 @@ func newFakeFleetsConsole(t *testing.T) *fakeFleetsConsole { |
| }) |
| mux.HandleFunc("POST /api/cli/fleets/{account}/{fleet}/boxes/{label}/detach", func(w http.ResponseWriter, r *http.Request) { |
| fc.lastDetachPath.Store(r.URL.Path) |
| + body, _ := io.ReadAll(r.Body) |
| + fc.lastDetachBody.Store(strings.TrimSpace(string(body))) |
| 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) { |
| @@ -552,6 +556,23 @@ func TestRunFleetsDetachBoxHitsRightPath(t *testing.T) { |
| if !strings.Contains(buf.String(), "detached acme/pi-1") { |
| t.Fatalf("stdout = %q, want it to confirm the detach", buf.String()) |
| } |
| + if got := fc.lastDetachBody.Load(); got != "{}" { |
| + t.Fatalf("detach body without --terminated = %v, want {}", got) |
| + } |
| +} |
| + |
| +// TestRunFleetsDetachBoxTerminated: --terminated sends the confirmation the |
| +// console needs to detach a box that has run instances (managed fleets 1b, |
| +// rule 5). |
| +func TestRunFleetsDetachBoxTerminated(t *testing.T) { |
| + fc := fleetsCLIFixture(t) |
| + captureStdout(t) |
| + |
| + RunFleets([]string{"detach-box", "--terminated", "-account", "bab", "acme", "pi-1"}) |
| + |
| + if got := fc.lastDetachBody.Load(); got != `{"terminated":true}` { |
| + t.Fatalf("detach body with --terminated = %v, want {\"terminated\":true}", got) |
| + } |
| } |
| // TestRunFleetsDrainHitsRightPath: `carlos fleets drain` reaches the drain |
| @@ -566,7 +587,7 @@ func TestRunFleetsDrainHitsRightPath(t *testing.T) { |
| 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") { |
| + if !strings.Contains(out, "draining acme/pi-1") || !strings.Contains(out, "carlos fleets detach-box --terminated acme pi-1") { |
| t.Fatalf("stdout = %q, want the drain confirmed and the detach step named", out) |
| } |
| } |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index f8ca90ed2..53b15d179 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -2743,16 +2743,6 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| } |
| w.steps.mark(a.now(), "identity") |
| - // 2c. The host's awake record (drainreport.go), durable before the |
| - // seed or the spawn can write its database: an agent that dies while |
| - // the host is awake leaves no final sync, and only this record tells |
| - // the box's heartbeat that writes may be missing from the bucket. A |
| - // record that cannot be written refuses the wake, nothing having run. |
| - if err := a.noteUnsynced(rt, lease); err != nil { |
| - w.stopOutcome.leaseReleased = a.giveBack(ctx, host, lease) |
| - return w, fmt.Errorf("start %s: refusing to start: %w", host, err) |
| - } |
| - |
| // 3. First-boot seed, strictly between the restore and the spawn — so it |
| // runs before Start's first health probe, and a brand-new instance is born |
| // seeded rather than briefly serving an empty database. fresh is the |
| @@ -2996,6 +2986,7 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| } |
| w.steps.mark(a.now(), "settle") |
| } |
| + |
| if ctx.Err() != nil || !a.wakeAllowed(host) { |
| a.cleanupFailedWake(ctx, e, rt, w, lease) |
| return w, ErrFenced |
| @@ -4842,11 +4833,6 @@ func (a *Service) retryPendingStop(e *actEntry) { |
| a.mu.Unlock() |
| } |
| -// finalCheckpointBudget is finishStop's budget for the final checkpoint |
| -// and lease release. A seam, so a test's refused final sync gives up |
| -// promptly; production never changes it. |
| -var finalCheckpointBudget = 30 * time.Second |
| - |
| // finishStop is stop()'s (and finishPendingStop's) tail: the final |
| // checkpoint, lease release, and forgetting the entry. Split out (design |
| // §6.3, codex R2-5) so a pendingStop entry's eventual finish shares it with |
| @@ -4897,7 +4883,7 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| // Close = final sync + lease release. After a lost lease the release part |
| // fails harmlessly (someone else owns the lock); the sync still preserves |
| // a local checkpoint. |
| - ctx, cancel := context.WithTimeout(context.Background(), finalCheckpointBudget) |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer cancel() |
| repErr := ErrStopUnproven |
| if _, ha := haEntryRep(e); ha { |
| @@ -4920,14 +4906,6 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| if repErr != nil { |
| log.Printf("activator: final checkpoint %s: %v", e.host, repErr) |
| } |
| - // A legacy release ran a final sync (the replica's Close): its outcome |
| - // is the host's replication records, written or cleared before the |
| - // entry goes (drainreport.go). No sync ran without a replica, so |
| - // nothing is recorded then. An HA host keeps no records at all |
| - // (controller ruling, Task 6a review: HA hosts are outside 1b's moves). |
| - if _, ha := haEntryRep(e); !ha && e.rep != nil { |
| - a.noteFinalReplication(e.host, repErr) |
| - } |
| a.mu.Lock() |
| outcome.uncertain = !outcome.complete() |
| e.stopOutcome = outcome |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index f7ec623eb..212525d36 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -366,9 +366,6 @@ type ExecBackend struct { |
| sameBox sameBoxState |
| // haWakes is each host's last Acquire classification (hawake.go). |
| haWakes haWakes |
| - // drain is the drain rule's box facts (drainreport.go): the leases |
| - // Acquire handed out, and the replication failure records' lock. |
| - drain drainState |
| // entryFiles is the Service's lookup of an awake entry's files |
| // publisher (hasecrets.go), installed by New. Nil: none. |
| entryFiles func(host string) *hostFiles |
| @@ -789,9 +786,6 @@ func (b *ExecBackend) Acquire(ctx context.Context, rt registry.Route) (Lease, er |
| l, err := b.acquireClassified(ctx, rt) |
| if err == nil { |
| markAcquiredHere(b, rt.Host) |
| - // Counted in the heartbeat's leases_held until it stops holding |
| - // (drainreport.go). |
| - b.trackHeld(rt.Host, l) |
| } |
| return l, err |
| } |
| @@ -996,13 +990,6 @@ func (b *ExecBackend) restorePlain(ctx context.Context, rt registry.Route) (bool |
| if err := b.establishAssignment(rt, dbPath); err != nil { |
| return false, err |
| } |
| - // The copy that runs is the bucket's now, so an earlier failed |
| - // final sync of the host on this box no longer stands between |
| - // the box and a drain (drainreport.go). A record that cannot be |
| - // removed stays: the box keeps reporting it. |
| - if err := b.clearFailedFinalSync(host); err != nil { |
| - log.Printf("activator: %s: restored from the bucket, but its earlier final sync failure record could not be cleared: %v", host, err) |
| - } |
| } else { |
| // Never replicated: a brand-new instance boots fresh and creates its |
| // own DB — the register-only create path (provisioning as a metadata |
diff --git a/internal/activator/drainreport.go b/internal/activator/drainreport.go| deleted file mode 100644 |
| index c67899b61..000000000 |
| --- a/internal/activator/drainreport.go |
| +++ /dev/null |
| @@ -1,511 +0,0 @@ |
| -package activator |
| - |
| -// The drain rule's box facts (managed fleets 1b, rule 5; Task 6a). A fleet |
| -// box is drained only when it has stopped everything AND its last writes |
| -// reached the bucket, so its heartbeat reports two counts, both read here |
| -// and neither costing a bucket request: |
| -// |
| -// - LeasesHeld: the instance leases this process holds right now, every |
| -// lease ExecBackend.Acquire handed out whose renewer still runs |
| -// (lease.Held.Holding), through Replicate and until the release, the |
| -// replicator's Close or Abandon stops it. |
| -// - ReplicationFailures: the hosts whose last local writes are not known |
| -// to be in the bucket, from two durable records per host in |
| -// <DataDir>/.replication-failures/, each written through writeDurable: |
| -// - <host>.unsynced, written at every wake once the lease is held and |
| -// before the seed or the spawn, so before anything of the host can |
| -// write its database (controller ruling, Task 6a). It covers an agent |
| -// that dies while the host is awake: there is then no stop and no |
| -// final sync, and only the record says so. It counts only while this |
| -// process does not hold the host's lease (an awake, held host is |
| -// LeasesHeld's). |
| -// - <host>.json, written when a release reports a failed final sync |
| -// while the lease was released anyway (lease.Replicator.Close releases |
| -// whatever the sync did). It counts whatever is held. |
| -// A host counts once, whichever records it has. Both are removed when a |
| -// later final sync of the host on this box lands or the host is |
| -// restored fresh from the bucket here. They survive an agent restart; |
| -// nothing else removes them. |
| -// |
| -// Both counts come from one snapshot (drainSnapshot): one capture of the |
| -// held leases decides both, so a host taking its lease mid-read is counted |
| -// once, never in neither. Without an activator the agent counts the |
| -// directory itself (CountReplicationRecords): every record, since no lease |
| -// can be held. |
| -// |
| -// HA hosts keep no records (controller ruling, Task 6a review: HA hosts are |
| -// outside 1b's move machinery, and Task 6b refuses to label or drain them): |
| -// nothing is written for an HA wake, stop, failed wake or restore, and a |
| -// record of a host the box now classifies HA is not counted. |
| -// |
| -// A wake whose unsynced record cannot be written is refused before anything |
| -// runs, the lease given back. A failed-sync record that cannot be written |
| -// is logged loudly and changes nothing else: the stop, the lease release |
| -// and the entry's removal are exactly as they were. The records are |
| -// evidence for the drain, not a lock. |
| - |
| -import ( |
| - "encoding/json" |
| - "errors" |
| - "fmt" |
| - "log" |
| - "os" |
| - "path/filepath" |
| - "strings" |
| - "sync" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/lease" |
| - "github.com/carlosframework/platform/internal/registry" |
| -) |
| - |
| -// ReplicationFailuresDir is the directory under the box's DataDir that |
| -// holds one record per host whose final sync failed. |
| -const ReplicationFailuresDir = ".replication-failures" |
| - |
| -// failedSyncSuffix names a host's failed-final-sync record in |
| -// ReplicationFailuresDir, and unsyncedSuffix its awake record. |
| -const ( |
| - failedSyncSuffix = ".json" |
| - unsyncedSuffix = ".unsynced" |
| -) |
| - |
| -// failedSyncErrMax bounds the error text a record keeps. |
| -const failedSyncErrMax = 1024 |
| - |
| -// failedSyncRecord is a record's content, for an operator reading it. Only |
| -// the file's presence counts. |
| -type failedSyncRecord struct { |
| - Host string `json:"host"` |
| - FailedAt time.Time `json:"failed_at"` |
| - Error string `json:"error"` |
| -} |
| - |
| -// unsyncedRecord is an awake record's content, for an operator reading it. |
| -type unsyncedRecord struct { |
| - Host string `json:"host"` |
| - WokenAt time.Time `json:"woken_at"` |
| -} |
| - |
| -// drainState is ExecBackend's share of the drain facts: the leases it has |
| -// handed out, with their hosts (pruned as they stop holding), and the lock |
| -// that serialises the records' writes. |
| -type drainState struct { |
| - mu sync.Mutex |
| - held map[*lease.Held]string |
| - rec sync.Mutex |
| -} |
| - |
| -// trackHeld remembers a lease Acquire handed out for host, forgetting |
| -// those that no longer hold, so the set stays the size of what is held on |
| -// a box whose heartbeat never asks. |
| -func (b *ExecBackend) trackHeld(host string, l Lease) { |
| - el, ok := l.(*execLease) |
| - if !ok || el.held == nil { |
| - return |
| - } |
| - b.drain.mu.Lock() |
| - defer b.drain.mu.Unlock() |
| - if b.drain.held == nil { |
| - b.drain.held = map[*lease.Held]string{} |
| - } |
| - b.pruneHeldLocked() |
| - b.drain.held[el.held] = host |
| -} |
| - |
| -// heldLeases counts the leases Acquire handed out that still hold. |
| -func (b *ExecBackend) heldLeases() int { |
| - b.drain.mu.Lock() |
| - defer b.drain.mu.Unlock() |
| - return len(b.pruneHeldLocked()) |
| -} |
| - |
| -// pruneHeldLocked forgets the tracked leases that no longer hold and |
| -// returns the hosts of those that do, one entry per held lease. Under |
| -// drain.mu. |
| -func (b *ExecBackend) pruneHeldLocked() []string { |
| - var hosts []string |
| - for h, host := range b.drain.held { |
| - if h.Holding() { |
| - hosts = append(hosts, host) |
| - } else { |
| - delete(b.drain.held, h) |
| - } |
| - } |
| - return hosts |
| -} |
| - |
| -// failedSyncDir is <DataDir>/.replication-failures. The DataDir is the |
| -// agent's own root, never a tenant's instance directory. |
| -func (b *ExecBackend) failedSyncDir() (string, error) { |
| - if b.DataDir == "" || !filepath.IsAbs(b.DataDir) { |
| - return "", fmt.Errorf("no absolute data directory to keep replication failures under (%q)", b.DataDir) |
| - } |
| - return filepath.Join(filepath.Clean(b.DataDir), ReplicationFailuresDir), nil |
| -} |
| - |
| -// failedSyncName is host's failed-sync record name, refusing a host that |
| -// is not one file name; the awake record is the same with unsyncedSuffix. |
| -func failedSyncName(host string) (string, error) { |
| - if host == "" || host == "." || host == ".." || strings.HasPrefix(host, ".") || strings.ContainsAny(host, `/\`) { |
| - return "", fmt.Errorf("%q is not a host a replication failure can be filed under", host) |
| - } |
| - return host + failedSyncSuffix, nil |
| -} |
| - |
| -// writeRecordLocked writes name in the record directory durably: the |
| -// directory created and its parent synced, then the record through |
| -// writeDurable (temp file, fsync, rename, directory fsync). Under |
| -// drain.rec. |
| -func writeRecordLocked(dir, name string, v any) error { |
| - body, err := json.MarshalIndent(v, "", " ") |
| - if err != nil { |
| - return err |
| - } |
| - if err := os.MkdirAll(dir, 0o700); err != nil { |
| - return err |
| - } |
| - if err := durableSync(filepath.Dir(dir)); err != nil { |
| - return fmt.Errorf("sync %s: %w", filepath.Dir(dir), err) |
| - } |
| - return writeDurable(dir, name, append(body, '\n')) |
| -} |
| - |
| -// drainSnapshotHook, when set, runs at the snapshot's two points: "before" |
| -// the held leases are captured and "held" after, before the records are |
| -// read. Test-only: it makes the interleaving with a wake deterministic. |
| -var drainSnapshotHook func(point string) |
| - |
| -// drainSnapshot is both drain facts from one capture of the held leases: |
| -// how many are held, and how many hosts have records, an awake record |
| -// counting only for a host not in that capture. A record of a host this |
| -// box classifies HA is not counted (knownHA). The error is the records' |
| -// read: the leases are always known. |
| -func (b *ExecBackend) drainSnapshot() (leases, failures int, err error) { |
| - if h := drainSnapshotHook; h != nil { |
| - h("before") |
| - } |
| - b.drain.mu.Lock() |
| - heldHosts := b.pruneHeldLocked() |
| - b.drain.mu.Unlock() |
| - held := map[string]bool{} |
| - for _, h := range heldHosts { |
| - held[h] = true |
| - } |
| - if h := drainSnapshotHook; h != nil { |
| - h("held") |
| - } |
| - dir, err := b.failedSyncDir() |
| - if err != nil { |
| - return len(heldHosts), 0, err |
| - } |
| - hosts, err := readRecordHosts(dir, held, &b.drain.rec) |
| - if err != nil { |
| - return len(heldHosts), 0, err |
| - } |
| - n := 0 |
| - for h := range hosts { |
| - if !b.knownHA(h) { |
| - n++ |
| - } |
| - } |
| - return len(heldHosts), n, nil |
| -} |
| - |
| -// knownHA reports whether this box classifies host HA, by the sticky marks |
| -// only (the lifetime index, the registry row): no record read, no request. |
| -func (b *ExecBackend) knownHA(host string) bool { |
| - if b.Lifetimes != nil { |
| - if e, ok := b.Lifetimes.Lookup(host); ok && e.HA { |
| - return true |
| - } |
| - } |
| - if b.Registry != nil { |
| - if rt, err := b.Registry.Get(host); err == nil && rt != nil && rt.HA { |
| - return true |
| - } |
| - } |
| - return false |
| -} |
| - |
| -// readRecordHosts lists the hosts with records in dir: every <host>.json, |
| -// and every <host>.unsynced whose host is not in held; never a temp file |
| -// (WriteAtomic's start with a dot). No directory is none; any other read |
| -// failure is returned, never "none". mu, when set, is held for the read. |
| -func readRecordHosts(dir string, held map[string]bool, mu *sync.Mutex) (map[string]bool, error) { |
| - if mu != nil { |
| - mu.Lock() |
| - defer mu.Unlock() |
| - } |
| - ents, err := os.ReadDir(dir) |
| - if errors.Is(err, os.ErrNotExist) { |
| - return nil, nil |
| - } |
| - if err != nil { |
| - return nil, err |
| - } |
| - hosts := map[string]bool{} |
| - for _, e := range ents { |
| - name := e.Name() |
| - if strings.HasPrefix(name, ".") { |
| - continue |
| - } |
| - if host, ok := strings.CutSuffix(name, failedSyncSuffix); ok { |
| - hosts[host] = true |
| - } else if host, ok := strings.CutSuffix(name, unsyncedSuffix); ok && !held[host] { |
| - hosts[host] = true |
| - } |
| - } |
| - return hosts, nil |
| -} |
| - |
| -// CountReplicationRecords counts the hosts with a replication record under |
| -// dataDir, for an agent with no activator: no lease can be held, so every |
| -// awake and failed record counts, each host once. A dataDir that is not |
| -// absolute, or a directory that cannot be read, is an error, never "none". |
| -func CountReplicationRecords(dataDir string) (int, error) { |
| - if dataDir == "" || !filepath.IsAbs(dataDir) { |
| - return 0, fmt.Errorf("no absolute data directory to read replication records under (%q)", dataDir) |
| - } |
| - hosts, err := readRecordHosts(filepath.Join(filepath.Clean(dataDir), ReplicationFailuresDir), nil, nil) |
| - return len(hosts), err |
| -} |
| - |
| -// noteUnsynced writes host's awake record durably, before anything of the |
| -// host can write its database. A later wake replaces it. A backend with no |
| -// absolute data directory keeps no records at all: the wake goes ahead as |
| -// today, and its count is an error, so the heartbeat reports at least 1 |
| -// and such a box never reads as drained. |
| -func (b *ExecBackend) noteUnsynced(rt registry.Route) error { |
| - name, err := failedSyncName(rt.Host) |
| - if err != nil { |
| - return err |
| - } |
| - dir, err := b.failedSyncDir() |
| - if err != nil { |
| - return nil |
| - } |
| - b.drain.rec.Lock() |
| - defer b.drain.rec.Unlock() |
| - return writeRecordLocked(dir, strings.TrimSuffix(name, failedSyncSuffix)+unsyncedSuffix, |
| - unsyncedRecord{Host: rt.Host, WokenAt: time.Now().UTC()}) |
| -} |
| - |
| -// noteFailedFinalSync writes host's record durably: the directory created |
| -// and its parent synced, then the record through writeDurable (temp file, |
| -// fsync, rename, directory fsync). A later failure of the same host |
| -// replaces it. |
| -func (b *ExecBackend) noteFailedFinalSync(host string, cause error) error { |
| - name, err := failedSyncName(host) |
| - if err != nil { |
| - return err |
| - } |
| - dir, err := b.failedSyncDir() |
| - if err != nil { |
| - return err |
| - } |
| - msg := "" |
| - if cause != nil { |
| - msg = cause.Error() |
| - } |
| - if len(msg) > failedSyncErrMax { |
| - msg = msg[:failedSyncErrMax] |
| - } |
| - b.drain.rec.Lock() |
| - defer b.drain.rec.Unlock() |
| - return writeRecordLocked(dir, name, failedSyncRecord{Host: host, FailedAt: time.Now().UTC(), Error: msg}) |
| -} |
| - |
| -// clearFailedFinalSync removes both of host's records, if it has any, and |
| -// syncs the directory after a removal. A backend with no absolute data |
| -// directory can have written no record, so there is nothing to clear. |
| -func (b *ExecBackend) clearFailedFinalSync(host string) error { |
| - name, err := failedSyncName(host) |
| - if err != nil { |
| - return err |
| - } |
| - dir, err := b.failedSyncDir() |
| - if err != nil { |
| - return nil |
| - } |
| - b.drain.rec.Lock() |
| - defer b.drain.rec.Unlock() |
| - removed := false |
| - for _, n := range []string{name, strings.TrimSuffix(name, failedSyncSuffix) + unsyncedSuffix} { |
| - if err := os.Remove(filepath.Join(dir, n)); err != nil { |
| - if errors.Is(err, os.ErrNotExist) { |
| - continue |
| - } |
| - return err |
| - } |
| - removed = true |
| - } |
| - if !removed { |
| - return nil |
| - } |
| - if err := durableSync(dir); err != nil { |
| - return fmt.Errorf("sync %s: %w", dir, err) |
| - } |
| - return nil |
| -} |
| - |
| -// failedFinalSyncs is drainSnapshot's failure count. |
| -func (b *ExecBackend) failedFinalSyncs() (int, error) { |
| - _, n, err := b.drainSnapshot() |
| - return n, err |
| -} |
| - |
| -// drainFacts is the backend half the Service reads the drain facts |
| -// through: ExecBackend's, and SplitBackend's dispatch to its exec half |
| -// (a unit-backed row takes no lease and replicates nothing). |
| -type drainFacts interface { |
| - heldLeases() int |
| - drainSnapshot() (leases, failures int, err error) |
| - noteUnsynced(rt registry.Route) error |
| - noteFailedFinalSync(host string, cause error) error |
| - clearFailedFinalSync(host string) error |
| - failedFinalSyncs() (int, error) |
| -} |
| - |
| -var ( |
| - _ drainFacts = (*ExecBackend)(nil) |
| - _ drainFacts = (*SplitBackend)(nil) |
| -) |
| - |
| -// errNoDrainFacts is a backend that keeps no record: it cannot answer |
| -// "no failures". |
| -var errNoDrainFacts = errors.New("this backend keeps no replication failure records") |
| - |
| -func (b *SplitBackend) execFacts() (drainFacts, bool) { |
| - f, ok := b.Exec.(drainFacts) |
| - return f, ok |
| -} |
| - |
| -func (b *SplitBackend) drainSnapshot() (int, int, error) { |
| - if f, ok := b.execFacts(); ok { |
| - return f.drainSnapshot() |
| - } |
| - return 0, 0, errNoDrainFacts |
| -} |
| - |
| -func (b *SplitBackend) heldLeases() int { |
| - if f, ok := b.execFacts(); ok { |
| - return f.heldLeases() |
| - } |
| - return 0 |
| -} |
| - |
| -// noteUnsynced dispatches on Backing: a unit-backed row takes no lease of |
| -// this backend's and replicates nothing, so it records nothing. An exec |
| -// half that keeps no records (a test double) records nothing either, as |
| -// Service.noteUnsynced treats such a backend; its count still answers |
| -// errNoDrainFacts, never "none". |
| -func (b *SplitBackend) noteUnsynced(rt registry.Route) error { |
| - if rt.Backing == registry.BackingUnit { |
| - return nil |
| - } |
| - if f, ok := b.execFacts(); ok { |
| - return f.noteUnsynced(rt) |
| - } |
| - return nil |
| -} |
| - |
| -func (b *SplitBackend) noteFailedFinalSync(host string, cause error) error { |
| - if f, ok := b.execFacts(); ok { |
| - return f.noteFailedFinalSync(host, cause) |
| - } |
| - return errNoDrainFacts |
| -} |
| - |
| -func (b *SplitBackend) clearFailedFinalSync(host string) error { |
| - if f, ok := b.execFacts(); ok { |
| - return f.clearFailedFinalSync(host) |
| - } |
| - return errNoDrainFacts |
| -} |
| - |
| -func (b *SplitBackend) failedFinalSyncs() (int, error) { |
| - if f, ok := b.execFacts(); ok { |
| - return f.failedFinalSyncs() |
| - } |
| - return 0, errNoDrainFacts |
| -} |
| - |
| -// DrainFacts is the heartbeat's two drain facts from one snapshot |
| -// (drainSnapshot): the instance leases this process holds right now, and |
| -// the hosts whose writes are not known to be in the bucket. err means the |
| -// failure count is unknown, never zero; leases is known either way. |
| -func (a *Service) DrainFacts() (leases, failures int, err error) { |
| - if f, ok := a.backend.(drainFacts); ok { |
| - return f.drainSnapshot() |
| - } |
| - return 0, 0, errNoDrainFacts |
| -} |
| - |
| -// LeasesHeld is how many instance leases this process holds right now |
| -// (the heartbeat's leases_held, which DrainFacts reads in the same |
| -// snapshot as the failures). A backend that takes no leases of its own |
| -// holds none. |
| -func (a *Service) LeasesHeld() int { |
| - if f, ok := a.backend.(drainFacts); ok { |
| - return f.heldLeases() |
| - } |
| - return 0 |
| -} |
| - |
| -// ReplicationFailures is DrainFacts' failure count alone: the hosts whose |
| -// writes on this box are not known to be in the bucket. An error means |
| -// the count is unknown, never zero. |
| -func (a *Service) ReplicationFailures() (int, error) { |
| - if f, ok := a.backend.(drainFacts); ok { |
| - return f.failedFinalSyncs() |
| - } |
| - return 0, errNoDrainFacts |
| -} |
| - |
| -// finalReplicationFailed reports whether a release's error says its final |
| -// sync failed: a legacy replicator's *lease.FinalSyncError. |
| -func finalReplicationFailed(err error) bool { |
| - var fs *lease.FinalSyncError |
| - return errors.As(err, &fs) |
| -} |
| - |
| -// noteUnsynced writes rt's awake record before anything of the host can |
| -// write (doWake, after the lease and the restore, before the seed and the |
| -// spawn). An error refuses the wake. A backend that keeps no records |
| -// (a test double) records nothing, and neither does an HA wake (its lease |
| -// or the row says HA): HA hosts keep no records. |
| -func (a *Service) noteUnsynced(rt registry.Route, l Lease) error { |
| - f, ok := a.backend.(drainFacts) |
| - if !ok || rt.HA || haHeld(l, nil) { |
| - return nil |
| - } |
| - if err := f.noteUnsynced(rt); err != nil { |
| - return fmt.Errorf("the record that it is awake could not be written: %w", err) |
| - } |
| - return nil |
| -} |
| - |
| -// noteFinalReplication records the outcome of a release that ran a final |
| -// sync of host (err is the release's error): a failed final sync is |
| -// recorded; any other outcome, a clean release or one that failed after |
| -// the sync landed (the lease delete, the marker), clears both records. |
| -// Never called with a.mu held: it touches the disk. |
| -func (a *Service) noteFinalReplication(host string, err error) { |
| - f, ok := a.backend.(drainFacts) |
| - if !ok { |
| - return |
| - } |
| - switch { |
| - case !finalReplicationFailed(err): |
| - if cerr := f.clearFailedFinalSync(host); cerr != nil { |
| - log.Printf("activator: %s: the final sync landed, but its replication records could not be cleared: %v (the box still reports them)", host, cerr) |
| - } |
| - case finalReplicationFailed(err): |
| - if nerr := f.noteFailedFinalSync(host, err); nerr != nil { |
| - log.Printf("activator: %s: FINAL SYNC FAILED and the failure could not be recorded: %v (its last writes may not be in the bucket; the box's heartbeat cannot report it)", host, nerr) |
| - } else { |
| - log.Printf("activator: %s: final sync failed; recorded until a later replication of it lands: %v", host, err) |
| - } |
| - } |
| -} |
diff --git a/internal/activator/drainreport_linux_test.go b/internal/activator/drainreport_linux_test.go| deleted file mode 100644 |
| index dd47538bb..000000000 |
| --- a/internal/activator/drainreport_linux_test.go |
| +++ /dev/null |
| @@ -1,38 +0,0 @@ |
| -//go:build linux |
| - |
| -package activator |
| - |
| -import ( |
| - "errors" |
| - "os" |
| - "testing" |
| -) |
| - |
| -// Linux only: it wakes through the start rule's harness (startrule_test.go). |
| -// A host restored fresh from the bucket on this box clears its record: the |
| -// copy whose writes did not reach the bucket is not the one that runs. A |
| -// warm wake (the same local copy) does not. |
| -func TestFreshRestoreClearsTheRecord(t *testing.T) { |
| - b := testExecBackend(t) |
| - rt := fleetUnlabelled(fleetRoute(b, "", false)) |
| - if err := b.noteFailedFinalSync(rt.Host, errors.New("x")); err != nil { |
| - t.Fatal(err) |
| - } |
| - writeUsableDB(t, rt.DBPath) |
| - replicaCalls(t, true) |
| - if _, err := wakeOn(t, b, rt, nil); err != nil { |
| - t.Fatalf("warm wake: %v", err) |
| - } |
| - if n, _ := b.failedFinalSyncs(); n != 1 { |
| - t.Fatalf("a warm wake cleared the record: %d", n) |
| - } |
| - if err := os.Remove(rt.DBPath); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, err := wakeOn(t, b, rt, nil); err != nil { |
| - t.Fatalf("restoring wake: %v", err) |
| - } |
| - if n, _ := b.failedFinalSyncs(); n != 0 { |
| - t.Fatalf("a fresh restore left the record: %d", n) |
| - } |
| -} |
diff --git a/internal/activator/drainreport_test.go b/internal/activator/drainreport_test.go| deleted file mode 100644 |
| index 3c5c4cda7..000000000 |
| --- a/internal/activator/drainreport_test.go |
| +++ /dev/null |
| @@ -1,495 +0,0 @@ |
| -package activator |
| - |
| -import ( |
| - "bytes" |
| - "context" |
| - "errors" |
| - "os" |
| - "path/filepath" |
| - "strings" |
| - "sync/atomic" |
| - "testing" |
| - "time" |
| - |
| - "github.com/carlosframework/platform/internal/lease" |
| - "github.com/carlosframework/platform/internal/registry" |
| -) |
| - |
| -// legacyService is haService for a host that is not HA: the real legacy |
| -// lease against the lock fixture and real litestream replication of the |
| -// host's database to the fixture, released by the replicator's Close |
| -// (finishStop's non-HA arm). The final checkpoint's budget is cut to two |
| -// seconds, so a refused final sync gives up promptly. |
| -func legacyService(t *testing.T, host string) *haSvc { |
| - t.Helper() |
| - s := haService(t, host) |
| - h := haFixOf(s.b) |
| - h.mu.Lock() |
| - h.records[host] = haRecord(host, false) |
| - h.mu.Unlock() |
| - s.b.Lifetimes = nil |
| - old := finalCheckpointBudget |
| - finalCheckpointBudget = 2 * time.Second |
| - t.Cleanup(func() { finalCheckpointBudget = old }) |
| - return s |
| -} |
| - |
| -// refuseReplicaPuts makes the fixture refuse every replica write under the |
| -// host's prefix while the returned switch is on (403: the SDK does not |
| -// retry it). The lock's own writes are never refused. |
| -func refuseReplicaPuts(s *haSvc) *atomic.Bool { |
| - var on atomic.Bool |
| - prefix := s.b.Cfg.hibernatePrefix(s.rt.Host) + "/" |
| - lock := s.lockKey() |
| - for i := 0; i < 5000; i++ { |
| - s.fx.FailNextMatching("PUT", 403, func(k string, _ []byte) bool { |
| - return on.Load() && strings.HasPrefix(k, prefix) && k != lock |
| - }) |
| - } |
| - return &on |
| -} |
| - |
| -func failures(t *testing.T, a *Service) int { |
| - t.Helper() |
| - n, err := a.ReplicationFailures() |
| - if err != nil { |
| - t.Fatalf("ReplicationFailures: %v", err) |
| - } |
| - return n |
| -} |
| - |
| -// The box half of TestDrainDoneNeedsNoFailedReplication (managed fleets |
| -// 1b, the drain rule): the final sync is refused but the lease is |
| -// released anyway, through the real lease and litestream. The box reports |
| -// one failure; a fresh agent over the same data directory still does; a |
| -// later replication of the host that succeeds clears it. |
| -func TestFailedFinalSyncIsReportedUntilReplicated(t *testing.T) { |
| - s := legacyService(t, "shop.example.com") |
| - refuse := refuseReplicaPuts(s) |
| - e, err := s.wakeForTest(context.Background()) |
| - if err != nil { |
| - t.Fatalf("wake: %v", err) |
| - } |
| - if _, ha := s.b.haAcquired(s.rt.Host); ha { |
| - t.Fatal("the host woke HA; this test is about the legacy release") |
| - } |
| - if n := s.a.LeasesHeld(); n != 1 { |
| - t.Fatalf("awake: LeasesHeld = %d, want 1", n) |
| - } |
| - if n := failures(t, s.a); n != 0 { |
| - t.Fatalf("awake: ReplicationFailures = %d, want 0", n) |
| - } |
| - if err := ensureDB(s.b.pathsFor(s.rt).dbPath); err != nil { |
| - t.Fatal(err) |
| - } |
| - refuse.Store(true) |
| - s.stopForTest(e) |
| - if !s.stoppedFor(e) { |
| - t.Fatal("the stop went pending; the final sync's failure must not hold the stop") |
| - } |
| - if body := s.fx.LockBody(s.b.Cfg.hibernatePrefix(s.rt.Host)); body != nil { |
| - t.Fatalf("the lease was not released after the failed final sync: %s", body) |
| - } |
| - if n := s.a.LeasesHeld(); n != 0 { |
| - t.Fatalf("stopped: LeasesHeld = %d, want 0", n) |
| - } |
| - if n := failures(t, s.a); n != 1 { |
| - t.Fatalf("after the failed final sync: ReplicationFailures = %d, want 1", n) |
| - } |
| - |
| - // The agent restarts: the record is on disk, not in memory. |
| - s2 := s.restart(t) |
| - if n := failures(t, s2.a); n != 1 { |
| - t.Fatalf("a fresh agent over the same data: ReplicationFailures = %d, want 1", n) |
| - } |
| - |
| - // The bucket takes writes again; the host wakes from its warm copy and |
| - // sleeps with a final sync that lands. |
| - refuse.Store(false) |
| - e2, err := s2.wakeForTest(context.Background()) |
| - if err != nil { |
| - t.Fatalf("second wake: %v", err) |
| - } |
| - if n := failures(t, s2.a); n != 1 { |
| - t.Fatalf("a warm wake cleared the record before anything replicated: %d", n) |
| - } |
| - s2.stopForTest(e2) |
| - if !s2.stoppedFor(e2) { |
| - t.Fatal("the second stop went pending") |
| - } |
| - if n := failures(t, s2.a); n != 0 { |
| - t.Fatalf("after a final sync that landed: ReplicationFailures = %d, want 0", n) |
| - } |
| - if n := s2.a.LeasesHeld(); n != 0 { |
| - t.Fatalf("after the second stop: LeasesHeld = %d, want 0", n) |
| - } |
| -} |
| - |
| -// A release whose final sync worked but whose lease delete did not is not |
| -// a replication failure: the writes are in the bucket. |
| -func TestFailedReleaseAloneIsNotAReplicationFailure(t *testing.T) { |
| - s := legacyService(t, "shop.example.com") |
| - e, err := s.wakeForTest(context.Background()) |
| - if err != nil { |
| - t.Fatalf("wake: %v", err) |
| - } |
| - s.fx.FailNextMatching("DELETE", 403, func(k string, _ []byte) bool { return k == s.lockKey() }) |
| - s.stopForTest(e) |
| - if n := failures(t, s.a); n != 0 { |
| - t.Fatalf("ReplicationFailures = %d, want 0", n) |
| - } |
| -} |
| - |
| -// The record: one durable file per host under the data directory, written |
| -// through writeDurable, counted, cleared, and never confused with a temp |
| -// file or anything else in the directory. |
| -func TestReplicationFailureRecord(t *testing.T) { |
| - b := testExecBackend(t) |
| - if n, err := b.failedFinalSyncs(); err != nil || n != 0 { |
| - t.Fatalf("no directory: %d, %v", n, err) |
| - } |
| - if err := b.noteFailedFinalSync("shop.example.com", errors.New("bucket said no")); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := b.noteFailedFinalSync("shop.example.com", errors.New("again")); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := b.noteFailedFinalSync("cafe.example.com", errors.New("bucket said no")); err != nil { |
| - t.Fatal(err) |
| - } |
| - dir := filepath.Join(b.DataDir, ReplicationFailuresDir) |
| - raw, err := os.ReadFile(filepath.Join(dir, "shop.example.com.json")) |
| - if err != nil || !bytes.Contains(raw, []byte(`"again"`)) || !bytes.Contains(raw, []byte(`"host": "shop.example.com"`)) { |
| - t.Fatalf("record: %s, %v", raw, err) |
| - } |
| - // A temp file left by an interrupted write and a stray file do not count. |
| - if err := os.WriteFile(filepath.Join(dir, ".x.json.tmp-0011"), nil, 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(filepath.Join(dir, "README"), nil, 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - if n, err := b.failedFinalSyncs(); err != nil || n != 2 { |
| - t.Fatalf("two hosts: %d, %v", n, err) |
| - } |
| - if err := b.clearFailedFinalSync("shop.example.com"); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := b.clearFailedFinalSync("shop.example.com"); err != nil { |
| - t.Fatalf("a second clear: %v", err) |
| - } |
| - if n, err := b.failedFinalSyncs(); err != nil || n != 1 { |
| - t.Fatalf("one host left: %d, %v", n, err) |
| - } |
| - for _, bad := range []string{"", ".", "..", "a/b", `a\b`} { |
| - if err := b.noteFailedFinalSync(bad, errors.New("x")); err == nil { |
| - t.Fatalf("host %q was filed", bad) |
| - } |
| - } |
| - // A directory that cannot be read is an error, never "none". |
| - b2 := testExecBackend(t) |
| - if err := os.WriteFile(filepath.Join(b2.DataDir, ReplicationFailuresDir), nil, 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, err := b2.failedFinalSyncs(); err == nil { |
| - t.Fatal("an unreadable record directory counted as none") |
| - } |
| - // No absolute data directory: nothing can be kept, and the count says so. |
| - b3 := testExecBackend(t) |
| - b3.DataDir = "" |
| - if _, err := b3.failedFinalSyncs(); err == nil { |
| - t.Fatal("a backend with no data directory counted none") |
| - } |
| - if err := b3.noteFailedFinalSync("shop.example.com", errors.New("x")); err == nil { |
| - t.Fatal("a backend with no data directory filed a record") |
| - } |
| - // Its wakes go ahead (no awake record can be kept), and the count stays |
| - // an error, so the box never reads as drained. |
| - if err := b3.noteUnsynced(fleetlessRoute("shop.example.com")); err != nil { |
| - t.Fatalf("a backend with no data directory refused the awake record: %v", err) |
| - } |
| -} |
| - |
| -// The record's write is durable: the directory is synced after the rename, |
| -// and a failed sync fails the write. |
| -func TestReplicationFailureRecordIsDurable(t *testing.T) { |
| - b := testExecBackend(t) |
| - dir := filepath.Join(b.DataDir, ReplicationFailuresDir) |
| - var synced []string |
| - old := durableSync |
| - durableSync = func(d string) error { |
| - synced = append(synced, d) |
| - if d == dir { |
| - return errors.New("synthetic sync failure") |
| - } |
| - return old(d) |
| - } |
| - t.Cleanup(func() { durableSync = old }) |
| - if err := b.noteFailedFinalSync("shop.example.com", errors.New("x")); err == nil { |
| - t.Fatal("a record whose directory would not sync was reported written") |
| - } |
| - if len(synced) < 2 || synced[0] != b.DataDir || synced[len(synced)-1] != dir { |
| - t.Fatalf("syncs %v: want the data directory (the record directory's creation), then the record directory", synced) |
| - } |
| -} |
| - |
| -// The Service reaches the record and the held leases through a |
| -// SplitBackend, as the agent wires it; a backend that keeps no record |
| -// cannot answer "none". |
| -func TestDrainFactsThroughTheSplitBackend(t *testing.T) { |
| - eb := testExecBackend(t) |
| - a := New(Config{Bucket: "test-bucket"}, &SplitBackend{Exec: eb, Unit: &UnitBackend{}}, nil) |
| - if err := eb.noteFailedFinalSync("shop.example.com", errors.New("x")); err != nil { |
| - t.Fatal(err) |
| - } |
| - if n, err := a.ReplicationFailures(); err != nil || n != 1 { |
| - t.Fatalf("ReplicationFailures = %d, %v", n, err) |
| - } |
| - if n := a.LeasesHeld(); n != 0 { |
| - t.Fatalf("LeasesHeld = %d", n) |
| - } |
| - fake := New(Config{Bucket: "test-bucket"}, &fakeBackend{}, nil) |
| - if _, err := fake.ReplicationFailures(); err == nil { |
| - t.Fatal("a backend with no record answered none") |
| - } |
| -} |
| - |
| -// Which release errors are a failed final replication: a legacy |
| -// replicator's *lease.FinalSyncError, however joined; never a failed lease |
| -// delete or marker alone. |
| -func TestFinalReplicationFailedClassifies(t *testing.T) { |
| - other := errors.New("marker PUT refused") |
| - for _, c := range []struct { |
| - err error |
| - want bool |
| - }{ |
| - {nil, false}, |
| - {other, false}, |
| - {ErrStopUnproven, false}, |
| - {&lease.FinalSyncError{Err: errors.New("sync")}, true}, |
| - {errors.Join(&lease.FinalSyncError{Err: errors.New("sync")}, other), true}, |
| - } { |
| - if got := finalReplicationFailed(c.err); got != c.want { |
| - t.Errorf("finalReplicationFailed(%v) = %v, want %v", c.err, got, c.want) |
| - } |
| - } |
| -} |
| - |
| -// The crash the stop never saw (controller ruling, Task 6a): the host is |
| -// woken and the agent dies without a stop, so there is no final sync and |
| -// no failure record. A fresh agent over the same data directory, holding |
| -// no lease of the host, reports 1 from the awake record alone. Once it |
| -// takes the host (the dead agent's lock expired), the held host is |
| -// LeasesHeld's, not a failure; a clean stop with a final sync that lands |
| -// leaves 0. |
| -func TestCrashWhileAwakeIsReported(t *testing.T) { |
| - s := legacyService(t, "shop.example.com") |
| - e, err := s.wakeForTest(context.Background()) |
| - if err != nil || e == nil { |
| - t.Fatalf("wake: %v", err) |
| - } |
| - if n := failures(t, s.a); n != 0 { |
| - t.Fatalf("awake and held: ReplicationFailures = %d, want 0", n) |
| - } |
| - if err := ensureDB(s.b.pathsFor(s.rt).dbPath); err != nil { |
| - t.Fatal(err) |
| - } |
| - prefix := s.b.Cfg.hibernatePrefix(s.rt.Host) |
| - owner := s.fx.LockOwner(prefix) |
| - |
| - // The crash: no stop, no final sync, no release. |
| - s2 := s.restart(t) |
| - if n := s2.a.LeasesHeld(); n != 0 { |
| - t.Fatalf("a fresh agent: LeasesHeld = %d, want 0", n) |
| - } |
| - if n := failures(t, s2.a); n != 1 { |
| - t.Fatalf("a fresh agent over a host left awake: ReplicationFailures = %d, want 1", n) |
| - } |
| - |
| - // The dead agent's lock runs out; the fresh agent takes the host. |
| - putLockFor(t, s2.b, s2.rt, leaseBody(t, owner, time.Now().Add(-time.Minute))) |
| - e2, err := s2.wakeForTest(context.Background()) |
| - if err != nil || e2 == nil { |
| - t.Fatalf("wake after the crash: %v", err) |
| - } |
| - if n := s2.a.LeasesHeld(); n != 1 { |
| - t.Fatalf("taken again: LeasesHeld = %d, want 1", n) |
| - } |
| - if n := failures(t, s2.a); n != 0 { |
| - t.Fatalf("taken again: ReplicationFailures = %d, want 0 (the held host is LeasesHeld's)", n) |
| - } |
| - s2.stopForTest(e2) |
| - if !s2.stoppedFor(e2) { |
| - t.Fatal("the stop went pending") |
| - } |
| - if n, h := failures(t, s2.a), s2.a.LeasesHeld(); n != 0 || h != 0 { |
| - t.Fatalf("after a clean stop: ReplicationFailures = %d, LeasesHeld = %d, want 0 and 0", n, h) |
| - } |
| -} |
| - |
| -// A normal wake and sleep leaves nothing: the awake record is written at |
| -// the wake and cleared by the final sync. |
| -func TestWakeSleepCycleLeavesNoRecord(t *testing.T) { |
| - s := legacyService(t, "shop.example.com") |
| - dir := filepath.Join(s.b.DataDir, ReplicationFailuresDir) |
| - e, err := s.wakeForTest(context.Background()) |
| - if err != nil || e == nil { |
| - t.Fatalf("wake: %v", err) |
| - } |
| - if _, err := os.Stat(filepath.Join(dir, s.rt.Host+unsyncedSuffix)); err != nil { |
| - t.Fatalf("no awake record while awake: %v", err) |
| - } |
| - s.stopForTest(e) |
| - if !s.stoppedFor(e) { |
| - t.Fatal("the stop went pending") |
| - } |
| - ents, err := os.ReadDir(dir) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if len(ents) != 0 || failures(t, s.a) != 0 { |
| - t.Fatalf("after a wake and a sleep: %v left, ReplicationFailures %d", ents, failures(t, s.a)) |
| - } |
| -} |
| - |
| -// The awake record is written before anything of the host runs, and a |
| -// record that cannot be written refuses the wake with nothing started and |
| -// the lease given back. |
| -func TestUnwritableAwakeRecordRefusesTheWake(t *testing.T) { |
| - s := legacyService(t, "shop.example.com") |
| - dir := filepath.Join(s.b.DataDir, ReplicationFailuresDir) |
| - var started bool |
| - start := s.ctl.onStart |
| - s.ctl.onStart = func() { |
| - if _, err := os.Stat(filepath.Join(dir, s.rt.Host+unsyncedSuffix)); err != nil { |
| - t.Errorf("the host started before its awake record existed: %v", err) |
| - } |
| - started = true |
| - start() |
| - } |
| - old := durableSync |
| - durableSync = func(d string) error { |
| - if d == dir { |
| - return errors.New("synthetic sync failure") |
| - } |
| - return old(d) |
| - } |
| - _, err := s.wakeForTest(context.Background()) |
| - durableSync = old |
| - if err == nil || started { |
| - t.Fatalf("wake = %v, started %v: want refused, nothing started", err, started) |
| - } |
| - if body := s.fx.LockBody(s.b.Cfg.hibernatePrefix(s.rt.Host)); body != nil { |
| - t.Fatalf("the refused wake kept the lease: %s", body) |
| - } |
| - e, err := s.wakeForTest(context.Background()) |
| - if err != nil || !started || e == nil { |
| - t.Fatalf("a wake once the record writes: %v, started %v", err, started) |
| - } |
| -} |
| - |
| -func fleetlessRoute(host string) registry.Route { |
| - return registry.Route{Host: host, Kind: "instance"} |
| -} |
| - |
| -// HA hosts keep no records (controller ruling, Task 6a review): an HA |
| -// wake and stop write nothing and leave ReplicationFailures as it was, and |
| -// a record of a host the box classifies HA is not counted. |
| -func TestHAWakeAndStopKeepNoRecord(t *testing.T) { |
| - s := haService(t, "shop.example.com") |
| - dir := filepath.Join(s.b.DataDir, ReplicationFailuresDir) |
| - if err := s.b.noteFailedFinalSync("cafe.example.com", errors.New("a legacy host's failure")); err != nil { |
| - t.Fatal(err) |
| - } |
| - before := failures(t, s.a) |
| - if before != 1 { |
| - t.Fatalf("one legacy record: %d", before) |
| - } |
| - e, err := s.wakeForTest(context.Background()) |
| - if err != nil || e == nil { |
| - t.Fatalf("wake: %v", err) |
| - } |
| - if _, ha := s.b.haAcquired(s.rt.Host); !ha { |
| - t.Fatal("the host did not wake HA") |
| - } |
| - if _, err := os.Stat(filepath.Join(dir, s.rt.Host+unsyncedSuffix)); !errors.Is(err, os.ErrNotExist) { |
| - t.Fatalf("an HA wake wrote an awake record: %v", err) |
| - } |
| - s.stopForTest(e) |
| - if !s.stoppedFor(e) { |
| - t.Fatal("the stop went pending") |
| - } |
| - ents, err := os.ReadDir(dir) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if len(ents) != 1 || ents[0].Name() != "cafe.example.com.json" { |
| - t.Fatalf("an HA wake and stop changed the records: %v", ents) |
| - } |
| - if n := failures(t, s.a); n != before { |
| - t.Fatalf("ReplicationFailures %d after an HA wake and stop, want %d", n, before) |
| - } |
| - // A record of the HA host itself (left from before it was HA) is not |
| - // counted. |
| - if err := s.b.noteFailedFinalSync(s.rt.Host, errors.New("from its legacy days")); err != nil { |
| - t.Fatal(err) |
| - } |
| - if n := failures(t, s.a); n != before { |
| - t.Fatalf("an HA host's record counted: %d, want %d", n, before) |
| - } |
| -} |
| - |
| -// Both counters come from one capture of the held leases: a host with an |
| -// awake record that takes its lease where the heartbeat used to sample |
| -// twice is counted once, as held when it took the lease before the |
| -// capture and as a failure when after; never in neither. The two separate |
| -// reads show the old false zero. |
| -func TestDrainSnapshotCountsAWakingHostOnce(t *testing.T) { |
| - s := legacyService(t, "shop.example.com") |
| - rt := s.rt |
| - acquire := func() Lease { |
| - t.Helper() |
| - l, err := s.b.Acquire(context.Background(), rt) |
| - if err != nil { |
| - t.Fatalf("acquire: %v", err) |
| - } |
| - return l |
| - } |
| - if err := s.b.noteUnsynced(rt); err != nil { |
| - t.Fatal(err) |
| - } |
| - |
| - // The old shape: leases sampled, the lease taken, failures sampled. |
| - leases := s.a.LeasesHeld() |
| - l := acquire() |
| - if f := failures(t, s.a); leases+f != 0 { |
| - t.Fatalf("the two-sample read was expected to miss the host (the bug): leases %d, failures %d", leases, f) |
| - } |
| - if err := l.Release(context.Background()); err != nil { |
| - t.Fatal(err) |
| - } |
| - |
| - for _, at := range []struct{ point, as string }{{"before", "held"}, {"held", "failure"}} { |
| - var taken Lease |
| - drainSnapshotHook = func(p string) { |
| - if p == at.point && taken == nil { |
| - taken = acquire() |
| - } |
| - } |
| - leases, f, err := s.a.DrainFacts() |
| - drainSnapshotHook = nil |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - want := [2]int{1, 0} |
| - if at.as == "failure" { |
| - want = [2]int{0, 1} |
| - } |
| - if [2]int{leases, f} != want { |
| - t.Fatalf("lease taken at %q: leases %d, failures %d, want %v (once, as %s)", at.point, leases, f, want, at.as) |
| - } |
| - if err := taken.Release(context.Background()); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| -} |
diff --git a/internal/activator/maintenance.go b/internal/activator/maintenance.go| index ef3aadc98..4baba261e 100644 |
| --- a/internal/activator/maintenance.go |
| +++ b/internal/activator/maintenance.go |
| @@ -483,12 +483,8 @@ func (a *Service) cleanupFailedWake(ctx context.Context, e *actEntry, rt registr |
| if w.rep != nil { |
| closeCtx, closeCancel := context.WithTimeout(context.Background(), 30*time.Second) |
| defer closeCancel() |
| - err := w.rep.Close(closeCtx) |
| - w.stopOutcome.replicaClosed = err == nil |
| + w.stopOutcome.replicaClosed = w.rep.Close(closeCtx) == nil |
| w.stopOutcome.leaseReleased = w.stopOutcome.replicaClosed |
| - if !haHeld(lease, w.rep) { // an HA host keeps no records (drainreport.go) |
| - a.noteFinalReplication(rt.Host, err) |
| - } |
| return |
| } |
| w.stopOutcome.leaseReleased = a.giveBack(ctx, rt.Host, lease) |
diff --git a/internal/activator/opset.go b/internal/activator/opset.go| index f4fc9636c..b89ffe798 100644 |
| --- a/internal/activator/opset.go |
| +++ b/internal/activator/opset.go |
| @@ -922,9 +922,6 @@ func (a *Service) reapUnprovenWake(host string, u *unprovenWake) { |
| if u.rep != nil { |
| err = u.rep.Close(ctx) |
| outcome.replicaClosed = err == nil |
| - if !haHeld(u.lease, u.rep) { // an HA host keeps no records (drainreport.go) |
| - a.noteFinalReplication(host, err) |
| - } |
| } else if u.lease != nil { |
| err = releaseLease(ctx, u.lease) |
| if err != nil { |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index fe9ebf7fe..0112966ac 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -2314,7 +2314,8 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| // 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 |
| + // on its detach needs the machine's termination confirmed (rule 5, |
| + // detachHeld). 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 != "" { |
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go| index 8f3989105..540cdc9d4 100644 |
| --- a/internal/console/fleetbox.go |
| +++ b/internal/console/fleetbox.go |
| @@ -252,9 +252,12 @@ func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, er |
| // loadFleetViewAt reads fleet as a labelling decision needs it, judging |
| // each box's heartbeat as of now. Only a registry that cannot be read is an |
| -// error. A fleet with fewer than two active boxes reads nothing more and is |
| -// not Active; otherwise anything that could not be read whole (the fleet's |
| -// heartbeats, the deployment's, the inventory) leaves Active false. |
| +// error. A fleet with fewer than two active boxes is never Active (new |
| +// labelling needs two). One that was never labelled reads nothing more; |
| +// one that was still has its boxes' heartbeats read, so a rollback below |
| +// the floor still pauses it and raises the alert (branch review R1, P2-2). |
| +// Otherwise anything that could not be read whole (the fleet's heartbeats, |
| +// the deployment's, the inventory) leaves Active false. |
| func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Time) (fleetView, error) { |
| v := fleetView{Load: map[string]int{}} |
| reg, err := s.openPassRegistry() |
| @@ -271,7 +274,18 @@ func (s *Server) loadFleetViewAt(ctx context.Context, fleet string, now time.Tim |
| } |
| } |
| slices.SortFunc(v.Boxes, func(a, b fleetBoxView) int { return strings.Compare(a.Label, b.Label) }) |
| - if len(v.Boxes) < 2 || s.cfg.Releases == nil { |
| + if s.cfg.Releases == nil { |
| + return v, nil |
| + } |
| + if len(v.Boxes) < 2 { |
| + if !v.labelled() { |
| + return v, nil |
| + } |
| + hbs, complete, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+fleet+"/") |
| + if err != nil || !complete { |
| + log.Printf("console: fleet %s view: heartbeats: complete %v, %v", fleet, complete, err) |
| + } |
| + joinBeats(v.Boxes, hbs, now) |
| return v, nil |
| } |
| // The fleet's heartbeats are read twice below, alone and in the |
diff --git a/internal/console/fleetrelabel.go b/internal/console/fleetrelabel.go| index 12b4f8a18..d258396b1 100644 |
| --- a/internal/console/fleetrelabel.go |
| +++ b/internal/console/fleetrelabel.go |
| @@ -15,7 +15,6 @@ import ( |
| "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). |
| @@ -47,15 +46,15 @@ import ( |
| // (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. |
| +// is what makes the detach doors ask for the machine's termination. |
| // |
| // 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). |
| +// console ever named on a record unless the request confirms its machine |
| +// is terminated (rule 5, detachHeld). |
| // fleetRelabelInterval is the worker's period. |
| const fleetRelabelInterval = 5 * time.Minute |
| @@ -363,74 +362,16 @@ func (s *Server) readFleetBinding(ctx context.Context, fleet, h string) (fleetBi |
| return b, true, nil |
| } |
| -// drainSkewMargin is how long after a drain began a heartbeat must be |
| -// composed to count as composed after it. The heartbeat's time is the box's |
| -// clock and the drain's start is the console's. Boxes run NTP, but a box |
| -// clock running ahead must not pass a heartbeat composed before the drain |
| -// (controller ruling on Task 6b, concern 5). |
| -const drainSkewMargin = 2 * time.Minute |
| - |
| -// 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 at least drainSkewMargin 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.Before(drainingSince.Add(drainSkewMargin)) && |
| - 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 |
| +// detachHeld is the detach doors' one check (rule 5, Paul 2026-10-31): |
| +// 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 active box detaches only when the request confirms its machine is |
| +// terminated: the console cannot tell from the box's own reports that its |
| +// last writes reached the bucket, so it asks the operator who ended the |
| +// machine. The accepted cost is that writes a terminated box never |
| +// uploaded are lost; a drain before the termination avoids that. |
| +func detachHeld(box registry.FleetBox, terminated bool) bool { |
| + return box.Status == "active" && box.LabelledAt != 0 && !terminated |
| } |
| // errFleetDrainHostClaim is drainBox's refusal on a host-claim console. |
| @@ -553,9 +494,11 @@ const ( |
| // 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. A listing that fails or is not whole is never "not |
| -// paused": it is fleetLabelsUnknown unless a report it did read pauses the |
| -// fleet. err is the listing's failure, for the log. |
| +// heartbeats are read. A listing that fails or is not whole, or an active |
| +// box with no report in it (joinBeats' unheard: attached and never heard |
| +// from, or silent past the listing's horizon), is never "not paused": it |
| +// is fleetLabelsUnknown unless a report it did read pauses the fleet |
| +// (branch review R1, P2-1). err is the reason, for the log. |
| func (s *Server) labelsPausedFor(ctx context.Context, fleet string, boxes []registry.FleetBox) (string, error) { |
| var v fleetView |
| for _, b := range boxes { |
| @@ -573,13 +516,16 @@ func (s *Server) labelsPausedFor(ctx context.Context, fleet string, boxes []regi |
| if err != nil { |
| return fleetLabelsUnknown, err |
| } |
| - joinBeats(v.Boxes, hbs, time.Now()) |
| + unheard := joinBeats(v.Boxes, hbs, time.Now()) |
| if box, _ := v.labelsPausedBy(); box != "" { |
| return fleetLabelsPaused, nil |
| } |
| if !complete { |
| return fleetLabelsUnknown, errors.New("the heartbeat listing was not read whole") |
| } |
| + if unheard { |
| + return fleetLabelsUnknown, errors.New("an active box has no report") |
| + } |
| return "", nil |
| } |
| @@ -593,7 +539,14 @@ func msgDrainStrandsApps(fleet, label string, apps []string) string { |
| // 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, leases or failed final uploads. run carlos fleets drain %s %s, then detach it when the box reports no instances, no held leases and no failed final uploads", |
| + return fmt.Sprintf("%s/%s has run instances, so it is detached only once its machine is gone. drain it first with carlos fleets drain %s %s. once the machine is terminated, detach it with carlos fleets detach-box --terminated %s %s", |
| + fleet, label, fleet, label, fleet, label) |
| +} |
| + |
| +// msgDetachNotDrainedPage is msgDetachNotDrained for the fleet page, whose |
| +// form confirms the termination with its checkbox. |
| +func msgDetachNotDrainedPage(fleet, label string) string { |
| + return fmt.Sprintf("%s/%s has run instances, so it is detached only once its machine is gone. Drain it first with carlos fleets drain %s %s. Once the machine is terminated, tick Machine terminated and detach it.", |
| fleet, label, fleet, label) |
| } |
diff --git a/internal/console/fleetrelabel_test.go b/internal/console/fleetrelabel_test.go| index 85b21f0b6..e3cf902f4 100644 |
| --- a/internal/console/fleetrelabel_test.go |
| +++ b/internal/console/fleetrelabel_test.go |
| @@ -21,7 +21,9 @@ import ( |
| // 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 |
| +// the drain, and the removal rule both detach doors ask (a box that has |
| +// run instances is detached only with its machine's termination |
| +// confirmed). App shop |
| // (and blog) in bab, fleet pi, boxes pi-1, pi-2, pi-3, hosts under |
| // example.com. |
| @@ -333,6 +335,67 @@ func TestLabelsPausedIsUnknownWhenReportsCannotBeRead(t *testing.T) { |
| } |
| } |
| +// Branch review R1, P2-1: a registered active box with no report at all |
| +// (attached and never heard from, or silent past the listing's horizon) |
| +// is missing version evidence, so LABELS PAUSED reads unknown, never "not |
| +// paused". A box positively observed below the floor still reads paused |
| +// beside it. |
| +func TestLabelsPausedIsUnknownWhenABoxHasNoReport(t *testing.T) { |
| + fx, token, reg := fleetBoxWorld(t, "code-rl-unheard", "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) // pi-1 holds a label: the fleet has labels |
| + if got := fleetListLabels(t, fx, token); got != "" { |
| + t.Fatalf("a current fleet shows labels_paused %q; want it absent", got) |
| + } |
| + registerFleetBox(t, reg, "pi", "pi-3") // attached, never reported |
| + if got := fleetListLabels(t, fx, token); got != fleetLabelsUnknown { |
| + t.Fatalf("with pi-3 registered and never reported, labels_paused = %q; want %q", got, fleetLabelsUnknown) |
| + } |
| + piBeat(t, fx, "pi-2", true, time.Now(), "v0.32.0") |
| + if got := fleetListLabels(t, fx, token); got != fleetLabelsPaused { |
| + t.Fatalf("pi-2 below the floor, pi-3 unheard: labels_paused = %q; want %q", got, fleetLabelsPaused) |
| + } |
| +} |
| + |
| +// Branch review R1, P2-2: a labelled fleet that shrinks to one active box |
| +// still has its version evidence read, so a rollback of that box below the |
| +// floor pauses the fleet and raises the alert. Activation still needs two |
| +// boxes. |
| +func TestOneBoxLabelledFleetStillAlertsOnRollback(t *testing.T) { |
| + fx, token, reg := fleetBoxWorld(t, "code-rl-onebox", "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") |
| + // pi-2 never held a label: it detaches at once, leaving pi-1 alone. |
| + if code, raw := detachAPI(t, fx, token, "pi-2", false); code != http.StatusOK { |
| + t.Fatalf("detach pi-2 = %d %s", code, raw) |
| + } |
| + if b := boxRow(t, reg, "pi-2"); b.Status != "detached" { |
| + t.Fatalf("pi-2 %+v; want detached", b) |
| + } |
| + piBeat(t, fx, "pi-1", true, time.Now(), "v0.32.0") // rolled back |
| + var logs bytes.Buffer |
| + restore := captureLogTo(&logs) |
| + relabelPass(t, fx) |
| + restore() |
| + if out := logs.String(); !strings.Contains(out, "ERROR") || !strings.Contains(out, "pi-1") || !strings.Contains(out, "v0.32.0") { |
| + t.Fatalf("no alert for the one-box fleet's rollback:\n%s", out) |
| + } |
| + if got := fleetListLabels(t, fx, token); got != fleetLabelsPaused { |
| + t.Fatalf("labels_paused = %q; want %q", got, fleetLabelsPaused) |
| + } |
| + wantLabel(t, shopRec(t, fx, "a.example.com"), "pi-1") |
| + v, err := fx.srv.loadFleetViewAt(context.Background(), "pi", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if v.Active || v.labelActive() { |
| + t.Fatal("a one-box fleet reads as active for labelling") |
| + } |
| +} |
| + |
| // 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" |
| @@ -419,70 +482,6 @@ func TestDrainRefusesAnUnmanagedRecord(t *testing.T) { |
| } |
| } |
| -// 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(3 * time.Minute) |
| - 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") |
| - } |
| -} |
| - |
| -// Controller ruling (concern 5): boxes run NTP, but a box clock running |
| -// ahead must not pass a heartbeat composed before the drain, so the |
| -// heartbeat must be composed drainSkewMargin after the drain began. |
| -func TestDrainDoneAllowsForClockSkew(t *testing.T) { |
| - since := time.Now() |
| - hb := status.Box{GeneratedAt: since.Add(time.Minute), Metrics: &status.BoxMetrics{Release: release.FleetBoxLabelFloor}} |
| - if drainDone(hb, since) { |
| - t.Fatal("an empty heartbeat composed 1 minute after the drain is done") |
| - } |
| - hb.GeneratedAt = since.Add(3 * time.Minute) |
| - if !drainDone(hb, since) { |
| - t.Fatal("an empty heartbeat composed 3 minutes after the drain is not done") |
| - } |
| -} |
| - |
| -func TestDrainDoneNeedsNoLeases(t *testing.T) { |
| - since := time.Now() |
| - hb := status.Box{GeneratedAt: since.Add(3 * 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) { |
| @@ -498,21 +497,31 @@ func drainedPi1(t *testing.T, code string) (*consoleFixture, string, *registry.R |
| return fx, token, reg |
| } |
| -// detachAPI detaches label through the CLI door. |
| -func detachAPI(t *testing.T, fx *consoleFixture, token, label string) (int, string) { |
| +// detachAPI detaches label through the CLI door, confirming the machine |
| +// is terminated when terminated is set. |
| +func detachAPI(t *testing.T, fx *consoleFixture, token, label string, terminated bool) (int, string) { |
| t.Helper() |
| - code, _, raw := rawReq(t, http.MethodPost, fleetsURL(fx, fx.sqid)+"/pi/boxes/"+label+"/detach", token, `{}`) |
| + body := `{}` |
| + if terminated { |
| + body = `{"terminated":true}` |
| + } |
| + code, _, raw := rawReq(t, http.MethodPost, fleetsURL(fx, fx.sqid)+"/pi/boxes/"+label+"/detach", token, body) |
| 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 { |
| +// detachPage detaches label through the owner's form, ticking Machine |
| +// terminated when terminated is set, and answers the flash the fleet page |
| +// then shows. |
| +func detachPage(t *testing.T, fx *consoleFixture, label string, terminated bool) 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}}) |
| + form := url.Values{"csrf": {csrf}, "label": {label}} |
| + if terminated { |
| + form.Set("terminated", "true") |
| + } |
| + st, loc, _ := postForm(t, c, fx.u("/fleets/pi/detach"), form) |
| if st != http.StatusSeeOther || loc != fx.path("/fleets/pi") { |
| t.Fatalf("page detach = %d -> %q", st, loc) |
| } |
| @@ -520,88 +529,54 @@ func detachPage(t *testing.T, fx *consoleFixture, label string) string { |
| 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(3*time.Minute), 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(4*time.Minute), 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) { |
| +// The removal rule (rule 5, Paul 2026-10-31): a box the console placed |
| +// instances on is detached only with the confirmation that its machine is |
| +// terminated, at both doors. Without it the doors refuse and say to drain |
| +// first and detach with the confirmation once the machine is gone. The |
| +// box's reports play no part: a drained box with an empty report is |
| +// refused without it, and a box still holding a lease is detached with it. |
| +func TestBothDetachDoorsNeedTerminated(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) { |
| + detach := func(terminated bool) (ok bool, said string) { |
| if door == "api" { |
| - code, raw := detachAPI(t, fx, token, "pi-1") |
| + code, raw := detachAPI(t, fx, token, "pi-1", terminated) |
| + if code == http.StatusConflict { |
| + return false, errorOf(t, raw) |
| + } |
| return code == http.StatusOK, raw |
| } |
| - body := detachPage(t, fx, "pi-1") |
| + body := detachPage(t, fx, "pi-1", terminated) |
| 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(3*time.Minute), 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) |
| + refusal := msgDetachNotDrained("pi", "pi-1") |
| + if door == "page" { |
| + refusal = msgDetachNotDrainedPage("pi", "pi-1") |
| + } |
| + // Drained, and its newest report shows nothing: still refused. |
| + beat(t, fx, "pi-1", time.Now().Add(3*time.Minute), nil) |
| + if ok, said := detach(false); ok || !strings.Contains(said, refusal) { |
| + t.Fatalf("detach of a drained box without terminated: 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(4*time.Minute), nil) |
| - if ok, said := detach(); !ok { |
| - t.Fatalf("detach of a drained box refused:\n%s", said) |
| + if ok, said := detach(true); !ok { |
| + t.Fatalf("detach with terminated 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. |
| + // A box never named on a record detaches at once, at either door, |
| + // without the confirmation. |
| 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 { |
| + if code, raw := detachAPI(t, fx, token, "pi-2", false); 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.") { |
| + if body := detachPage(t, fx, "pi-3", false); !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" { |
| @@ -609,9 +584,58 @@ func TestBothDetachDoorsUseDrainDone(t *testing.T) { |
| } |
| } |
| +// The refusals say what to do: drain first, then detach with the |
| +// confirmation once the machine is terminated. |
| +func TestDetachRefusalSaysDrainThenTerminated(t *testing.T) { |
| + for _, msg := range []string{msgDetachNotDrained("pi", "pi-1"), msgDetachNotDrainedPage("pi", "pi-1")} { |
| + if !strings.Contains(msg, "carlos fleets drain pi pi-1") { |
| + t.Fatalf("refusal %q does not say to drain first", msg) |
| + } |
| + if strings.ContainsAny(msg, "\u2014\u2013") { |
| + t.Fatalf("refusal %q has a dash", msg) |
| + } |
| + } |
| + if m := msgDetachNotDrained("pi", "pi-1"); !strings.Contains(m, "carlos fleets detach-box --terminated pi pi-1") { |
| + t.Fatalf("CLI refusal %q does not name --terminated", m) |
| + } |
| + if m := msgDetachNotDrainedPage("pi", "pi-1"); !strings.Contains(m, "Machine terminated") { |
| + t.Fatalf("page refusal %q does not name the checkbox", m) |
| + } |
| +} |
| + |
| +// A silent box (its records already moved by the lost-box rule) is |
| +// detached only with the confirmation too: once its machine is known to be |
| +// gone, the operator says so. |
| +func TestSilentBoxDetachesOnlyTerminated(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", false); 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", false); !strings.Contains(body, msgDetachNotDrainedPage("pi", "pi-1")) { |
| + t.Fatalf("page detach of a silent box shows no refusal:\n%s", body) |
| + } |
| + if b := boxRow(t, reg, "pi-1"); b.Status != "active" { |
| + t.Fatalf("box %+v; want still attached", b) |
| + } |
| + if code, raw := detachAPI(t, fx, token, "pi-1", true); code != http.StatusOK { |
| + t.Fatalf("API detach of a silent box with terminated = %d %s", code, raw) |
| + } |
| + if b := boxRow(t, reg, "pi-1"); b.Status != "detached" { |
| + t.Fatalf("box %+v; want detached", b) |
| + } |
| +} |
| + |
| // Review fix round 1, P1: a relabel that lands after the detach door is |
| // called and before it takes the fleet's lock names the box on a record. |
| -// The door must see that and ask the drain rule, at both doors. |
| +// The door must see that and ask for the confirmation, at both doors. |
| func TestDetachSeesARelabelThatLandsBeforeTheLock(t *testing.T) { |
| for _, door := range []string{"api", "page"} { |
| t.Run(door, func(t *testing.T) { |
| @@ -627,10 +651,10 @@ func TestDetachSeesARelabelThatLandsBeforeTheLock(t *testing.T) { |
| } |
| var refused bool |
| if door == "api" { |
| - code, raw := detachAPI(t, fx, token, "pi-1") |
| + code, raw := detachAPI(t, fx, token, "pi-1", false) |
| refused = code == http.StatusConflict && errorOf(t, raw) == msgDetachNotDrained("pi", "pi-1") |
| } else { |
| - refused = strings.Contains(detachPage(t, fx, "pi-1"), msgDetachNotDrained("pi", "pi-1")) |
| + refused = strings.Contains(detachPage(t, fx, "pi-1", false), msgDetachNotDrainedPage("pi", "pi-1")) |
| } |
| wantLabel(t, shopRec(t, fx, "a.example.com"), "pi-1") |
| if !refused { |
diff --git a/internal/console/fleets.go b/internal/console/fleets.go| index 4973aa81a..39f01aa6d 100644 |
| --- a/internal/console/fleets.go |
| +++ b/internal/console/fleets.go |
| @@ -568,12 +568,17 @@ func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request) |
| jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again") |
| return |
| } |
| - var req struct{} |
| + var req struct { |
| + // Terminated confirms the box's machine is gone (managed fleets |
| + // 1b, rule 5): a box the console ever placed instances on is |
| + // detached only with it (detachHeld). |
| + Terminated bool `json:"terminated"` |
| + } |
| if !readJSON(w, r, &req) { |
| return |
| } |
| label := r.PathValue("label") |
| - // The drain rule (managed fleets 1b, rule 5): the box is read, judged |
| + // The removal rule (managed fleets 1b, rule 5): the box is read, judged |
| // and detached under the fleet's lock, the lock every writer of a label |
| // holds, so the box row the check reads is the one the write acts on |
| // and nothing names the box between them. |
| @@ -592,13 +597,7 @@ func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request) |
| jsonError(w, http.StatusNotFound, "no such box") |
| return |
| } |
| - 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 { |
| + if detachHeld(*box, req.Terminated) { |
| jsonError(w, http.StatusConflict, msgDetachNotDrained(fleet.Name, label)) |
| return |
| } |
| @@ -616,8 +615,8 @@ func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request) |
| // 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). |
| +// instances. Detach (handleAPIFleetDetachBox) is the second step, once the |
| +// box's machine is terminated (detachHeld). |
| func (s *Server) handleAPIFleetDrainBox(w http.ResponseWriter, r *http.Request) { |
| addr, acct, fleet, reg, ok := s.apiFleet(w, r) |
| if !ok { |
| @@ -1563,7 +1562,10 @@ func (s *Server) handleFleetDetachBoxPage(w http.ResponseWriter, r *http.Request |
| http.Redirect(w, r, fleetPageURL(acct.Sqid, fleet.Name), http.StatusSeeOther) |
| } |
| label := strings.TrimSpace(r.FormValue("label")) |
| - // The drain rule, read, judged and written under the fleet's lock, as |
| + // The form's "terminated" field is the API's (detachHeld): the owner |
| + // confirms the box's machine is gone. |
| + terminated := r.FormValue("terminated") == "true" |
| + // The removal rule, read, judged and written under the fleet's lock, as |
| // handleAPIFleetDetachBox does. |
| if s.detachBeforeLock != nil { |
| s.detachBeforeLock(fleet.Name, label) |
| @@ -1580,14 +1582,8 @@ func (s *Server) handleFleetDetachBoxPage(w http.ResponseWriter, r *http.Request |
| back("err", "No such box.") |
| return |
| } |
| - 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)) |
| + if detachHeld(*box, terminated) { |
| + back("err", msgDetachNotDrainedPage(fleet.Name, label)) |
| return |
| } |
| if err := reg.SetFleetBoxStatus(fleet.Name, label, "detached"); err != nil { |
diff --git a/internal/console/templates/fleetdetail.html b/internal/console/templates/fleetdetail.html| index 49af19561..b148cd148 100644 |
| --- a/internal/console/templates/fleetdetail.html |
| +++ b/internal/console/templates/fleetdetail.html |
| @@ -53,6 +53,7 @@ |
| <form method="post" action="{{$.Base}}/fleets/{{$.FleetDetail.Name}}/detach"> |
| <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| <input type="hidden" name="label" value="{{.Label}}"> |
| + <label class="small"><input type="checkbox" name="terminated" value="true"> Machine terminated</label> |
| <button type="submit" class="linkish danger">Detach</button> |
| </form> |
| <form method="post" action="{{$.Base}}/fleets/{{$.FleetDetail.Name}}/tags"> |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 440b06312..a70819f03 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -4397,11 +4397,6 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func |
| // pass still says something rather than nothing. |
| Layout: layoutStatusReport(routes), |
| } |
| - // The drain rule's facts (managed fleets 1b): the instance leases |
| - // this box holds and its unresolved replication records, from the |
| - // activator's memory and the data directory (read directly when |
| - // there is no activator). No store request. |
| - drainReport(&p, svc, dataDir()) |
| // The hosts this box is refusing because it cannot provide their |
| // config (amadan #213): private Metrics only, nothing public. |
| claimReport(&p) |
diff --git a/internal/host/drainreport.go b/internal/host/drainreport.go| deleted file mode 100644 |
| index 42ae57d32..000000000 |
| --- a/internal/host/drainreport.go |
| +++ /dev/null |
| @@ -1,35 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "log" |
| - |
| - "github.com/carlosframework/platform/internal/activator" |
| - "github.com/carlosframework/platform/internal/status" |
| -) |
| - |
| -// drainReport fills the heartbeat's drain rule facts (managed fleets 1b, |
| -// rule 5): the instance leases this process holds right now, and the hosts |
| -// whose writes on this box are not known to be in the bucket. Both come |
| -// from the activator's one snapshot (Service.DrainFacts), so a host taking |
| -// its lease mid-read is counted once, never in neither. With no activator |
| -// (svc nil) no lease can be held, and the durable records under dataDir |
| -// are counted directly (activator.CountReplicationRecords): records left |
| -// by an earlier run with an activator still count. Neither read touches |
| -// the bucket. A failure count that cannot be read is reported as at least |
| -// 1, so a console never reads it as drained. |
| -func drainReport(p *status.Probes, svc *activator.Service, dataDir string) { |
| - var ( |
| - leases, n int |
| - err error |
| - ) |
| - if svc == nil { |
| - n, err = activator.CountReplicationRecords(dataDir) |
| - } else { |
| - leases, n, err = svc.DrainFacts() |
| - } |
| - if err != nil { |
| - log.Printf("agent: status tick: replication records unreadable: %v (reported as at least 1)", err) |
| - n = max(n, 1) |
| - } |
| - p.LeasesHeld, p.ReplicationFailures = leases, n |
| -} |
diff --git a/internal/host/drainreport_test.go b/internal/host/drainreport_test.go| deleted file mode 100644 |
| index 05678533e..000000000 |
| --- a/internal/host/drainreport_test.go |
| +++ /dev/null |
| @@ -1,167 +0,0 @@ |
| -package host |
| - |
| -import ( |
| - "context" |
| - "encoding/json" |
| - "os" |
| - "path/filepath" |
| - "testing" |
| - |
| - "github.com/carlosframework/platform/internal/activator" |
| - "github.com/carlosframework/platform/internal/lease/locktest" |
| - "github.com/carlosframework/platform/internal/registry" |
| - "github.com/carlosframework/platform/internal/release" |
| - "github.com/carlosframework/platform/internal/status" |
| -) |
| - |
| -// drainBox is a fleet box's activator wired as RunAgent wires it (a |
| -// SplitBackend over an ExecBackend), and the heartbeat statusLoop |
| -// composes from it: drainReport, then statusTick under the box's label. |
| -type drainBox struct { |
| - eb *activator.ExecBackend |
| - svc *activator.Service |
| - reg *registry.Registry |
| - store release.Store |
| -} |
| - |
| -func newDrainBox(t *testing.T, bucket string) *drainBox { |
| - t.Helper() |
| - reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { reg.Close() }) |
| - cfg := activator.Config{Bucket: bucket} |
| - eb := &activator.ExecBackend{Cfg: cfg, OptDir: t.TempDir(), DataDir: t.TempDir()} |
| - svc := activator.New(cfg, &activator.SplitBackend{Exec: eb, Unit: &activator.UnitBackend{OptDir: eb.OptDir}}, reg) |
| - return &drainBox{eb: eb, svc: svc, reg: reg, store: release.NewDirStore(t.TempDir())} |
| -} |
| - |
| -// heartbeat composes and writes one heartbeat under the label pi-1 and |
| -// returns it as written, raw and decoded. |
| -func (d *drainBox) heartbeat(t *testing.T, svc *activator.Service) (string, status.Box) { |
| - t.Helper() |
| - ctx := context.Background() |
| - p := status.Probes{MachineID: "test-machine"} |
| - drainReport(&p, svc, d.eb.DataDir) |
| - if err := statusTick(ctx, d.store, d.reg, p, false, "pi-1"); err != nil { |
| - t.Fatalf("statusTick: %v", err) |
| - } |
| - raw, _, err := d.store.Get(ctx, "status/boxes/pi-1.json") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - var box status.Box |
| - if err := json.Unmarshal(raw, &box); err != nil { |
| - t.Fatal(err) |
| - } |
| - return string(raw), box |
| -} |
| - |
| -// The drain rule's lease half (managed fleets 1b): a box holding two |
| -// instance leases reports 2 in its heartbeat, and 0 once both are given |
| -// back. Real leases, against the lock fixture. |
| -func TestHeartbeatCountsHeldLeases(t *testing.T) { |
| - fx := locktest.NewLockFixture(t) // sets env: not parallel |
| - d := newDrainBox(t, fx.Bucket) |
| - ctx := context.Background() |
| - var held []activator.Lease |
| - for _, host := range []string{"shop.example.com", "cafe.example.com"} { |
| - l, err := d.eb.Acquire(ctx, registry.Route{Host: host, Kind: "instance"}) |
| - if err != nil { |
| - t.Fatalf("acquire %s: %v", host, err) |
| - } |
| - held = append(held, l) |
| - } |
| - raw, box := d.heartbeat(t, d.svc) |
| - if box.LeasesHeld != 2 || box.ReplicationFailures != 0 { |
| - t.Fatalf("holding two leases: leases_held %d, replication_failures %d\n%s", box.LeasesHeld, box.ReplicationFailures, raw) |
| - } |
| - if err := held[0].Release(ctx); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, box := d.heartbeat(t, d.svc); box.LeasesHeld != 1 { |
| - t.Fatalf("after one release: leases_held %d, want 1", box.LeasesHeld) |
| - } |
| - if err := held[1].Release(ctx); err != nil { |
| - t.Fatal(err) |
| - } |
| - raw, box = d.heartbeat(t, d.svc) |
| - if box.LeasesHeld != 0 { |
| - t.Fatalf("after both releases: leases_held %d, want 0\n%s", box.LeasesHeld, raw) |
| - } |
| - var keys map[string]any |
| - if err := json.Unmarshal([]byte(raw), &keys); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, ok := keys["leases_held"]; !ok { |
| - t.Fatalf("a zero count is not on the wire: %s", raw) |
| - } |
| - if _, ok := keys["replication_failures"]; !ok { |
| - t.Fatalf("a zero count is not on the wire: %s", raw) |
| - } |
| -} |
| - |
| -// The drain rule's replication half: a failed final sync recorded by an |
| -// earlier agent on this box's data directory is in the heartbeat; a |
| -// record directory that cannot be read reports at least one, never none. |
| -// A box with no activator holds nothing. |
| -func TestHeartbeatReportsReplicationFailures(t *testing.T) { |
| - t.Parallel() |
| - d := newDrainBox(t, "test-bucket") |
| - dir := filepath.Join(d.eb.DataDir, activator.ReplicationFailuresDir) |
| - if err := os.MkdirAll(dir, 0o700); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := os.WriteFile(filepath.Join(dir, "shop.example.com.json"), []byte(`{"host":"shop.example.com"}`), 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, box := d.heartbeat(t, d.svc); box.ReplicationFailures != 1 { |
| - t.Fatalf("one record: replication_failures %d, want 1", box.ReplicationFailures) |
| - } |
| - if err := os.RemoveAll(dir); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, box := d.heartbeat(t, d.svc); box.ReplicationFailures != 0 { |
| - t.Fatalf("no records: replication_failures %d, want 0", box.ReplicationFailures) |
| - } |
| - if err := os.WriteFile(dir, nil, 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - if _, box := d.heartbeat(t, d.svc); box.ReplicationFailures < 1 { |
| - t.Fatalf("an unreadable record directory: replication_failures %d, want at least 1", box.ReplicationFailures) |
| - } |
| - if _, box := d.heartbeat(t, nil); box.LeasesHeld != 0 || box.ReplicationFailures < 1 { |
| - t.Fatalf("no activator, unreadable records: leases_held %d, replication_failures %d, want 0 and at least 1", box.LeasesHeld, box.ReplicationFailures) |
| - } |
| -} |
| - |
| -// Review finding 3: no activator is not no failures. Records left by an |
| -// earlier run (a failed final sync of one host, another left awake by a |
| -// crash) are on disk under the data directory; the agent restarted without |
| -// an activator reports both, since no lease can be held without one. With |
| -// no records it reports 0. |
| -func TestHeartbeatWithoutAnActivatorReportsRecords(t *testing.T) { |
| - t.Parallel() |
| - d := newDrainBox(t, "test-bucket") |
| - if _, box := d.heartbeat(t, nil); box.LeasesHeld != 0 || box.ReplicationFailures != 0 { |
| - t.Fatalf("no activator, no records: leases_held %d, replication_failures %d", box.LeasesHeld, box.ReplicationFailures) |
| - } |
| - dir := filepath.Join(d.eb.DataDir, activator.ReplicationFailuresDir) |
| - if err := os.MkdirAll(dir, 0o700); err != nil { |
| - t.Fatal(err) |
| - } |
| - for _, name := range []string{"shop.example.com.json", "cafe.example.com.unsynced", "cafe.example.com.json", ".tmp-partial.json"} { |
| - if err := os.WriteFile(filepath.Join(dir, name), []byte("{}\n"), 0o600); err != nil { |
| - t.Fatal(err) |
| - } |
| - } |
| - if _, box := d.heartbeat(t, nil); box.LeasesHeld != 0 || box.ReplicationFailures != 2 { |
| - t.Fatalf("no activator, two hosts' records: leases_held %d, replication_failures %d, want 0 and 2", box.LeasesHeld, box.ReplicationFailures) |
| - } |
| - p := status.Probes{} |
| - drainReport(&p, nil, "relative/data") |
| - if p.ReplicationFailures < 1 { |
| - t.Fatalf("no activator and no absolute data directory: replication_failures %d, want at least 1", p.ReplicationFailures) |
| - } |
| -} |
diff --git a/internal/host/fleettwobox_e2e_test.go b/internal/host/fleettwobox_e2e_test.go| index 6b536417a..5c79dcc6c 100644 |
| --- a/internal/host/fleettwobox_e2e_test.go |
| +++ b/internal/host/fleettwobox_e2e_test.go |
| @@ -52,8 +52,7 @@ import ( |
| // - ExecBackend.Acquire and Restore (the lease take, the start rule, the |
| // set-aside and the restore from the fleet bucket), the lease's renewal |
| // and release, litestream replication (Lease.Replicate, Rep.Close); |
| -// - the heartbeat's drain facts (drainReport over a Service on the |
| -// backend) and the binding a wake publishes (fleetBindingHook). |
| +// - the binding a wake publishes (fleetBindingHook). |
| // |
| // What is modelled, and why: |
| // - the activator's orchestration around the backend: a wake is Acquire, |
| @@ -160,7 +159,6 @@ type fleetBox struct { |
| reg *registry.Registry |
| store *cutStore |
| eb *activator.ExecBackend |
| - svc *activator.Service // the heartbeat's drain facts (DrainFacts) |
| awake map[string]activator.Rep |
| } |
| @@ -321,7 +319,6 @@ func (b *fleetBox) start() { |
| cfg := activator.Config{Bucket: fleetBucket, Region: fleetRegion, Prefix: fleetPrefix} |
| id := b.self |
| b.eb = &activator.ExecBackend{Cfg: cfg, DataDir: b.dd, OptDir: b.w.t.TempDir(), LeaseIdentity: &id, LeaseTTL: fleetTTL} |
| - b.svc = activator.New(cfg, b.eb, b.reg) |
| b.awake = map[string]activator.Rep{} |
| } |
| @@ -549,8 +546,7 @@ func (b *fleetBox) heartbeat(at time.Time) status.Box { |
| } |
| // heartbeatRel is statusTick's composition with a chosen time and |
| -// release: the box's routes, the drain facts, its label, written under |
| -// fleets/pi/. |
| +// release: the box's routes and its label, written under fleets/pi/. |
| func (b *fleetBox) heartbeatRel(at time.Time, rel string) status.Box { |
| t := b.w.t |
| t.Helper() |
| @@ -559,7 +555,6 @@ func (b *fleetBox) heartbeatRel(at time.Time, rel string) status.Box { |
| t.Fatal(err) |
| } |
| p := status.Probes{MachineID: "machine-" + b.label, Release: rel} |
| - drainReport(&p, b.svc, b.dd) |
| box := status.CollectBox(routes, p, at) |
| box.Label = b.label |
| if err := status.WriteBox(context.Background(), release.NewPrefixStore(b.store, "fleets/"+fleetName+"/"), box); err != nil { |
| @@ -850,8 +845,10 @@ func TestTwoBoxFleetEndToEnd_Real(t *testing.T) { |
| } |
| pi2.write(fleetA, "2") |
| - // (4) Drain pi-2: a and b move to pi-1. pi-2 stays attached until its |
| - // heartbeat says it holds nothing. |
| + // (4) Drain pi-2: a and b move to pi-1. pi-2 is detached only with the |
| + // confirmation that its machine is terminated (rule 5): refused |
| + // without it, then given it once pi-2 has dropped its rows, stopped a |
| + // (its final sync) and released the lease. |
| w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/drain", `{}`, http.StatusOK) |
| w.wantRecord(fleetA, "pi-1", true) |
| w.wantRecord(fleetB, "pi-1", true) |
| @@ -860,24 +857,17 @@ func TestTwoBoxFleetEndToEnd_Real(t *testing.T) { |
| if row.DrainingSince == 0 || row.Status != "active" { |
| t.Fatalf("pi-2 after the drain: %+v, want active and draining", row) |
| } |
| - since := time.Unix(0, row.DrainingSince) |
| - w.advance(time.Minute) |
| - if hb := pi2.heartbeat(w.now); hb.LeasesHeld != 1 { |
| - t.Fatalf("pi-2 reports %d leases held, want 1 (a)", hb.LeasesHeld) |
| - } |
| w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/detach", `{}`, http.StatusConflict) |
| pi2.mustReconcile() |
| wantOnly(t, pi2) |
| - w.wantNoLock(fleetA) |
| - at := w.now.Add(3 * time.Minute) |
| - if since.Add(3 * time.Minute).After(at) { |
| - at = since.Add(3 * time.Minute) |
| + if len(pi2.awake) != 0 { |
| + t.Fatalf("pi-2 still has %d awake after the drain", len(pi2.awake)) |
| } |
| - w.now = at |
| - if hb := pi2.heartbeat(w.now); hb.LeasesHeld != 0 || hb.ReplicationFailures != 0 || hb.Routes.Resident+hb.Routes.Hibernating != 0 { |
| - t.Fatalf("drained pi-2 reports %+v routes, %d leases, %d failures", hb.Routes, hb.LeasesHeld, hb.ReplicationFailures) |
| + w.wantNoLock(fleetA) |
| + w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/detach", `{"terminated":true}`, http.StatusOK) |
| + if row := w.boxRow("pi-2"); row.Status != "detached" { |
| + t.Fatalf("pi-2 after the terminated detach: %+v, want detached", row) |
| } |
| - w.mustDo(http.MethodPost, "/api/cli/fleets/"+w.acct+"/pi/boxes/pi-2/detach", `{}`, http.StatusOK) |
| // pi-1 wakes a under the new assignment: its old copy (written under |
| // the first) is set aside, the bucket's restored, and it reads 2, not |
diff --git a/internal/lease/finalsync.go b/internal/lease/finalsync.go| deleted file mode 100644 |
| index 29abe6fb5..000000000 |
| --- a/internal/lease/finalsync.go |
| +++ /dev/null |
| @@ -1,37 +0,0 @@ |
| -package lease |
| - |
| -// FinalSyncError is a replicator release (Close) whose final sync failed: |
| -// the database's last writes may not have reached the replica. Close |
| -// releases the lease either way, so the error is the one record that the |
| -// box still holds writes the bucket does not (managed fleets 1b, the drain |
| -// rule: the activator keeps it on disk until a later replication of the |
| -// host lands). A release that failed after a sync that worked is not one. |
| -// Error is the failure's own text, unchanged. |
| -type FinalSyncError struct{ Err error } |
| - |
| -func (e *FinalSyncError) Error() string { return e.Err.Error() } |
| -func (e *FinalSyncError) Unwrap() error { return e.Err } |
| - |
| -// finalSyncErr wraps a store close's error as a *FinalSyncError; nil |
| -// stays nil. |
| -func finalSyncErr(err error) error { |
| - if err == nil { |
| - return nil |
| - } |
| - return &FinalSyncError{Err: err} |
| -} |
| - |
| -// Holding reports whether this lease is still held by this process: its |
| -// renewer runs, for this handle or for the replicator Replicate traded it |
| -// for. It is true from Acquire until Release, the replicator's Close or |
| -// Abandon stops the renewer, and stays true for a lease whose renewal has |
| -// failed until one of those stands it down. The status heartbeat counts it |
| -// (the drain rule's held leases); it authorizes nothing. |
| -func (h *Held) Holding() bool { return h.rn.running() } |
| - |
| -// running reports whether stop has not been called. |
| -func (rn *renewer) running() bool { |
| - rn.mu.Lock() |
| - defer rn.mu.Unlock() |
| - return !rn.stopped |
| -} |
diff --git a/internal/lease/finalsync_test.go b/internal/lease/finalsync_test.go| deleted file mode 100644 |
| index 34a2422b8..000000000 |
| --- a/internal/lease/finalsync_test.go |
| +++ /dev/null |
| @@ -1,158 +0,0 @@ |
| -package lease |
| - |
| -import ( |
| - "context" |
| - "database/sql" |
| - "errors" |
| - "io" |
| - "net/http" |
| - "net/http/httptest" |
| - "path/filepath" |
| - "sync/atomic" |
| - "testing" |
| - "time" |
| - |
| - "github.com/benbjohnson/litestream" |
| - lsfile "github.com/benbjohnson/litestream/file" |
| - "github.com/superfly/ltx" |
| -) |
| - |
| -// refusingReplica is a file replica whose writes fail while refuse is set: |
| -// the bucket refusing the final sync. |
| -type refusingReplica struct { |
| - litestream.ReplicaClient |
| - refuse atomic.Bool |
| -} |
| - |
| -func (r *refusingReplica) WriteLTXFile(ctx context.Context, level int, min, max ltx.TXID, rd io.Reader) (*ltx.FileInfo, error) { |
| - if r.refuse.Load() { |
| - return nil, errors.New("synthetic replica write refusal") |
| - } |
| - return r.ReplicaClient.WriteLTXFile(ctx, level, min, max, rd) |
| -} |
| - |
| -// refusingDeletes is the lock store with every DELETE refused: a release |
| -// that fails after a final sync that worked. |
| -type refusingDeletes struct{ *lockStore } |
| - |
| -func (s refusingDeletes) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| - if r.Method == http.MethodDelete { |
| - w.WriteHeader(http.StatusForbidden) |
| - return |
| - } |
| - s.lockStore.ServeHTTP(w, r) |
| -} |
| - |
| -func heldOn(t *testing.T, h http.Handler) *Held { |
| - t.Helper() |
| - srv := httptest.NewServer(h) |
| - t.Cleanup(srv.Close) |
| - fakeCreds(t) |
| - t.Setenv("CARLOS_S3_ENDPOINT", srv.URL) |
| - held, err := AcquireTTL(context.Background(), "test-bucket", "one.example", "test-region", 10*time.Second) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { _ = held.Release(context.Background()) }) |
| - return held |
| -} |
| - |
| -func writeRow(t *testing.T, path string) { |
| - t.Helper() |
| - db, err := sql.Open("sqlite", path) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - defer db.Close() |
| - if _, err := db.Exec(`INSERT INTO t (body) VALUES ('tail')`); err != nil { |
| - t.Fatal(err) |
| - } |
| -} |
| - |
| -// A Close whose final sync fails says so with a *FinalSyncError, whose text |
| -// is the failure's own; the lease is released anyway. A Close whose sync |
| -// worked but whose release failed is not one: the database's writes are in |
| -// the replica. Holding follows the renewer from Acquire to the Close. |
| -func TestCloseSaysWhenTheFinalSyncFailed(t *testing.T) { |
| - t.Run("sync fails", func(t *testing.T) { |
| - backend := &lockStore{} |
| - h := heldOn(t, backend) |
| - if !h.Holding() { |
| - t.Fatal("a fresh lease is not holding") |
| - } |
| - path := filepath.Join(t.TempDir(), "source.db") |
| - seedDB(t, path) |
| - replica := &refusingReplica{ReplicaClient: lsfile.NewReplicaClient(t.TempDir())} |
| - h.replicaClient = replica |
| - r, err := h.Replicate(context.Background(), path, 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if !h.Holding() { |
| - t.Fatal("the lease stopped holding when replication took it over") |
| - } |
| - writeRow(t, path) |
| - replica.refuse.Store(true) |
| - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| - defer cancel() |
| - err = r.Close(ctx) |
| - var fs *FinalSyncError |
| - if !errors.As(err, &fs) { |
| - t.Fatalf("Close = %v, want a *FinalSyncError", err) |
| - } |
| - if fs.Error() != fs.Err.Error() { |
| - t.Fatalf("the error's text changed: %q, want %q", fs.Error(), fs.Err.Error()) |
| - } |
| - if h.Holding() { |
| - t.Fatal("the lease is still holding after Close") |
| - } |
| - if _, deletes := backend.counts(); deletes != 1 { |
| - t.Fatalf("the lease was not released after the failed sync: %d deletes", deletes) |
| - } |
| - }) |
| - t.Run("release fails", func(t *testing.T) { |
| - backend := &lockStore{} |
| - h := heldOn(t, refusingDeletes{backend}) |
| - path := filepath.Join(t.TempDir(), "source.db") |
| - seedDB(t, path) |
| - h.replicaClient = lsfile.NewReplicaClient(t.TempDir()) |
| - r, err := h.Replicate(context.Background(), path, 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - writeRow(t, path) |
| - err = r.Close(context.Background()) |
| - var fs *FinalSyncError |
| - if err == nil || errors.As(err, &fs) { |
| - t.Fatalf("Close = %v, want a release failure that is not a *FinalSyncError", err) |
| - } |
| - if h.Holding() { |
| - t.Fatal("the lease is still holding after Close") |
| - } |
| - }) |
| - t.Run("clean", func(t *testing.T) { |
| - h := heldOn(t, &lockStore{}) |
| - path := filepath.Join(t.TempDir(), "source.db") |
| - seedDB(t, path) |
| - h.replicaClient = lsfile.NewReplicaClient(t.TempDir()) |
| - r, err := h.Replicate(context.Background(), path, 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err := r.Close(context.Background()); err != nil { |
| - t.Fatal(err) |
| - } |
| - if h.Holding() { |
| - t.Fatal("the lease is still holding after Close") |
| - } |
| - }) |
| - t.Run("released", func(t *testing.T) { |
| - h := heldOn(t, &lockStore{}) |
| - if err := h.Release(context.Background()); err != nil { |
| - t.Fatal(err) |
| - } |
| - if h.Holding() { |
| - t.Fatal("the lease is still holding after Release") |
| - } |
| - }) |
| -} |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 3ce6de7c9..4bb396f45 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -570,10 +570,7 @@ func (r *Replicator) Close(ctx context.Context) error { |
| // the DB now initialized, store.Close's own final sync is the one that |
| // counts, and its error is returned. |
| _ = r.db.SyncAndWait(ctx) |
| - // A failed final sync is a *FinalSyncError (finalsync.go), so a caller |
| - // can tell it from a failed release below: the lease is released either |
| - // way, but only the first leaves writes the bucket does not hold. |
| - err := finalSyncErr(r.store.Close(ctx)) |
| + err := r.store.Close(ctx) |
| lease := r.rn.stop() |
| if lease != nil { |
diff --git a/internal/registry/fleets.go b/internal/registry/fleets.go| index 504eb08ae..b7ff3908d 100644 |
| --- a/internal/registry/fleets.go |
| +++ b/internal/registry/fleets.go |
| @@ -602,8 +602,8 @@ func (r *Registry) SetFleetBoxStatus(fleet, label, status string) error { |
| // SetFleetBoxDraining marks an active box as draining from since (unix |
| // nanoseconds) and answers the start it carries: a box already draining |
| -// keeps its first start, since the drain rule asks for a heartbeat composed |
| -// after the drain began. The box stays active, so FleetChannelAuth still |
| +// keeps its first start: the drain is marked once. The box stays active, |
| +// so FleetChannelAuth still |
| // lists it. An unknown or detached box is an error. Bumps rev only when the |
| // column is written. |
| func (r *Registry) SetFleetBoxDraining(fleet, label string, since int64) (int64, error) { |
diff --git a/internal/status/contract_test.go b/internal/status/contract_test.go| index 7afe8bb5c..e2686bfc9 100644 |
| --- a/internal/status/contract_test.go |
| +++ b/internal/status/contract_test.go |
| @@ -79,14 +79,7 @@ var allowedBoxKeys = map[string][]string{ |
| // Safe on the identical structural ground: BuildFleet's field-by-field |
| // copy never names "metrics", so no hostname here can reach FleetBox or |
| // fleet.json regardless of what this map holds. |
| - // |
| - // "leases_held" and "replication_failures" (managed fleets 1b, the drain |
| - // rule) are COUNTS, like expired_canaries: how many instance leases the |
| - // box holds, and how many hosts' final syncs failed there unresolved. |
| - // No hostname, no tenant. Bucket-private like everything on Box: the |
| - // console reads them to decide a drain is done, and allowedFleetKeys |
| - // below names neither, so BuildFleet can never copy them into fleet.json. |
| - "": {"generated_at", "label", "name", "region", "routes", "load", "capacity", "replication", "adoption_running", "config_path_running", "restart_path_running", "expired_canaries", "metrics", "leases_held", "replication_failures"}, |
| + "": {"generated_at", "label", "name", "region", "routes", "load", "capacity", "replication", "adoption_running", "config_path_running", "restart_path_running", "expired_canaries", "metrics"}, |
| "routes": {"static", "resident", "hibernating", "awake", "asleep"}, |
| "replication": {"healthy", "lag_seconds"}, |
| "metrics": {"mem_total_bytes", "mem_avail_bytes", "load1", "disk_free_bytes", "release", "tunnel", "route_versions", "upstreams", "layout", "config_refusals", "config_refusals_total", "release_refusals", "proof_waits", "config_guard", "build_states", "build_states_err", "update_settings", "updates", "egress", "size_committed_mib"}, |
| @@ -351,13 +344,8 @@ func fixtureProbes() status.Probes { |
| return status.Probes{ |
| MachineID: "test-machine-id", |
| Region: "us-west-1", |
| - // Non-zero drain facts, so leases_held and replication_failures |
| - // are walked with a value in them, and the fleet walk proves |
| - // neither reaches fleet.json. |
| - LeasesHeld: 2, |
| - ReplicationFailures: 1, |
| - Upstreams: upstreams, |
| - Layout: layoutReport, |
| + Upstreams: upstreams, |
| + Layout: layoutReport, |
| // One refusal so metrics.config_refusals is exercised by the |
| // allowlist walk and not merely permitted by it. |
| ConfigRefusals: []status.ConfigRefusal{ |
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go| index c39e3a98c..5335a80ff 100644 |
| --- a/internal/status/snapshot.go |
| +++ b/internal/status/snapshot.go |
| @@ -99,14 +99,6 @@ type Probes struct { |
| // zero; 0 is itself a real, confident answer when every canary route on |
| // the box is fresh, or there are none at all. |
| ExpiredCanaries *int |
| - // LeasesHeld and ReplicationFailures are the drain rule's box facts |
| - // (managed fleets 1b, rule 5), read from the box's activator by the |
| - // caller: the instance leases this process holds right now, and the |
| - // hosts whose final sync failed on this box with no later replication |
| - // landing since. Copied to Box as they are; a box with no activator |
| - // reports 0 for both. |
| - LeasesHeld int |
| - ReplicationFailures int |
| // Alerts is the box's alert-sink answer (see AlertDelivery), carried |
| // into Box.Metrics. nil means "never asked". |
| Alerts *AlertDelivery |
| @@ -810,9 +802,7 @@ type Replication struct { |
| // meant for the public page; Metrics and Sidecars are the two places that |
| // default is intentionally suspended, gated by staying bucket-private (see |
| // the package doc) and excluded from FleetBox by construction (fleet.go's |
| -// BuildFleet copies fields one at a time and never names either). The drain |
| -// rule's two counts (LeasesHeld, ReplicationFailures) name nothing, but are |
| -// bucket-private on the same ground: BuildFleet never names them either. |
| +// BuildFleet copies fields one at a time and never names either). |
| type Box struct { |
| GeneratedAt time.Time `json:"generated_at"` |
| Label string `json:"label"` |
| @@ -875,18 +865,6 @@ type Box struct { |
| // must not reach fleet.json. omitempty keeps a box with no sidecars |
| // byte-identical to one written before this field existed. |
| Sidecars int `json:"sidecars,omitempty"` |
| - // LeasesHeld and ReplicationFailures are the drain rule's two box facts |
| - // (managed fleets 1b, rule 5): how many instance leases this box's |
| - // activator holds right now, and how many hosts' final syncs failed |
| - // here with no later replication landing since (a durable record on |
| - // the box's disk, so an agent restart does not forget it). The console |
| - // detaches a draining box only on a heartbeat composed after the drain |
| - // began with both at 0. Counts only, no host; always on the wire, a |
| - // zero included, and, like Metrics and Sidecars, never copied into |
| - // FleetBox. A ReplicationFailures the box cannot read is reported as at |
| - // least 1, never 0. |
| - LeasesHeld int `json:"leases_held"` |
| - ReplicationFailures int `json:"replication_failures"` |
| } |
| // replHealthyWithin is the lag under which replication counts as healthy. |
| @@ -1125,20 +1103,18 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| } |
| box := Box{ |
| - GeneratedAt: now, |
| - Label: Label(p.MachineID), |
| - Region: p.Region, |
| - Routes: counts, |
| - Load: bandWord(p.MemFrac, loadWords), |
| - Capacity: bandWord(worst, capacityWords), |
| - Replication: Replication{Healthy: healthy, LagSecs: p.LagSecs}, |
| - AdoptionRunning: p.AdoptRunning, |
| - ConfigPathRunning: p.ConfigPathRunning, |
| - RestartPathRunning: p.RestartPathRunning, |
| - ExpiredCanaries: p.ExpiredCanaries, |
| - Sidecars: sidecars, |
| - LeasesHeld: p.LeasesHeld, |
| - ReplicationFailures: p.ReplicationFailures, |
| + GeneratedAt: now, |
| + Label: Label(p.MachineID), |
| + Region: p.Region, |
| + Routes: counts, |
| + Load: bandWord(p.MemFrac, loadWords), |
| + Capacity: bandWord(worst, capacityWords), |
| + Replication: Replication{Healthy: healthy, LagSecs: p.LagSecs}, |
| + AdoptionRunning: p.AdoptRunning, |
| + ConfigPathRunning: p.ConfigPathRunning, |
| + RestartPathRunning: p.RestartPathRunning, |
| + ExpiredCanaries: p.ExpiredCanaries, |
| + Sidecars: sidecars, |
| } |
| // Metrics attaches only when something is known — an all-unknown Probes, |