region HA: drain fix round 1, barrier, release log and held closes
Task 5 fix round 1 (Astra I1-I4, I6, I7; Fable P2 and cheap P3s). - Acknowledgements: the coordinator alone owns the seen map; askers answer on a channel. The failure names each box and why. - The connection drain is a barrier: new requests after it are refused through the bounded exit with today's answer; at the bound contexts are cancelled and connections closed; handlers are joined, and a drain that cannot reach zero fails (ErrDrainNotIdle). - Release outcomes: finishStop records every release in a transaction log from withdraw to the report; any missing or unclean marker fails the drain, idle stops included. After the moves the driver waits for held and quiet rather than failing at once. - A taken host's edge-held streams close at an event boundary, and the connection drain closes the rest first. - Hold statistics are read after the connection barrier. - drain --cancel refuses, and keeps the fence, when the socket does not answer but an edge process runs. - Releases share the four-way semaphore; cancel blocks a racing start; the peer seam is atomic; test fakes share one synchronized recorder. - Carried: the p2b golden gains ha_take, and the name-class inventory is renewed for edgesFileWriteClaims (no name derivation changed).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+3 −0internal/activator/hadrainmove.go+71 −7internal/activator/hadrainmove_test.go+36 −0internal/edge/edge.go+7 −1internal/edge/hadrainconns.go+140 −44internal/edge/hadrainconns_test.go+223 −69internal/host/group_maintenance_drain.go+17 −4internal/host/group_names_test.go+1 −1internal/host/hadrain.go+208 −63internal/host/hadrain_socket_linux.go+12 −3internal/host/hadrain_test.go+357 −129internal/host/hadrainfence_linux_test.go+30 −12internal/host/testdata/edges-p2b-golden.json+1 −1
Intent
<task-notification> <task-id>a40e6294574b2458e</task-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a40e6294574b2458e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: drain driver" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE_WITH_CONCERNS. Commits: - `1b2d6354` region HA: the drain driver, the drain verbs and the start fence - `ceb5f234` census: card and overlay for held-requests Task 5 Tests: the new tests pass (22 in host, plus activator and edge) and the regression runs pass. 23 of 24 mutations fail their tests; M2 survives because it removes a redundant fence check. Concerns: 1. **Fence path needs a ruling.** The maintenance directory is root-only (0700) and the agent runs as `carlos`, so it can't read a fence there. I put it in a root-owned sibling, `/run/carlos-group-fence/fence.json`, created by the same verbs. 2. **No two-box MinIO test.** The driver runs against fakes, and its activator hooks against the real lease fixture. The end-to-end run with the real edge and activator is left to Task 8. 3. **SSE streams are cut at the bound.** Edge-held SSE streams are ended at the 60 s connection bound, not at an event boundary; nothing in the code does that today. Idle HTTP/2 connections are not closed early. 4. **`status` is refused during a drain.** It takes the apply lock like every verb, so Task 6 must read the drain's own output and check `status` afterwards. 5. **Two tests already fail at base acf99931:** `TestEdgesNamedPoolsGolden` and `TestGroupNameClassCensus` in `internal/host`, left over from Tasks 4 and 1. They will fail CI on this branch. Census re-proposed with `NAME=region-ha-held-build` from the cumulative `branch-claims.tsv`. The census test passes; the cross-family verdict on #280 is still owed. Report: `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-held-build/.superpowers/sdd/2026-11-08-region-ha-held-requests/task-5-report.md`</result> <usage><subagent_tokens>398571</subagent_tokens><tool_uses>150</tool_uses><duration_ms>4377912</duration_ms></usage> </task-notification>
<task-notification> <task-id>b6khi0zr9</task-id> <tool-use-id>toolu_01XaLatkLw8fmNDVoxfmsEt4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/b6khi0zr9.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra Task 5 review" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>ae80bad131d5e81d3</task-id> <tool-use-id>toolu_01P6fJArZ7JG5MgANhb1wrRm</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/ae80bad131d5e81d3.output</output-file> <status>completed</status> <summary>Agent "Fable review of Task 5" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Task quality: Needs fixes** (no Critical; spec compliant on steps 1-5, failures, fence, cancel/fence-clear; two Missing items). P1: 0 · P2: 4 (R3.5 SSE event-boundary close missing; two-box MinIO driver test missing; `drain --cancel` lifts the fence on any dial error against a live agent; unclean idle release can escape via `ErrMoveNotHeld`/`ErrDrainStopGone`) · P3: 10. Review written to `.superpowers/sdd/2026-11-08-region-ha-held-requests/task-5-review-fable.md`.</result> <usage><subagent_tokens>191951</subagent_tokens><tool_uses>29</tool_uses><duration_ms>661252</duration_ms></usage> </task-notification>
<task-notification> <task-id>a40e6294574b2458e</task-id> <tool-use-id>toolu_01J734JmhjjEy1riRMyG1Uwp</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/283be278-5c6a-4a71-a8d6-b3d32c668985/tasks/a40e6294574b2458e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: drain driver" is waiting on its own background work</summary> <note>This agent stopped with background work of its own still running. It may resume on its own when that work completes or reports, and the same task-id notifies again if it does; the result below may be interim.</note> <result>The fix mutations are running; I won't touch sources until they finish.</result> <usage><subagent_tokens>481673</subagent_tokens><tool_uses>31</tool_uses><duration_ms>816742</duration_ms></usage> </task-notification>
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 3f00e0b65..c385c99ad 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -1384,6 +1384,8 @@ type Service struct { |
| // moves is the planned handover's per-host state and admission |
| // tickets (handover.go), under mu. |
| moves moveTable |
| + // drainLog is the drain transaction's release log (hadrainmove.go). |
| + drainLog drainReleases |
| mu sync.Mutex |
| entries map[string]*actEntry |
| @@ -5308,6 +5310,7 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| outcome.uncertain = !outcome.complete() |
| e.stopOutcome = outcome |
| a.rememberStopLocked(e.host, outcome) |
| + a.noteDrainReleaseLocked(e) |
| republish := e.worker || a.publishesLocked(e) |
| a.cancelHeldLegsLocked(e, 0) |
| delete(a.entries, e.host) |
diff --git a/internal/activator/hadrainmove.go b/internal/activator/hadrainmove.go| index 592e4f714..795916c6e 100644 |
| --- a/internal/activator/hadrainmove.go |
| +++ b/internal/activator/hadrainmove.go |
| @@ -202,14 +202,78 @@ func (a *Service) DrainStop(ctx context.Context, host string) (DrainRelease, err |
| } |
| a.mu.Lock() |
| defer a.mu.Unlock() |
| - r := DrainRelease{HA: ha, Marker: e.haReleased, Clean: e.haReleased && e.haReleaseClean} |
| - if !ha { |
| - // A lease that is not HA is deleted, never marked: its stop |
| - // outcome says whether the replica closed (the release with it). |
| - r.Marker = e.stopOutcome != nil && e.stopOutcome.replicaClosed |
| - r.Clean = r.Marker |
| + o := drainOutcomeLocked(e) |
| + return DrainRelease{HA: o.HA, Marker: o.Marker, Clean: o.Clean}, nil |
| +} |
| + |
| +// DrainOutcome is one finished stop's release, as the drain records it. |
| +type DrainOutcome struct { |
| + Host string `json:"host"` |
| + HA bool `json:"ha"` |
| + // Marker: a release marker was written (or the lease was no longer |
| + // this box's, a 412). For a lease that is not HA: the replica closed |
| + // (its lease deleted). An entry with no replica holds no lease, and |
| + // counts as released. |
| + Marker bool `json:"marker"` |
| + Clean bool `json:"clean"` |
| +} |
| + |
| +// drainOutcomeLocked is e's release as finishStop left it. Under a.mu. |
| +func drainOutcomeLocked(e *actEntry) DrainOutcome { |
| + _, ha := haEntryRep(e) |
| + o := DrainOutcome{Host: e.host, HA: ha} |
| + switch { |
| + case ha: |
| + o.Marker, o.Clean = e.haReleased, e.haReleased && e.haReleaseClean |
| + case e.rep == nil: |
| + // No replica, so no lease of this entry to release. |
| + o.Marker, o.Clean = true, true |
| + default: |
| + o.Marker = e.stopOutcome != nil && e.stopOutcome.replicaClosed |
| + o.Clean = o.Marker |
| + } |
| + return o |
| +} |
| + |
| +// drainReleases is the drain transaction's release log (R2.11): from |
| +// BeginDrainReleases until EndDrainReleases, every stop that finishes on |
| +// this box (finishStop: idle sleeps, retried pending stops, the drain's |
| +// own stops) records its outcome, so the drain can refuse any unclean or |
| +// missing marker, whichever path wrote it. |
| +type drainReleases struct { |
| + on bool |
| + log []DrainOutcome |
| +} |
| + |
| +// BeginDrainReleases starts recording release outcomes, or keeps the |
| +// recording already running. |
| +func (a *Service) BeginDrainReleases() { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + a.drainLog.on = true |
| +} |
| + |
| +// DrainReleases is every outcome recorded since BeginDrainReleases. |
| +func (a *Service) DrainReleases() []DrainOutcome { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return append([]DrainOutcome(nil), a.drainLog.log...) |
| +} |
| + |
| +// EndDrainReleases stops recording and forgets the log. |
| +func (a *Service) EndDrainReleases() { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + a.drainLog = drainReleases{} |
| +} |
| + |
| +// noteDrainReleaseLocked is finishStop's record of e's release. Under |
| +// a.mu. A stateless generation holds no lease. |
| +func (a *Service) noteDrainReleaseLocked(e *actEntry) { |
| + if !a.drainLog.on || e.gen.Stateless { |
| + return |
| } |
| - return r, nil |
| + a.drainLog.log = append(a.drainLog.log, drainOutcomeLocked(e)) |
| } |
| // DrainTakeOwner is the take timeout's one lock re-read (build ruling, |
diff --git a/internal/activator/hadrainmove_test.go b/internal/activator/hadrainmove_test.go| index d25d370a4..7aebab924 100644 |
| --- a/internal/activator/hadrainmove_test.go |
| +++ b/internal/activator/hadrainmove_test.go |
| @@ -189,3 +189,39 @@ func TestDrainHoldStats(t *testing.T) { |
| t.Fatalf("after reset %+v", st) |
| } |
| } |
| + |
| +// The drain's release log (R2.11): a stop that was already running when |
| +// the drain began (here an idle stop paused in Finish) finishes unclean |
| +// while quiescence waits. The entry is gone, the box is quiet, and the |
| +// log still holds the unclean outcome. Nothing is logged before Begin or |
| +// after End. |
| +func TestDrainReleaseLogKeepsAPausedStopsUncleanOutcome(t *testing.T) { |
| + s, e, _, _, _ := shutdownFixture(t) |
| + r := e.rep.(*shutdownRep) |
| + inner := r.finish |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + r.finish = func(ctx context.Context) (uint64, error) { |
| + close(entered) |
| + <-release |
| + txid, _ := inner(ctx) |
| + return txid, errors.New("final sync: the store refused") |
| + } |
| + s.a.mu.Lock() |
| + s.a.beginStopLocked(e, StopIdle) |
| + s.a.mu.Unlock() |
| + <-entered |
| + s.a.BeginDrainReleases() |
| + if q := s.a.DrainQuietNow(); q.Stopping != 1 { |
| + t.Fatalf("quiet %+v, want the paused stop counted", q) |
| + } |
| + close(release) |
| + waitFor(t, "quiet", func() bool { return s.a.DrainQuietNow().Zero() && len(s.a.DrainHeld()) == 0 }) |
| + got := s.a.DrainReleases() |
| + if len(got) != 1 || got[0].Host != s.rt.Host || !got[0].HA || !got[0].Marker || got[0].Clean { |
| + t.Fatalf("release log %+v, want one unclean marker", got) |
| + } |
| + s.a.EndDrainReleases() |
| + if got := s.a.DrainReleases(); len(got) != 0 { |
| + t.Fatalf("log after End: %+v", got) |
| + } |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 711c4fbc4..b28d316f4 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -1959,7 +1959,13 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| } |
| // Counted for the drain's connection drain (§25.4 step 4): a request in |
| // flight here is one the drain waits for, and ends at its bound. |
| - r, untrack := e.conns.track(w, r) |
| + // After the drain's final barrier a new request is refused at once |
| + // through the bounded exit, with today's answer: never forwarded. |
| + r, untrack, admitted := e.conns.track(w, r) |
| + if !admitted { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + return |
| + } |
| defer untrack() |
| if e.handleDemoRequest(w, r, true) { |
| return |
diff --git a/internal/edge/hadrainconns.go b/internal/edge/hadrainconns.go| index fa53dc8e3..3e6546b98 100644 |
| --- a/internal/edge/hadrainconns.go |
| +++ b/internal/edge/hadrainconns.go |
| @@ -7,6 +7,8 @@ package edge |
| import ( |
| "context" |
| + "errors" |
| + "net" |
| "net/http" |
| "slices" |
| "sync" |
| @@ -62,31 +64,59 @@ func (e *Edge) DrainSnapshot(rt registry.Route) boxchoice.WakeSnapshot { |
| return s |
| } |
| +// drainJoinBound is how long DrainConnections waits, after it has ended |
| +// the requests still running at its bound, for their handlers to return. |
| +// A var so a test can shorten it. |
| +var drainJoinBound = 10 * time.Second |
| + |
| // connDrain is the edge's connection drain (§25.4 step 4): every request |
| // ServeHTTP serves is counted, and can be ended, while the edge runs. |
| +// |
| +// The common path takes one mutex twice per request (register and |
| +// unregister) and allocates a cancellable context; no header is set and |
| +// nothing is refused unless a drain is running. |
| type connDrain struct { |
| + // draining: responses say Connection: close. |
| draining atomic.Bool |
| mu sync.Mutex |
| - next uint64 |
| - active map[uint64]context.CancelFunc |
| - // changed is closed and replaced whenever a request ends while |
| - // draining. |
| + // barrier: closed under mu by DrainConnections; a request arriving |
| + // after it is refused, never counted or forwarded. |
| + barrier bool |
| + next uint64 |
| + active map[uint64]trackedRequest |
| + // changed is closed and replaced whenever a request ends. |
| changed chan struct{} |
| servers []*http.Server |
| } |
| +// trackedRequest is one request in flight: its cancel, and the connection |
| +// it arrived on (nil when the server was not registered with serve). |
| +type trackedRequest struct { |
| + cancel context.CancelFunc |
| + conn net.Conn |
| +} |
| + |
| +type drainConnKey struct{} |
| + |
| // track counts r until the returned func runs, and makes its context |
| -// cancellable by the drain's bound. While draining, the response says |
| -// Connection: close (HTTP/2 reads it as a graceful GOAWAY). |
| -func (d *connDrain) track(w http.ResponseWriter, r *http.Request) (*http.Request, func()) { |
| - ctx, cancel := context.WithCancel(r.Context()) |
| +// cancellable and its connection closable by the drain's bound. ok is |
| +// false once the drain's barrier is closed: the caller refuses r. While |
| +// draining, the response says Connection: close (HTTP/2 reads it as a |
| +// graceful GOAWAY). |
| +func (d *connDrain) track(w http.ResponseWriter, r *http.Request) (*http.Request, func(), bool) { |
| + c, _ := r.Context().Value(drainConnKey{}).(net.Conn) |
| d.mu.Lock() |
| + if d.barrier { |
| + d.mu.Unlock() |
| + return r, func() {}, false |
| + } |
| + ctx, cancel := context.WithCancel(r.Context()) |
| if d.active == nil { |
| - d.active = make(map[uint64]context.CancelFunc) |
| + d.active = make(map[uint64]trackedRequest) |
| } |
| d.next++ |
| id := d.next |
| - d.active[id] = cancel |
| + d.active[id] = trackedRequest{cancel: cancel, conn: c} |
| d.mu.Unlock() |
| if d.draining.Load() { |
| w.Header().Set("Connection", "close") |
| @@ -100,39 +130,35 @@ func (d *connDrain) track(w http.ResponseWriter, r *http.Request) (*http.Request |
| d.changed = nil |
| } |
| d.mu.Unlock() |
| - } |
| + }, true |
| } |
| -// serve registers the edge's listeners' servers, whose idle keep-alive |
| -// connections the drain closes. |
| +// serve registers the edge's listeners' servers: their idle keep-alive |
| +// connections are closed by the drain, and each request's connection is |
| +// recorded (ConnContext, chained after any already set) so the drain can |
| +// close it at its bound. |
| func (d *connDrain) serve(srvs ...*http.Server) { |
| d.mu.Lock() |
| defer d.mu.Unlock() |
| - d.servers = append(d.servers, srvs...) |
| + for _, srv := range srvs { |
| + previous := srv.ConnContext |
| + srv.ConnContext = func(ctx context.Context, c net.Conn) context.Context { |
| + if previous != nil { |
| + ctx = previous(ctx, c) |
| + } |
| + return context.WithValue(ctx, drainConnKey{}, c) |
| + } |
| + d.servers = append(d.servers, srv) |
| + } |
| } |
| -// DrainConnections is §25.4 step 4's connection drain: from now every |
| -// response says Connection: close and idle keep-alive connections are |
| -// closed; it then waits up to bound for the requests still in flight |
| -// (forwarded requests, streams, WebSockets) to finish. Those still running |
| -// at the bound, or when ctx ends, are ended through their contexts, and |
| -// their number is returned: the report's connections closed at the bound. |
| -func (e *Edge) DrainConnections(ctx context.Context, bound time.Duration) int { |
| - d := &e.conns |
| - d.draining.Store(true) |
| - d.mu.Lock() |
| - srvs := append([]*http.Server(nil), d.servers...) |
| - d.mu.Unlock() |
| - for _, s := range srvs { |
| - s.SetKeepAlivesEnabled(false) |
| - } |
| - timer := time.NewTimer(bound) |
| - defer timer.Stop() |
| +// waitIdle waits until no request is in flight, or until done fires. |
| +func (d *connDrain) waitIdle(done <-chan struct{}) bool { |
| for { |
| d.mu.Lock() |
| if len(d.active) == 0 { |
| d.mu.Unlock() |
| - return 0 |
| + return true |
| } |
| if d.changed == nil { |
| d.changed = make(chan struct{}) |
| @@ -141,28 +167,77 @@ func (e *Edge) DrainConnections(ctx context.Context, bound time.Duration) int { |
| d.mu.Unlock() |
| select { |
| case <-ch: |
| - continue |
| - case <-timer.C: |
| - case <-ctx.Done(): |
| + case <-done: |
| + return false |
| } |
| - d.mu.Lock() |
| - n := len(d.active) |
| - for _, cancel := range d.active { |
| - cancel() |
| + } |
| +} |
| + |
| +// ErrDrainNotIdle is a connection drain that could not establish zero |
| +// requests in flight: handlers still running after their contexts were |
| +// cancelled and their connections closed. |
| +var ErrDrainNotIdle = errors.New("connection drain: requests are still in flight after their connections were closed") |
| + |
| +// DrainConnections is §25.4 step 4's connection drain, a barrier: |
| +// |
| +// 1. from now no new request is served (the barrier: today's 503 with |
| +// Retry-After through the bounded exit), every response says |
| +// Connection: close, idle keep-alive connections are closed, and the |
| +// edge-held streams still open here are closed at an event boundary; |
| +// 2. it waits up to bound for the requests still in flight (forwarded |
| +// requests, streams, WebSockets) to finish; |
| +// 3. those still running at the bound, or when ctx ends, are ended: their |
| +// contexts are cancelled and their connections closed (a hijacked |
| +// WebSocket included). Their number is returned: the report's |
| +// connections closed at the bound; |
| +// 4. it joins them: their handlers must return within drainJoinBound, or |
| +// the drain fails with ErrDrainNotIdle. |
| +// |
| +// On success nothing is in flight and nothing new is admitted until |
| +// EndConnectionDrain. |
| +func (e *Edge) DrainConnections(ctx context.Context, bound time.Duration) (int, error) { |
| + d := &e.conns |
| + d.mu.Lock() |
| + d.barrier = true |
| + srvs := append([]*http.Server(nil), d.servers...) |
| + d.mu.Unlock() |
| + d.draining.Store(true) |
| + for _, s := range srvs { |
| + s.SetKeepAlivesEnabled(false) |
| + } |
| + e.closeAllHeld() |
| + wctx, wcancel := context.WithTimeout(ctx, bound) |
| + defer wcancel() |
| + if d.waitIdle(wctx.Done()) { |
| + return 0, nil |
| + } |
| + d.mu.Lock() |
| + n := len(d.active) |
| + for _, t := range d.active { |
| + t.cancel() |
| + if t.conn != nil { |
| + _ = t.conn.Close() |
| } |
| - d.mu.Unlock() |
| - return n |
| } |
| + d.mu.Unlock() |
| + jctx, jcancel := context.WithTimeout(context.Background(), drainJoinBound) |
| + defer jcancel() |
| + if !d.waitIdle(jctx.Done()) { |
| + return n, ErrDrainNotIdle |
| + } |
| + return n, nil |
| } |
| -// EndConnectionDrain undoes DrainConnections (drain --cancel): keep-alives |
| -// come back and responses no longer close their connections. |
| +// EndConnectionDrain undoes DrainConnections (drain --cancel): the barrier |
| +// opens, keep-alives come back and responses no longer close their |
| +// connections. |
| func (e *Edge) EndConnectionDrain() { |
| d := &e.conns |
| - d.draining.Store(false) |
| d.mu.Lock() |
| + d.barrier = false |
| srvs := append([]*http.Server(nil), d.servers...) |
| d.mu.Unlock() |
| + d.draining.Store(false) |
| for _, s := range srvs { |
| s.SetKeepAlivesEnabled(true) |
| } |
| @@ -174,3 +249,24 @@ func (e *Edge) InFlight() int { |
| defer e.conns.mu.Unlock() |
| return len(e.conns.active) |
| } |
| + |
| +// CloseHeldHost closes host's edge-held streams on this edge at their next |
| +// event boundary (the held task writes only whole events, and its close |
| +// arm runs between them), so each browser reconnects with Last-Event-ID |
| +// to the confirmed holder (§25.4 step 3.5, R3.5). Memory only. |
| +func (e *Edge) CloseHeldHost(host string) { |
| + if e.held != nil { |
| + e.held.closeHost(host) |
| + } |
| +} |
| + |
| +// closeAllHeld closes every edge-held stream on this edge the same way |
| +// (§25.4 step 4). |
| +func (e *Edge) closeAllHeld() { |
| + if e.held == nil { |
| + return |
| + } |
| + for _, h := range e.held.hosts() { |
| + e.held.closeHost(h) |
| + } |
| +} |
diff --git a/internal/edge/hadrainconns_test.go b/internal/edge/hadrainconns_test.go| index 68c0c105d..024f35a86 100644 |
| --- a/internal/edge/hadrainconns_test.go |
| +++ b/internal/edge/hadrainconns_test.go |
| @@ -2,10 +2,13 @@ package edge |
| import ( |
| "context" |
| + "errors" |
| "io" |
| "net/http" |
| "net/http/httptest" |
| "slices" |
| + "strings" |
| + "sync/atomic" |
| "testing" |
| "time" |
| @@ -36,12 +39,17 @@ func TestDrainAckPeersAreTheLiveBoxes(t *testing.T) { |
| } |
| } |
| -// drainServer is an edge-shaped server whose handler counts its requests |
| -// through the connection drain, as ServeHTTP does. |
| +// drainServer is an edge-shaped server whose handler goes through the |
| +// connection drain as ServeHTTP does: refused after the barrier, counted |
| +// otherwise. |
| func drainServer(t *testing.T, d *connDrain, h http.HandlerFunc) *httptest.Server { |
| t.Helper() |
| srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| - r, done := d.track(w, r) |
| + r, done, ok := d.track(w, r) |
| + if !ok { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + return |
| + } |
| defer done() |
| h(w, r) |
| })) |
| @@ -51,75 +59,205 @@ func drainServer(t *testing.T, d *connDrain, h http.HandlerFunc) *httptest.Serve |
| return srv |
| } |
| -// The connection drain: Connection: close on every response from then on, |
| -// a wait for requests in flight, and those still running at the bound |
| -// ended and counted. |
| -func TestDrainConnections(t *testing.T) { |
| +func drainGet(t *testing.T, srv *httptest.Server, path string) *http.Response { |
| + t.Helper() |
| + resp, err := srv.Client().Get(srv.URL + path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp |
| +} |
| + |
| +// The barrier: Connection: close from the drain on, nothing new admitted |
| +// after it (today's 503, never reaching a handler) until |
| +// EndConnectionDrain; with nothing in flight it returns at once. |
| +func TestDrainConnectionsBarrier(t *testing.T) { |
| + e := &Edge{} |
| + var served atomic.Int32 |
| + srv := drainServer(t, &e.conns, func(w http.ResponseWriter, r *http.Request) { |
| + served.Add(1) |
| + io.WriteString(w, "ok") |
| + }) |
| + resp := drainGet(t, srv, "/") |
| + resp.Body.Close() |
| + if resp.Close || resp.StatusCode != 200 { |
| + t.Fatal("Connection: close or a refusal before the drain") |
| + } |
| + if n, err := e.DrainConnections(context.Background(), time.Minute); n != 0 || err != nil { |
| + t.Fatalf("drain with nothing in flight: %d %v", n, err) |
| + } |
| + resp = drainGet(t, srv, "/") |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "10" || !resp.Close || served.Load() != 1 { |
| + t.Fatalf("after the barrier: %d %v, served %d", resp.StatusCode, resp.Header, served.Load()) |
| + } |
| + e.EndConnectionDrain() |
| + resp = drainGet(t, srv, "/") |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || resp.Close || served.Load() != 2 { |
| + t.Fatalf("after EndConnectionDrain: %d", resp.StatusCode) |
| + } |
| +} |
| + |
| +// A request that finishes within the bound is waited for, not ended, and |
| +// a request arriving while the drain waits (crossing the barrier) is |
| +// refused, not counted. |
| +func TestDrainConnectionsWaitsAndRefusesLateRequests(t *testing.T) { |
| e := &Edge{} |
| release := make(chan struct{}) |
| - ended := make(chan error, 1) |
| + var late atomic.Int32 |
| srv := drainServer(t, &e.conns, func(w http.ResponseWriter, r *http.Request) { |
| - if r.URL.Path == "/long" { |
| - w.WriteHeader(200) |
| - w.(http.Flusher).Flush() |
| - select { |
| - case <-r.Context().Done(): |
| - ended <- r.Context().Err() |
| - case <-release: |
| - ended <- nil |
| - } |
| + if r.URL.Path == "/late" { |
| + late.Add(1) |
| return |
| } |
| - io.WriteString(w, "ok") |
| + w.WriteHeader(200) |
| + w.(http.Flusher).Flush() |
| + <-release |
| }) |
| - get := func(path string) *http.Response { |
| - resp, err := srv.Client().Get(srv.URL + path) |
| - if err != nil { |
| - t.Fatal(err) |
| + long := drainGet(t, srv, "/long") |
| + defer long.Body.Close() |
| + waitInFlight(t, e, 1) |
| + done := make(chan error, 1) |
| + go func() { |
| + n, err := e.DrainConnections(context.Background(), 5*time.Second) |
| + if n != 0 && err == nil { |
| + err = errors.New("a finished request was counted as closed") |
| } |
| - return resp |
| - } |
| - resp := get("/short") |
| + done <- err |
| + }() |
| + waitFor(t, time.Second, "the barrier", func() bool { |
| + e.conns.mu.Lock() |
| + defer e.conns.mu.Unlock() |
| + return e.conns.barrier |
| + }) |
| + resp := drainGet(t, srv, "/late") |
| resp.Body.Close() |
| - if resp.Close || resp.Header.Get("Connection") == "close" { |
| - t.Fatal("Connection: close before the drain") |
| + if resp.StatusCode != http.StatusServiceUnavailable || late.Load() != 0 || e.InFlight() != 1 { |
| + t.Fatalf("a late request: %d, handler ran %d, in flight %d", resp.StatusCode, late.Load(), e.InFlight()) |
| } |
| - // Nothing in flight: the drain returns at once with nothing closed. |
| - if n := e.DrainConnections(context.Background(), time.Minute); n != 0 { |
| - t.Fatalf("closed %d with nothing in flight", n) |
| + close(release) |
| + if err := <-done; err != nil { |
| + t.Fatal(err) |
| } |
| - resp = get("/short") |
| - resp.Body.Close() |
| - if !resp.Close { |
| - t.Fatal("no Connection: close while draining") |
| + if e.InFlight() != 0 { |
| + t.Fatal("the drain returned with a request in flight") |
| } |
| - e.EndConnectionDrain() |
| - // A request that finishes within the bound is waited for, not closed. |
| - long := get("/long") |
| - go func() { time.Sleep(50 * time.Millisecond); close(release) }() |
| - if n := e.DrainConnections(context.Background(), 5*time.Second); n != 0 { |
| - t.Fatalf("closed %d, want the finished request waited for", n) |
| +} |
| + |
| +// At the bound: a handler that ignores its context but is blocked on its |
| +// connection (reading a body that never comes) ends when the connection |
| +// is closed, is counted, and is joined before the drain returns. |
| +func TestDrainConnectionsClosesTheConnectionAtTheBound(t *testing.T) { |
| + e := &Edge{} |
| + entered := make(chan struct{}) |
| + srv := drainServer(t, &e.conns, func(w http.ResponseWriter, r *http.Request) { |
| + close(entered) |
| + _, _ = io.ReadAll(r.Body) // ignores the context: only the connection's close ends it |
| + }) |
| + pr, pw := io.Pipe() |
| + defer pw.Close() |
| + go func() { |
| + req, _ := http.NewRequest("POST", srv.URL+"/upload", pr) |
| + req.ContentLength = -1 |
| + if resp, err := srv.Client().Do(req); err == nil { |
| + resp.Body.Close() |
| + } |
| + }() |
| + _, _ = pw.Write([]byte("partial")) |
| + <-entered |
| + n, err := e.DrainConnections(context.Background(), 100*time.Millisecond) |
| + if n != 1 || err != nil { |
| + t.Fatalf("closed %d, %v; want 1 and joined", n, err) |
| } |
| - if err := <-ended; err != nil { |
| - t.Fatalf("the waited-for request ended with %v", err) |
| + if e.InFlight() != 0 { |
| + t.Fatal("returned before the handler left") |
| } |
| - long.Body.Close() |
| - e.EndConnectionDrain() |
| - // One still running at the bound is ended and counted. |
| - release = make(chan struct{}) |
| - long = get("/long") |
| - defer long.Body.Close() |
| +} |
| + |
| +// A handler that ignores both its context and its connection cannot be |
| +// joined: the drain fails, it never reports zero. |
| +func TestDrainConnectionsFailsWhenZeroIsNotReached(t *testing.T) { |
| + prev := drainJoinBound |
| + drainJoinBound = 100 * time.Millisecond |
| + defer func() { drainJoinBound = prev }() |
| + e := &Edge{} |
| + stuck := make(chan struct{}) |
| + defer close(stuck) |
| + srv := drainServer(t, &e.conns, func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(200) |
| + w.(http.Flusher).Flush() |
| + <-stuck |
| + }) |
| + resp := drainGet(t, srv, "/stuck") |
| + defer resp.Body.Close() |
| + waitInFlight(t, e, 1) |
| + n, err := e.DrainConnections(context.Background(), 50*time.Millisecond) |
| + if n != 1 || !errors.Is(err, ErrDrainNotIdle) { |
| + t.Fatalf("closed %d, %v; want ErrDrainNotIdle", n, err) |
| + } |
| +} |
| + |
| +// A taken host's edge-held streams close at the next event boundary: the |
| +// browser has every whole event, never a part of the next. |
| +func TestCloseHeldHostAtAnEventBoundary(t *testing.T) { |
| + sent := make(chan struct{}) |
| + h := newHeldHarness(t, heldTestConfig(), func(n int, w http.ResponseWriter, r *http.Request) { |
| + sseHead(w) |
| + sseSend(w, "id: 1\ndata: whole\n\n") |
| + sseSend(w, "id: 2\ndata: par") |
| + close(sent) |
| + <-r.Context().Done() |
| + }) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + <-sent |
| + waitFor(t, time.Second, "held", func() bool { return len(h.e.held.hosts()) == 1 }) |
| + time.Sleep(50 * time.Millisecond) // the partial event reaches the task |
| + h.e.CloseHeldHost(heldTestHost) |
| + body, err := readFor(resp.Body, time.Second) |
| + if err != io.EOF { |
| + t.Fatalf("stream did not end: %v", err) |
| + } |
| + if !strings.Contains(body, "id: 1\ndata: whole\n\n") || strings.Contains(body, "par") { |
| + t.Fatalf("body %q: want the whole event and nothing of the next", body) |
| + } |
| + if r := <-h.ends; r != heldCloseUnmanaged { |
| + t.Fatalf("close reason %v", r) |
| + } |
| + (&Edge{}).CloseHeldHost(heldTestHost) // no held set: nothing to do |
| +} |
| + |
| +// The connection drain closes the held streams still open here first, so |
| +// they do not hold the drain to its bound. |
| +func TestDrainConnectionsClosesHeldStreams(t *testing.T) { |
| + h := newHeldHarness(t, heldTestConfig(), func(int, http.ResponseWriter, *http.Request) {}) |
| + h.act.asleep.Store(true) |
| + rt := registry.Route{Host: heldTestHost} |
| + h.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + r, done, ok := h.e.conns.track(w, r) |
| + if !ok { |
| + handoverExit(w, r, answerHolderUnreachable) |
| + return |
| + } |
| + defer done() |
| + h.e.serveHeld(w, r, rt, h.proxy) |
| + })) |
| + h.e.conns.serve(h.srv.Config) |
| + h.start(t) |
| + resp := h.get(t, "/live?carlos_hold=1", nil) |
| + waitFor(t, time.Second, "held", func() bool { return len(h.e.held.hosts()) == 1 }) |
| start := time.Now() |
| - if n := e.DrainConnections(context.Background(), 100*time.Millisecond); n != 1 { |
| - t.Fatalf("closed %d at the bound, want 1", n) |
| + n, err := h.e.DrainConnections(context.Background(), 10*time.Second) |
| + if n != 0 || err != nil || time.Since(start) > 5*time.Second { |
| + t.Fatalf("drain: %d %v after %s", n, err, time.Since(start)) |
| } |
| - if time.Since(start) < 100*time.Millisecond { |
| - t.Fatal("the drain did not wait for its bound") |
| + if _, err := readFor(resp.Body, time.Second); err != io.EOF { |
| + t.Fatalf("held stream did not end: %v", err) |
| } |
| - if err := <-ended; err == nil { |
| - t.Fatal("the request running at the bound was not ended") |
| + if r := <-h.ends; r != heldCloseUnmanaged { |
| + t.Fatalf("close reason %v", r) |
| } |
| - waitInFlight(t, e, 0) |
| } |
| func waitInFlight(t *testing.T, e *Edge, n int) { |
| @@ -133,9 +271,10 @@ func waitInFlight(t *testing.T, e *Edge, n int) { |
| t.Fatalf("in flight %d, want %d", e.InFlight(), n) |
| } |
| -// Through the real ServeHTTP: a forwarded request in flight is counted, |
| -// a response while draining says Connection: close, and a request still |
| -// running at the bound is ended and counted. |
| +// Through the real ServeHTTP: a forwarded request in flight is counted, a |
| +// response while draining says Connection: close... and after the |
| +// barrier a new request is refused; the one still running at the bound |
| +// is ended, counted and joined. |
| func TestDrainConnectionsThroughServeHTTP(t *testing.T) { |
| release := make(chan struct{}) |
| backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| @@ -169,28 +308,43 @@ func TestDrainConnectionsThroughServeHTTP(t *testing.T) { |
| req.Host = "app.example.com" |
| return srv.Client().Do(req) |
| } |
| + short, err := get("/short") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + short.Body.Close() |
| + if short.StatusCode != 200 || short.Close { |
| + t.Fatal("before the drain") |
| + } |
| resp, err := get("/long") |
| if err != nil { |
| t.Fatal(err) |
| } |
| defer resp.Body.Close() |
| waitInFlight(t, e, 1) |
| - done := make(chan int, 1) |
| - go func() { done <- e.DrainConnections(context.Background(), 300*time.Millisecond) }() |
| + type result struct { |
| + n int |
| + err error |
| + } |
| + done := make(chan result, 1) |
| + go func() { |
| + n, err := e.DrainConnections(context.Background(), 300*time.Millisecond) |
| + done <- result{n, err} |
| + }() |
| time.Sleep(50 * time.Millisecond) |
| - short, err := get("/short") |
| + late, err := get("/short") |
| if err != nil { |
| t.Fatal(err) |
| } |
| - short.Body.Close() |
| - if !short.Close { |
| - t.Fatal("a response while draining kept its connection") |
| + late.Body.Close() |
| + if late.StatusCode != http.StatusServiceUnavailable || !late.Close { |
| + t.Fatalf("a request after the barrier: %d", late.StatusCode) |
| + } |
| + if r := <-done; r.n != 1 || r.err != nil { |
| + t.Fatalf("drain %+v, want 1 closed and joined", r) |
| } |
| - if n := <-done; n != 1 { |
| - t.Fatalf("closed %d at the bound, want 1", n) |
| + if e.InFlight() != 0 { |
| + t.Fatal("the drain returned with a request in flight") |
| } |
| - // The proxied stream ends at the bound (an error or an EOF), and the |
| - // edge no longer counts it. |
| _, _ = io.ReadAll(resp.Body) |
| - waitInFlight(t, e, 0) |
| } |
diff --git a/internal/host/group_maintenance_drain.go b/internal/host/group_maintenance_drain.go| index 1183efc27..f2cc9d0ba 100644 |
| --- a/internal/host/group_maintenance_drain.go |
| +++ b/internal/host/group_maintenance_drain.go |
| @@ -13,7 +13,10 @@ import ( |
| "time" |
| ) |
| -var errDrainFailed = errors.New("drain failed") |
| +var ( |
| + errDrainFailed = errors.New("drain failed") |
| + errDrainSocketDown = errors.New("the edge runs but its drain socket does not answer; the fence stays") |
| +) |
| // runDrain is drain <txn>: the withdraw step, the start fence, then the |
| // move step. It prints the agent's last report, and succeeds only when the |
| @@ -57,7 +60,8 @@ func (cmd *groupMaintenanceCommand) runDrain(ctx context.Context, out io.Writer) |
| // runDrainCancel is drain --cancel <txn>: the agent ends its drain of txn, |
| // then the fence of txn goes. Another transaction's drain or fence |
| // refuses, and nothing is removed. An agent that is not running holds no |
| -// drain state, so only the fence is removed then. |
| +// drain state, so only the fence is removed then; an edge process that |
| +// runs but does not answer refuses, and the fence stays. |
| func (cmd *groupMaintenanceCommand) runDrainCancel(ctx context.Context) error { |
| fence := cmd.fenceAt() |
| if f := fence.read(); f.Present && (f.Err != nil || f.Transaction != cmd.txn) { |
| @@ -65,8 +69,17 @@ func (cmd *groupMaintenanceCommand) runDrainCancel(ctx context.Context) error { |
| } |
| ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| defer cancel() |
| - if err := cmd.drainSocket().cancel(ctx, cmd.txn); err != nil && !errors.Is(err, errDrainAgentDown) { |
| - return err |
| + if err := cmd.drainSocket().cancel(ctx, cmd.txn); err != nil { |
| + if !errors.Is(err, errDrainAgentDown) { |
| + return err |
| + } |
| + // The socket does not answer. That proves no drain state only if |
| + // no agent runs: an edge process whose socket failed to start may |
| + // still be draining, and lifting its fence would leave it so, |
| + // unfenced. |
| + if pid, _, perr := cmd.edge(ctx); perr == nil && pid > 0 { |
| + return errDrainSocketDown |
| + } |
| } |
| return fence.remove(cmd.txn) |
| } |
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go| index d6fefe7a8..a41b0631b 100644 |
| --- a/internal/host/group_names_test.go |
| +++ b/internal/host/group_names_test.go |
| @@ -442,7 +442,7 @@ var groupNameProducerInventory = map[string]string{ |
| "claimunit_binding.go:claimUnitShape.route": "f38fd6e10aba680354ee908c255fd34e731fe2d1a22fffd41ac449e8b763dd2c", |
| "claimunit_policy.go:claimUnitShapeCheck": "45f16830e5ed834995ca573a710f1e390a504b7eb78c3c0465ac70e7f306e50c", |
| "claimunit_policy.go:rootClaimRestartShape": "1d0370516c32482b1784f4bd4ab0deb042c31120d81f4dc8c417f52b24ef76ac", |
| - "edgesfile.go:edgesFileWriteClaims": "db2cee40a66e82362acf832cf4dddef95cf29451cdc3b1b6f1910b392540e95e", |
| + "edgesfile.go:edgesFileWriteClaims": "2bf28c120263e519a95d167e0aba903a283644a9816670d1b451c500679d9ce1", // held-requests: drain report and forced drain publish only; no name derivation |
| "movesheldenv.go:composeHeldEnv": "17ad3714758d1c07a71375734c125496855a16ca800eb814bde58283d3a5318b", |
| "movesheldrelease_root.go:heldReleaseRoute": "10bf824edc963319a38a47b91877b865977b1dc4a27c6e7680c46704289a7df7", |
| "movesstage.go:heldReleasePublished": "edad51c04a01657b77a9fc469404db5fde51cff1f2c61e243d6a717fb6224e85", |
diff --git a/internal/host/hadrain.go b/internal/host/hadrain.go| index db53253a6..ad4651aeb 100644 |
| --- a/internal/host/hadrain.go |
| +++ b/internal/host/hadrain.go |
| @@ -65,7 +65,8 @@ func newIncarnation() string { |
| return hex.EncodeToString(b[:]) |
| } |
| -// drainDeadline is 15 minutes plus 1 minute per 20 awake hosts. |
| +// drainDeadline is 15 minutes plus 1 minute per 20 awake hosts: per |
| +// whole 20, rounded down (45 hosts get 17 minutes). |
| func drainDeadline(awake int) time.Duration { |
| return drainDeadlineBase + time.Duration(awake/20)*drainDeadlinePer20 |
| } |
| @@ -87,6 +88,9 @@ type drainActivator interface { |
| DrainTakeOwner(ctx context.Context, rt registry.Route) (string, int64, bool) |
| ResetDrainHoldStats() |
| DrainHoldStatsNow() activator.DrainHoldStats |
| + BeginDrainReleases() |
| + DrainReleases() []activator.DrainOutcome |
| + EndDrainReleases() |
| } |
| // drainEdge is the edge's half (internal/edge hadrain.go, hatake.go, |
| @@ -98,8 +102,9 @@ type drainEdge interface { |
| PeerDraining(ref string) bool |
| DrainSnapshot(rt registry.Route) boxchoice.WakeSnapshot |
| Take(ctx context.Context, peer, host, lifetime string, markerGen int64, txn string) (string, int64, error) |
| - DrainConnections(ctx context.Context, bound time.Duration) int |
| + DrainConnections(ctx context.Context, bound time.Duration) (int, error) |
| EndConnectionDrain() |
| + CloseHeldHost(host string) |
| } |
| // drainMarks is the box's drain state (hadrainstate.go). |
| @@ -187,6 +192,8 @@ type drainDriver struct { |
| deadline time.Time |
| // withdrawn is set once the withdraw step succeeded for txn. |
| withdrawn bool |
| + // cancelling is set while cancel joins and clears: no step starts. |
| + cancelling bool |
| } |
| type drainRun struct { |
| @@ -200,6 +207,7 @@ var ( |
| errDrainNoFence = errors.New("the start fence for this transaction is not installed") |
| errDrainStep = errors.New("withdraw must succeed before move") |
| errDrainUnknown = errors.New("unknown drain step") |
| + errDrainCancel = errors.New("the drain is being cancelled") |
| ) |
| func newDrainDriver(act drainActivator, e drainEdge, marks drainMarks, fence func() fenceState) *drainDriver { |
| @@ -218,6 +226,9 @@ func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| } |
| d.mu.Lock() |
| defer d.mu.Unlock() |
| + if d.cancelling { |
| + return nil, errDrainCancel |
| + } |
| if d.txn != "" && d.txn != txn { |
| return nil, errDrainOtherTxn |
| } |
| @@ -250,6 +261,9 @@ func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| } |
| if step == "withdraw" { |
| d.withdrawn = false |
| + // The transaction's release log (R2.11): every stop that finishes |
| + // from here to the report is checked, whichever path ran it. |
| + d.act.BeginDrainReleases() |
| } |
| d.txn = txn |
| ctx, cancel := context.WithDeadline(context.Background(), d.deadline) |
| @@ -312,12 +326,22 @@ func (d *drainDriver) cancel(ctx context.Context, txn string) error { |
| return errGroupMaintenance |
| } |
| d.mu.Lock() |
| + if d.cancelling { |
| + d.mu.Unlock() |
| + return errDrainCancel |
| + } |
| if d.txn != "" && d.txn != txn { |
| d.mu.Unlock() |
| return errDrainOtherTxn |
| } |
| + d.cancelling = true |
| r := d.run |
| d.mu.Unlock() |
| + defer func() { |
| + d.mu.Lock() |
| + d.cancelling = false |
| + d.mu.Unlock() |
| + }() |
| if r != nil { |
| r.cancel() |
| select { |
| @@ -327,6 +351,7 @@ func (d *drainDriver) cancel(ctx context.Context, txn string) error { |
| } |
| } |
| d.act.EndDrainMoves() |
| + d.act.EndDrainReleases() |
| d.edge.EndConnectionDrain() |
| d.marks.clear() |
| d.mu.Lock() |
| @@ -382,39 +407,57 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| actx, acancel := context.WithTimeout(ctx, drainAckBound) |
| defer acancel() |
| peers := d.edge.DrainAckPeers(d.now()) |
| + // Only this goroutine reads or writes seen and why; the askers send |
| + // their answers back on a channel. |
| seen := map[string]bool{} |
| + why := map[string]string{} |
| + type answer struct { |
| + peer string |
| + ok bool |
| + err error |
| + } |
| tick := time.NewTicker(drainAckEvery) |
| defer tick.Stop() |
| for { |
| - var wg sync.WaitGroup |
| - var mu sync.Mutex |
| + var pending []string |
| for _, p := range peers { |
| - if seen[p] { |
| - continue |
| + if !seen[p] { |
| + pending = append(pending, p) |
| } |
| - wg.Add(1) |
| + } |
| + if len(pending) == 0 { |
| + d.note(func() { rep.Acked = append([]string(nil), peers...) }) |
| + return nil |
| + } |
| + answers := make(chan answer, len(pending)) |
| + for _, p := range pending { |
| go func(p string) { |
| - defer wg.Done() |
| rctx, rcancel := context.WithTimeout(actx, drainAckEvery) |
| defer rcancel() |
| - if ok, err := d.edge.AskDrainSeen(rctx, p, txn, phase, mark.ID); err == nil && ok { |
| - mu.Lock() |
| - seen[p] = true |
| - mu.Unlock() |
| - } |
| + ok, err := d.edge.AskDrainSeen(rctx, p, txn, phase, mark.ID) |
| + answers <- answer{p, ok, err} |
| }(p) |
| } |
| - wg.Wait() |
| + for range pending { |
| + a := <-answers |
| + switch { |
| + case a.err == nil && a.ok: |
| + seen[a.peer] = true |
| + case a.err != nil: |
| + why[a.peer] = a.err.Error() |
| + default: |
| + why[a.peer] = "not seen yet" |
| + } |
| + } |
| + if allSeen(peers, seen) { |
| + continue |
| + } |
| var missing []string |
| for _, p := range peers { |
| if !seen[p] { |
| - missing = append(missing, p) |
| + missing = append(missing, p+" ("+why[p]+")") |
| } |
| } |
| - if len(missing) == 0 { |
| - d.note(func() { rep.Acked = append([]string(nil), peers...) }) |
| - return nil |
| - } |
| select { |
| case <-actx.Done(): |
| return []string{fmt.Sprintf("the %s state was not acknowledged by %v", phase, missing)} |
| @@ -423,8 +466,74 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| } |
| } |
| -// move is steps 2 to 5. |
| +func allSeen(peers []string, seen map[string]bool) bool { |
| + for _, p := range peers { |
| + if !seen[p] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// move is steps 2 to 5, then the transaction's release audit and the |
| +// hold statistics, both read after the connection barrier has joined |
| +// every request (so every held request's outcome is counted). |
| func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) []string { |
| + reasons := d.moveSteps(ctx, txn, rep) |
| + reasons = append(reasons, d.auditReleases(rep)...) |
| + d.note(func() { |
| + st := d.act.DrainHoldStatsNow() |
| + rep.Holds = drainHolds{LongestMS: st.Longest.Milliseconds(), Todays: st.Todays, RefusedAtOnce: st.RefusedAtOnce} |
| + }) |
| + return reasons |
| +} |
| + |
| +// auditReleases checks every release recorded since the withdraw (R2.11): |
| +// any stop that finished without a marker, or with an unclean one, fails |
| +// the drain, whatever path ran it (an idle sleep during quiescence or |
| +// between the host list and its move, a retried pending stop, the drain's |
| +// own stop). A host released outside the drain's own stops is listed as |
| +// released, kind "idle". |
| +func (d *drainDriver) auditReleases(rep *drainReport) []string { |
| + var reasons []string |
| + outcomes := d.act.DrainReleases() |
| + d.note(func() { |
| + known := map[string]bool{} |
| + for _, m := range rep.Moved { |
| + known[m.Host] = true |
| + } |
| + for _, r := range rep.Released { |
| + known[r.Host] = true |
| + } |
| + flagged := map[string]bool{} |
| + for _, h := range rep.Unclean { |
| + flagged[h] = true |
| + } |
| + for _, l := range rep.Left { |
| + flagged[l.Host] = true |
| + } |
| + for _, o := range outcomes { |
| + bad := !o.Marker || !o.Clean |
| + if bad && !flagged[o.Host] { |
| + flagged[o.Host] = true |
| + if o.Marker { |
| + rep.Unclean = append(rep.Unclean, o.Host) |
| + reasons = append(reasons, o.Host+": a release in this drain was unclean") |
| + } else { |
| + reasons = append(reasons, o.Host+": a release in this drain wrote no marker") |
| + } |
| + } |
| + if !known[o.Host] && !flagged[o.Host] { |
| + known[o.Host] = true |
| + rep.Released = append(rep.Released, drainLeft{Host: o.Host, Kind: "idle", Marker: o.Marker, Clean: o.Clean}) |
| + } |
| + } |
| + }) |
| + return reasons |
| +} |
| + |
| +// moveSteps is steps 2 to 5. |
| +func (d *drainDriver) moveSteps(ctx context.Context, txn string, rep *drainReport) []string { |
| fence := func() bool { |
| f := d.fence() |
| return f.Present && f.Err == nil && f.Transaction == txn |
| @@ -437,7 +546,7 @@ func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) [] |
| if err := d.quiesce(ctx); err != nil { |
| return []string{fmt.Sprintf("the box did not settle: %v", err)} |
| } |
| - // Step 3: the moves, busiest first, at most 4 at a time. |
| + // Step 3: the moves and releases, busiest first, at most 4 at a time. |
| d.act.ResetDrainHoldStats() |
| var reasons []string |
| var rmu sync.Mutex |
| @@ -450,58 +559,37 @@ func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) [] |
| var wg sync.WaitGroup |
| for _, h := range d.act.DrainHosts() { |
| h := h |
| - if !h.Movable { |
| - // An always-on worker, or a host that is not HA: released with |
| - // its marker through the normal stop, never taken (build ruling, |
| - // spec §25.4 step 3.4). |
| - rel, err := d.act.DrainStop(ctx, h.Route.Host) |
| - kind := "other" |
| - if h.Worker { |
| - kind = "worker" |
| - } |
| - left := drainLeft{Host: h.Route.Host, Kind: kind, Marker: rel.Marker, Clean: rel.Clean} |
| - switch { |
| - case errors.Is(err, activator.ErrDrainStopGone): |
| - continue |
| - case err != nil: |
| - left.Reason = err.Error() |
| - fail(fmt.Sprintf("%s: the release did not finish: %v", h.Route.Host, err)) |
| - case !rel.Marker: |
| - fail(fmt.Sprintf("%s: released without a marker", h.Route.Host)) |
| - case !rel.Clean: |
| - fail(fmt.Sprintf("%s: the release was unclean", h.Route.Host)) |
| - d.note(func() { rep.Unclean = append(rep.Unclean, h.Route.Host) }) |
| - } |
| - d.note(func() { rep.Released = append(rep.Released, left) }) |
| - continue |
| - } |
| sem <- struct{}{} |
| - // Begun here, in order, so the busiest host is held first. |
| - began := d.act.BeginMove(h.Route.Host) |
| + var began error |
| + if h.Movable { |
| + // Begun here, in order, so the busiest host is held first. |
| + began = d.act.BeginMove(h.Route.Host) |
| + } |
| wg.Add(1) |
| go func() { |
| defer wg.Done() |
| defer func() { <-sem }() |
| - if s := d.moveOne(ctx, txn, h, began, rep); s != "" { |
| + var s string |
| + if h.Movable { |
| + s = d.moveOne(ctx, txn, h, began, rep) |
| + } else { |
| + s = d.releaseOne(ctx, h, rep) |
| + } |
| + if s != "" { |
| fail(s) |
| } |
| }() |
| } |
| wg.Wait() |
| - d.note(func() { |
| - st := d.act.DrainHoldStatsNow() |
| - rep.Holds = drainHolds{LongestMS: st.Longest.Milliseconds(), Todays: st.Todays, RefusedAtOnce: st.RefusedAtOnce} |
| - }) |
| if len(reasons) > 0 { |
| sort.Strings(reasons) |
| return reasons |
| } |
| - // No lease may name this box now: nothing held, nothing settling. |
| - if held := d.act.DrainHeld(); len(held) > 0 { |
| - return []string{fmt.Sprintf("hosts are still held here: %v", held)} |
| - } |
| - if q := d.act.DrainQuietNow(); !q.Zero() { |
| - return []string{fmt.Sprintf("the box is not quiet after the moves: %+v", q)} |
| + // No lease may name this box now: nothing held, nothing settling. An |
| + // idle stop that began meanwhile is waited for (the audit reads its |
| + // outcome); anything left at the deadline fails the drain. |
| + if err := d.settle(ctx); err != nil { |
| + return []string{fmt.Sprintf("the box did not settle after the moves: %v", err)} |
| } |
| // Step 4: drained, acknowledged; then the connections. |
| if err := d.marks.setDrained(); err != nil { |
| @@ -511,8 +599,11 @@ func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) [] |
| return r |
| } |
| d.act.EndDrainMoves() |
| - closed := d.edge.DrainConnections(ctx, drainConnBound) |
| + closed, err := d.edge.DrainConnections(ctx, drainConnBound) |
| d.note(func() { rep.Closed = closed }) |
| + if err != nil { |
| + return []string{fmt.Sprintf("the connections did not drain: %v", err)} |
| + } |
| // Step 5: certify (H5) from this incarnation. |
| q := d.act.DrainQuietNow() |
| held := d.act.DrainHeld() |
| @@ -526,6 +617,39 @@ func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) [] |
| return nil |
| } |
| +// releaseOne releases an always-on worker, or a host that is not HA, with |
| +// its marker through the normal stop: never taken (build ruling, spec |
| +// §25.4 step 3.4). A host already gone is left to the release audit. |
| +func (d *drainDriver) releaseOne(ctx context.Context, h activator.DrainHost, rep *drainReport) string { |
| + host := h.Route.Host |
| + rel, err := d.act.DrainStop(ctx, host) |
| + if errors.Is(err, activator.ErrDrainStopGone) { |
| + return "" |
| + } |
| + kind := "other" |
| + if h.Worker { |
| + kind = "worker" |
| + } |
| + left := drainLeft{Host: host, Kind: kind, Marker: rel.Marker, Clean: rel.Clean} |
| + var reason string |
| + switch { |
| + case err != nil: |
| + left.Reason = err.Error() |
| + reason = fmt.Sprintf("%s: the release did not finish: %v", host, err) |
| + case !rel.Marker: |
| + reason = host + ": released without a marker" |
| + case !rel.Clean: |
| + reason = host + ": the release was unclean" |
| + } |
| + d.note(func() { |
| + rep.Released = append(rep.Released, left) |
| + if err == nil && rel.Marker && !rel.Clean { |
| + rep.Unclean = append(rep.Unclean, host) |
| + } |
| + }) |
| + return reason |
| +} |
| + |
| // quiesce waits, memory only, until nothing is settling: wakes restoring, |
| // acquires on their PUT, recoveries, pending stops and owed markers. |
| func (d *drainDriver) quiesce(ctx context.Context) error { |
| @@ -544,6 +668,24 @@ func (d *drainDriver) quiesce(ctx context.Context) error { |
| } |
| } |
| +// settle waits, memory only, until no entry is held here and nothing is |
| +// settling. |
| +func (d *drainDriver) settle(ctx context.Context) error { |
| + t := time.NewTicker(drainQuietPoll) |
| + defer t.Stop() |
| + for { |
| + held, q := d.act.DrainHeld(), d.act.DrainQuietNow() |
| + if len(held) == 0 && q.Zero() { |
| + return nil |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return fmt.Errorf("%w: held %v, %+v", ctx.Err(), held, q) |
| + case <-t.C: |
| + } |
| + } |
| +} |
| + |
| // moveOne is step 3 for one host. It answers a failure, or "". |
| func (d *drainDriver) moveOne(ctx context.Context, txn string, h activator.DrainHost, began error, rep *drainReport) string { |
| host := h.Route.Host |
| @@ -556,9 +698,9 @@ func (d *drainDriver) moveOne(ctx context.Context, txn string, h activator.Drain |
| } |
| if err := began; err != nil { |
| if errors.Is(err, activator.ErrMoveNotHeld) { |
| - // It stopped on its own meanwhile (an idle sleep): its own stop |
| - // wrote its marker, and the check after the moves sees any |
| - // lease still held. |
| + // It stopped on its own meanwhile (an idle sleep): the check |
| + // after the moves waits for that stop, and the release audit |
| + // fails the drain if its marker is missing or unclean. |
| return "" |
| } |
| return leave("begin", err.Error(), activator.DrainRelease{}) |
| @@ -592,6 +734,9 @@ func (d *drainDriver) moveOne(ctx context.Context, txn string, h activator.Drain |
| if err := d.act.SetMoveTaken(host, holder, gen); err != nil { |
| return leave("take", err.Error(), rel) |
| } |
| + // Its edge-held streams here reconnect to the holder now, at an event |
| + // boundary, not at the end of the drain (R3.5). |
| + d.edge.CloseHeldHost(host) |
| d.note(func() { |
| rep.Moved = append(rep.Moved, drainMoved{Host: host, Holder: holder, Gen: gen, Confirmed: how}) |
| }) |
diff --git a/internal/host/hadrain_socket_linux.go b/internal/host/hadrain_socket_linux.go| index d092bcceb..f8144d342 100644 |
| --- a/internal/host/hadrain_socket_linux.go |
| +++ b/internal/host/hadrain_socket_linux.go |
| @@ -10,15 +10,24 @@ import ( |
| "net/http" |
| "os" |
| "path/filepath" |
| + "sync/atomic" |
| "syscall" |
| "time" |
| "golang.org/x/sys/unix" |
| ) |
| -// drainPeerAllowed is the uid the drain socket serves: root only. A test |
| -// seam. |
| -var drainPeerAllowed = func(uid uint32) bool { return uid == 0 } |
| +// drainPeerSeam replaces the root-only peer rule in tests; nil in |
| +// production. |
| +var drainPeerSeam atomic.Pointer[func(uint32) bool] |
| + |
| +// drainPeerAllowed is whether the drain socket serves uid: root only. |
| +func drainPeerAllowed(uid uint32) bool { |
| + if f := drainPeerSeam.Load(); f != nil { |
| + return (*f)(uid) |
| + } |
| + return uid == 0 |
| +} |
| type drainPeerKey struct{} |
diff --git a/internal/host/hadrain_test.go b/internal/host/hadrain_test.go| index e8cc94687..60ad78d47 100644 |
| --- a/internal/host/hadrain_test.go |
| +++ b/internal/host/hadrain_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "slices" |
| "strings" |
| "sync" |
| + "sync/atomic" |
| "testing" |
| "time" |
| @@ -21,41 +22,66 @@ import ( |
| // fixes. The real activator hooks are tested in internal/activator |
| // (hadrainmove_test.go) over the lease fixture. |
| +// recorder is the one ordered event log the three fakes share. |
| +type recorder struct { |
| + mu sync.Mutex |
| + ev []string |
| +} |
| + |
| +func (r *recorder) add(s string) { |
| + if r == nil { |
| + return |
| + } |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + r.ev = append(r.ev, s) |
| +} |
| + |
| +func (r *recorder) events() []string { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return append([]string(nil), r.ev...) |
| +} |
| + |
| +// fakeDrainAct is the activator. Every field after mu is read and written |
| +// under mu; the funcs are set before the drain starts. |
| type fakeDrainAct struct { |
| - mu sync.Mutex |
| - hosts []activator.DrainHost |
| - awake map[string]bool |
| - quiet func() activator.DrainQuiet |
| - stop func(ctx context.Context, host string) (activator.DrainRelease, error) |
| - owner func(rt registry.Route) (string, int64, bool) |
| - stats activator.DrainHoldStats |
| - events *[]string |
| - left map[string]string |
| - taken map[string]string |
| - begun []string |
| - resets int |
| - ended int |
| - inQuiet int |
| + rec *recorder |
| + quiet func() activator.DrainQuiet |
| + stop func(ctx context.Context, host string) (activator.DrainRelease, error) |
| + owner func(rt registry.Route) (string, int64, bool) |
| + |
| + mu sync.Mutex |
| + hosts []activator.DrainHost |
| + awake map[string]bool |
| + stats activator.DrainHoldStats |
| + left map[string]string |
| + taken map[string]string |
| + begun []string |
| + resets int |
| + ended int |
| + inQuiet int |
| + releases []activator.DrainOutcome |
| + logOn bool |
| + logEnds int |
| + notMoving map[string]bool |
| onBeginMove func(string) |
| } |
| -func (f *fakeDrainAct) ev(s string) { |
| - f.mu.Lock() |
| - defer f.mu.Unlock() |
| - if f.events != nil { |
| - *f.events = append(*f.events, s) |
| - } |
| -} |
| func (f *fakeDrainAct) DrainQuietNow() activator.DrainQuiet { |
| f.mu.Lock() |
| f.inQuiet++ |
| - q := f.quiet |
| f.mu.Unlock() |
| - if q == nil { |
| + if f.quiet == nil { |
| return activator.DrainQuiet{} |
| } |
| - return q() |
| + return f.quiet() |
| +} |
| +func (f *fakeDrainAct) quietCalls() int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.inQuiet |
| } |
| func (f *fakeDrainAct) DrainHosts() []activator.DrainHost { |
| f.mu.Lock() |
| @@ -83,59 +109,83 @@ func (f *fakeDrainAct) DrainHeld() []string { |
| return out |
| } |
| func (f *fakeDrainAct) BeginMove(host string) error { |
| - f.ev("begin " + host) |
| + f.rec.add("begin " + host) |
| f.mu.Lock() |
| f.begun = append(f.begun, host) |
| - cb := f.onBeginMove |
| + cb, gone := f.onBeginMove, f.notMoving[host] |
| f.mu.Unlock() |
| if cb != nil { |
| cb(host) |
| } |
| + if gone { |
| + return activator.ErrMoveNotHeld |
| + } |
| return nil |
| } |
| func (f *fakeDrainAct) WaitMoveTickets(context.Context, string) error { return nil } |
| func (f *fakeDrainAct) WaitDrainInflight(context.Context, string) error { return nil } |
| func (f *fakeDrainAct) SetMoveReleasing(host string) error { |
| - f.ev("releasing " + host) |
| + f.rec.add("releasing " + host) |
| return nil |
| } |
| func (f *fakeDrainAct) DrainStop(ctx context.Context, host string) (activator.DrainRelease, error) { |
| - f.ev("stop " + host) |
| - f.mu.Lock() |
| - stop := f.stop |
| - f.mu.Unlock() |
| + f.rec.add("stop " + host) |
| rel, err := activator.DrainRelease{HA: true, Marker: true, Clean: true}, error(nil) |
| - if stop != nil { |
| - rel, err = stop(ctx, host) |
| + if f.stop != nil { |
| + rel, err = f.stop(ctx, host) |
| } |
| if err == nil { |
| - f.mu.Lock() |
| - f.awake[host] = false |
| - f.mu.Unlock() |
| + f.finish(host, rel) |
| } |
| return rel, err |
| } |
| + |
| +// finish is a stop that finished: the entry goes, and its outcome is in |
| +// the release log, as finishStop records it. |
| +func (f *fakeDrainAct) finish(host string, rel activator.DrainRelease) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.awake[host] = false |
| + if f.logOn { |
| + f.releases = append(f.releases, activator.DrainOutcome{Host: host, HA: rel.HA, Marker: rel.Marker, Clean: rel.Clean}) |
| + } |
| +} |
| func (f *fakeDrainAct) SetMoveTaken(host, ref string, gen int64) error { |
| - f.ev(fmt.Sprintf("taken %s %s %d", host, ref, gen)) |
| + f.rec.add(fmt.Sprintf("taken %s %s %d", host, ref, gen)) |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.taken[host] = ref |
| return nil |
| } |
| +func (f *fakeDrainAct) takenBy(host string) string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.taken[host] |
| +} |
| +func (f *fakeDrainAct) leftWhy(host string) string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.left[host] |
| +} |
| func (f *fakeDrainAct) SetMoveLeft(host, reason string) { |
| - f.ev("left " + host) |
| + f.rec.add("left " + host) |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.left[host] = reason |
| } |
| func (f *fakeDrainAct) EndDrainMoves() { |
| - f.ev("end-moves") |
| + f.rec.add("end-moves") |
| f.mu.Lock() |
| f.ended++ |
| f.mu.Unlock() |
| } |
| +func (f *fakeDrainAct) endedMoves() int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.ended |
| +} |
| func (f *fakeDrainAct) DrainTakeOwner(_ context.Context, rt registry.Route) (string, int64, bool) { |
| - f.ev("owner " + rt.Host) |
| + f.rec.add("owner " + rt.Host) |
| if f.owner == nil { |
| return "", 0, false |
| } |
| @@ -151,46 +201,89 @@ func (f *fakeDrainAct) DrainHoldStatsNow() activator.DrainHoldStats { |
| defer f.mu.Unlock() |
| return f.stats |
| } |
| +func (f *fakeDrainAct) setStats(st activator.DrainHoldStats) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.stats = st |
| +} |
| +func (f *fakeDrainAct) BeginDrainReleases() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.logOn = true |
| +} |
| +func (f *fakeDrainAct) DrainReleases() []activator.DrainOutcome { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]activator.DrainOutcome(nil), f.releases...) |
| +} |
| +func (f *fakeDrainAct) EndDrainReleases() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.logOn, f.releases = false, nil |
| + f.logEnds++ |
| +} |
| +// fakeDrainEdge is the edge. Every field after mu is read and written |
| +// under mu; the funcs are set before the drain starts. |
| type fakeDrainEdge struct { |
| + rec *recorder |
| + ack func(peer string) (bool, error) |
| + take func(ctx context.Context, peer, host string) (string, int64, error) |
| + connections func() (int, error) |
| + |
| mu sync.Mutex |
| - events *[]string |
| peers []string |
| - ack func(peer string) (bool, error) |
| asks map[string]int |
| nottake map[string]bool |
| draining map[string]bool |
| - take func(ctx context.Context, peer, host string) (string, int64, error) |
| takeErr error |
| takes []string |
| closed int |
| ends int |
| + heldShut []string |
| } |
| -func (f *fakeDrainEdge) ev(s string) { |
| +func (f *fakeDrainEdge) DrainAckPeers(time.Time) []string { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - if f.events != nil { |
| - *f.events = append(*f.events, s) |
| - } |
| + return append([]string(nil), f.peers...) |
| } |
| -func (f *fakeDrainEdge) DrainAckPeers(time.Time) []string { return append([]string(nil), f.peers...) } |
| func (f *fakeDrainEdge) AskDrainSeen(_ context.Context, peer, txn, phase string, id uint64) (bool, error) { |
| f.mu.Lock() |
| if f.asks == nil { |
| f.asks = map[string]int{} |
| } |
| f.asks[peer+" "+phase]++ |
| - ack := f.ack |
| f.mu.Unlock() |
| - f.ev("ask " + phase + " " + peer) |
| - if ack != nil { |
| - return ack(peer) |
| + f.rec.add("ask " + phase + " " + peer) |
| + if f.ack != nil { |
| + return f.ack(peer) |
| } |
| return true, nil |
| } |
| -func (f *fakeDrainEdge) PeerTakes(ref string) bool { return !f.nottake[ref] } |
| -func (f *fakeDrainEdge) PeerDraining(ref string) bool { return f.draining[ref] } |
| +func (f *fakeDrainEdge) askCount(key string) int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.asks[key] |
| +} |
| +func (f *fakeDrainEdge) PeerTakes(ref string) bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return !f.nottake[ref] |
| +} |
| +func (f *fakeDrainEdge) PeerDraining(ref string) bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.draining[ref] |
| +} |
| +func (f *fakeDrainEdge) setDraining(ref string) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.draining == nil { |
| + f.draining = map[string]bool{} |
| + } |
| + f.draining[ref] = true |
| +} |
| func (f *fakeDrainEdge) DrainSnapshot(rt registry.Route) boxchoice.WakeSnapshot { |
| now := time.Now().UTC().Format(time.RFC3339) |
| return boxchoice.WakeSnapshot{Self: "a", Usable: true, LocalDenied: true, |
| @@ -201,13 +294,13 @@ func (f *fakeDrainEdge) DrainSnapshot(rt registry.Route) boxchoice.WakeSnapshot |
| Peers: map[string]bool{"a": true, "b": true, "c": true}} |
| } |
| func (f *fakeDrainEdge) Take(ctx context.Context, peer, host, lifetime string, gen int64, txn string) (string, int64, error) { |
| - f.ev("take " + host + " " + peer) |
| + f.rec.add("take " + host + " " + peer) |
| f.mu.Lock() |
| f.takes = append(f.takes, host+"@"+peer) |
| - take, takeErr := f.take, f.takeErr |
| + takeErr := f.takeErr |
| f.mu.Unlock() |
| - if take != nil { |
| - return take(ctx, peer, host) |
| + if f.take != nil { |
| + return f.take(ctx, peer, host) |
| } |
| if takeErr != nil { |
| return "", 0, takeErr |
| @@ -217,43 +310,55 @@ func (f *fakeDrainEdge) Take(ctx context.Context, peer, host, lifetime string, g |
| } |
| return peer, gen + 1, nil |
| } |
| -func (f *fakeDrainEdge) DrainConnections(context.Context, time.Duration) int { |
| - f.ev("connections") |
| - return f.closed |
| +func (f *fakeDrainEdge) takeLog() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]string(nil), f.takes...) |
| +} |
| +func (f *fakeDrainEdge) DrainConnections(context.Context, time.Duration) (int, error) { |
| + f.rec.add("connections") |
| + if f.connections != nil { |
| + return f.connections() |
| + } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.closed, nil |
| } |
| func (f *fakeDrainEdge) EndConnectionDrain() { |
| f.mu.Lock() |
| f.ends++ |
| f.mu.Unlock() |
| } |
| +func (f *fakeDrainEdge) CloseHeldHost(host string) { |
| + f.rec.add("close-held " + host) |
| + f.mu.Lock() |
| + f.heldShut = append(f.heldShut, host) |
| + f.mu.Unlock() |
| +} |
| +// fakeMarks is the drain state. |
| type fakeMarks struct { |
| + rec *recorder |
| mu sync.Mutex |
| - events *[]string |
| id uint64 |
| begun, drained, cleared int |
| stuck bool |
| } |
| -func (f *fakeMarks) ev(s string) { |
| - if f.events != nil { |
| - *f.events = append(*f.events, s) |
| - } |
| -} |
| func (f *fakeMarks) begin(string) error { |
| f.mu.Lock() |
| - defer f.mu.Unlock() |
| f.begun++ |
| f.id++ |
| - f.ev("draining") |
| + f.mu.Unlock() |
| + f.rec.add("draining") |
| return nil |
| } |
| func (f *fakeMarks) setDrained() error { |
| f.mu.Lock() |
| - defer f.mu.Unlock() |
| f.drained++ |
| f.id++ |
| - f.ev("drained") |
| + f.mu.Unlock() |
| + f.rec.add("drained") |
| return nil |
| } |
| func (f *fakeMarks) clear() { |
| @@ -261,6 +366,11 @@ func (f *fakeMarks) clear() { |
| defer f.mu.Unlock() |
| f.cleared++ |
| } |
| +func (f *fakeMarks) counts() (begun, drained, cleared int) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.begun, f.drained, f.cleared |
| +} |
| func (f *fakeMarks) waitPublished(ctx context.Context) (haDrainMark, error) { |
| f.mu.Lock() |
| stuck, id := f.stuck, f.id |
| @@ -279,8 +389,8 @@ func drainHost(host string, inflight int) activator.DrainHost { |
| // healthyDrain is a box with two awake HA hosts, an always-on worker and |
| // a host that is not HA; two peers that acknowledge and take. |
| func healthyDrain() (*fakeDrainAct, *fakeDrainEdge, *fakeMarks) { |
| - events := &[]string{} |
| - act := &fakeDrainAct{events: events, left: map[string]string{}, taken: map[string]string{}, |
| + rec := &recorder{} |
| + act := &fakeDrainAct{rec: rec, left: map[string]string{}, taken: map[string]string{}, |
| hosts: []activator.DrainHost{ |
| drainHost("quiet.example.com", 1), |
| drainHost("busy.example.com", 5), |
| @@ -289,8 +399,8 @@ func healthyDrain() (*fakeDrainAct, *fakeDrainEdge, *fakeMarks) { |
| }, |
| awake: map[string]bool{"quiet.example.com": true, "busy.example.com": true, "worker.example.com": true, "plain.example.com": true}, |
| stats: activator.DrainHoldStats{Longest: 1500 * time.Millisecond, Todays: 0, RefusedAtOnce: 2}} |
| - ed := &fakeDrainEdge{events: events, peers: []string{"b", "c"}, closed: 3} |
| - return act, ed, &fakeMarks{events: events} |
| + ed := &fakeDrainEdge{rec: rec, peers: []string{"b", "c"}, closed: 3} |
| + return act, ed, &fakeMarks{rec: rec} |
| } |
| func fenceOf(txn string) func() fenceState { |
| @@ -342,8 +452,8 @@ func indexOf(events []string, prefix string) int { |
| // The whole sequence of §25.4 on the fakes: withdraw acknowledged, the |
| // moves busiest first with the worker and the non-HA host released, not |
| -// taken; drained acknowledged; redirects dropped only then; the |
| -// connections drained; the report. |
| +// taken; each taken host's held streams closed; drained acknowledged; |
| +// redirects dropped only then; the connections drained; the report. |
| func TestDrainDriverWholeSequence(t *testing.T) { |
| act, ed, marks := healthyDrain() |
| d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| @@ -367,11 +477,11 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| t.Fatalf("released %+v", rep.Released) |
| } |
| for _, r := range rep.Released { |
| - if !r.Marker || !r.Clean { |
| + if !r.Marker || !r.Clean || r.Kind == "idle" { |
| t.Fatalf("released %+v", r) |
| } |
| } |
| - for _, take := range ed.takes { |
| + for _, take := range ed.takeLog() { |
| if strings.HasPrefix(take, "worker.") || strings.HasPrefix(take, "plain.") { |
| t.Fatalf("a %s was taken", take) |
| } |
| @@ -382,8 +492,8 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| if rep.Closed != 3 || rep.Holds.LongestMS != 1500 || rep.Holds.RefusedAtOnce != 2 || !slices.Equal(rep.Acked, []string{"b", "c"}) || act.resets != 1 { |
| t.Fatalf("report counts %+v", rep) |
| } |
| - ev := *act.events |
| - order := []string{"draining", "ask draining b", "begin busy.example.com", "stop busy.example.com", "take busy.example.com b", "taken busy.example.com b", "drained", "ask drained b", "end-moves", "connections"} |
| + ev := act.rec.events() |
| + order := []string{"draining", "ask draining b", "begin busy.example.com", "stop busy.example.com", "take busy.example.com b", "taken busy.example.com b", "close-held busy.example.com", "drained", "ask drained b", "end-moves", "connections"} |
| last := -1 |
| for _, step := range order { |
| i := indexOf(ev, step) |
| @@ -399,10 +509,10 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| t.Fatalf("%q after drained: %v", e, ev) |
| } |
| } |
| - if marks.cleared != 0 { |
| + if _, _, cleared := marks.counts(); cleared != 0 { |
| t.Fatal("a successful drain cleared the drain state") |
| } |
| - // The move step is answered again as it was; a withdraw restarts it. |
| + // The move step is answered again as it was. |
| done, err := d.start("t1", "move") |
| if err != nil { |
| t.Fatal(err) |
| @@ -417,15 +527,14 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| // drain starts: nothing moves until the box is quiet. |
| func TestDrainWaitsForQuiescence(t *testing.T) { |
| act, ed, marks := healthyDrain() |
| - var mu sync.Mutex |
| - settling := true |
| + release := make(chan struct{}) |
| act.quiet = func() activator.DrainQuiet { |
| - mu.Lock() |
| - defer mu.Unlock() |
| - if settling { |
| + select { |
| + case <-release: |
| + return activator.DrainQuiet{} |
| + default: |
| return activator.DrainQuiet{Waking: 1} |
| } |
| - return activator.DrainQuiet{} |
| } |
| d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| @@ -435,16 +544,17 @@ func TestDrainWaitsForQuiescence(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - time.Sleep(4 * drainQuietPoll) |
| + // The driver has looked at the box several times and seen it settling. |
| + for act.quietCalls() < 3 { |
| + time.Sleep(time.Millisecond) |
| + } |
| act.mu.Lock() |
| begun := len(act.begun) |
| act.mu.Unlock() |
| - if begun != 0 { |
| - t.Fatal("a move began while a wake was settling") |
| + if begun != 0 || indexOf(act.rec.events(), "stop ") >= 0 { |
| + t.Fatal("a move or release began while a wake was settling") |
| } |
| - mu.Lock() |
| - settling = false |
| - mu.Unlock() |
| + close(release) |
| <-done |
| if rep := d.snapshot(); rep.Result != "ok" || len(rep.Moved) != 2 { |
| t.Fatalf("report %+v", rep) |
| @@ -468,7 +578,7 @@ func TestDrainDeadline(t *testing.T) { |
| if rep.Result != "failed" || !strings.Contains(strings.Join(rep.Reasons, ";"), "the drain deadline passed") { |
| t.Fatalf("report %+v", rep) |
| } |
| - if marks.cleared != 0 || marks.drained != 0 { |
| + if _, drained, cleared := marks.counts(); cleared != 0 || drained != 0 { |
| t.Fatal("a failed drain left the drain state or published drained") |
| } |
| } |
| @@ -488,10 +598,10 @@ func TestDrainUnprovenStopFails(t *testing.T) { |
| } |
| d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| rep := runDrain(t, d, "t1") |
| - if rep.Result != "failed" || act.left["busy.example.com"] == "" || act.taken["busy.example.com"] != "" { |
| - t.Fatalf("report %+v left %v", rep, act.left) |
| + if rep.Result != "failed" || act.leftWhy("busy.example.com") == "" || act.takenBy("busy.example.com") != "" { |
| + t.Fatalf("report %+v", rep) |
| } |
| - if marks.drained != 0 || marks.cleared != 0 || act.ended != 0 { |
| + if _, drained, cleared := marks.counts(); drained != 0 || cleared != 0 || act.endedMoves() != 0 { |
| t.Fatal("a failed drain went on to drained, or dropped the drain state") |
| } |
| } |
| @@ -505,10 +615,10 @@ func TestDrainUncleanReleaseFails(t *testing.T) { |
| } |
| d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| rep := runDrain(t, d, "t1") |
| - if rep.Result != "failed" || !slices.Equal(rep.Unclean, []string{"quiet.example.com"}) || act.taken["quiet.example.com"] != "" || act.left["quiet.example.com"] == "" { |
| + if rep.Result != "failed" || !slices.Equal(rep.Unclean, []string{"quiet.example.com"}) || act.takenBy("quiet.example.com") != "" || act.leftWhy("quiet.example.com") == "" { |
| t.Fatalf("report %+v", rep) |
| } |
| - if act.taken["busy.example.com"] != "b" { |
| + if act.takenBy("busy.example.com") != "b" { |
| t.Fatal("the clean host was not moved") |
| } |
| // A released worker's unclean marker fails it too. |
| @@ -522,6 +632,69 @@ func TestDrainUncleanReleaseFails(t *testing.T) { |
| } |
| } |
| +// R2.11 through the release log: a stop already running when the drain |
| +// began finishes unclean while quiescence waits, and an idle stop between |
| +// the host list and BeginMove (ErrMoveNotHeld) writes an unclean marker. |
| +// Neither is one of the drain's own stops; both fail it. A clean idle |
| +// stop is listed as released, kind idle. |
| +func TestDrainReleaseLogCatchesEveryUncleanStop(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + act.awake["early.example.com"] = true |
| + release := make(chan struct{}) |
| + act.quiet = func() activator.DrainQuiet { |
| + select { |
| + case <-release: |
| + return activator.DrainQuiet{} |
| + default: |
| + return activator.DrainQuiet{Stopping: 1} |
| + } |
| + } |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + if err := d.startWithdrawForTest("t1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + done, err := d.start("t1", "move") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for act.quietCalls() < 2 { |
| + time.Sleep(time.Millisecond) |
| + } |
| + // The pre-existing stop finishes, unclean, while quiescence waits. |
| + act.finish("early.example.com", activator.DrainRelease{HA: true, Marker: true, Clean: false}) |
| + close(release) |
| + <-done |
| + rep := d.snapshot() |
| + if rep.Result != "failed" || !slices.Contains(rep.Unclean, "early.example.com") || !strings.Contains(strings.Join(rep.Reasons, ";"), "early.example.com") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + |
| + act, ed, marks = healthyDrain() |
| + act.notMoving = map[string]bool{"quiet.example.com": true, "busy.example.com": true} |
| + act.onBeginMove = func(host string) { |
| + // It went to sleep on its own just before its move began. |
| + clean := host == "busy.example.com" |
| + act.finish(host, activator.DrainRelease{HA: true, Marker: true, Clean: clean}) |
| + } |
| + rep = runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != "failed" || !slices.Equal(rep.Unclean, []string{"quiet.example.com"}) { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + var idle []string |
| + for _, r := range rep.Released { |
| + if r.Kind == "idle" { |
| + idle = append(idle, r.Host) |
| + } |
| + } |
| + if !slices.Equal(idle, []string{"busy.example.com"}) { |
| + t.Fatalf("released %+v, want busy as idle", rep.Released) |
| + } |
| + // A cancel forgets the log. |
| + if err := newDrainDriver(act, ed, marks, fenceOf("t1")).cancel(context.Background(), "t1"); err != nil || act.logEnds != 1 { |
| + t.Fatalf("cancel: %v, log ended %d", err, act.logEnds) |
| + } |
| +} |
| + |
| // No marker (S3 down: an owed marker) fails the drain. |
| func TestDrainNoMarkerFails(t *testing.T) { |
| act, ed, marks := healthyDrain() |
| @@ -544,10 +717,10 @@ func TestDrainTakeFails(t *testing.T) { |
| return peer, 9, nil |
| } |
| rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| - if rep.Result != "failed" || len(rep.Moved) != 1 || rep.Moved[0].Host != "busy.example.com" || act.left["quiet.example.com"] == "" { |
| + if rep.Result != "failed" || len(rep.Moved) != 1 || rep.Moved[0].Host != "busy.example.com" || act.leftWhy("quiet.example.com") == "" { |
| t.Fatalf("report %+v", rep) |
| } |
| - if indexOf(*act.events, "owner ") >= 0 { |
| + if indexOf(act.rec.events(), "owner ") >= 0 { |
| t.Fatal("a take that answered was re-read") |
| } |
| } |
| @@ -568,10 +741,10 @@ func TestDrainTakeRefusedTriesNext(t *testing.T) { |
| // A peer that does not answer takes, or is draining, is never asked. |
| act, ed, marks = healthyDrain() |
| ed.nottake = map[string]bool{"b": true} |
| - ed.draining = map[string]bool{"c": true} |
| + ed.setDraining("c") |
| rep = runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| - if rep.Result != "failed" || len(ed.takes) != 0 { |
| - t.Fatalf("report %+v takes %v", rep, ed.takes) |
| + if rep.Result != "failed" || len(ed.takeLog()) != 0 { |
| + t.Fatalf("report %+v takes %v", rep, ed.takeLog()) |
| } |
| } |
| @@ -596,10 +769,8 @@ func TestDrainTakeTimeoutConfirmedByTheLock(t *testing.T) { |
| <-ctx.Done() |
| return "", 0, ctx.Err() |
| } |
| - ed.draining = map[string]bool{} |
| if tc.drain { |
| - // Draining after it was chosen: the take went out to it. |
| - act.onBeginMove = func(string) { ed.mu.Lock(); ed.draining["b"] = true; ed.mu.Unlock() } |
| + act.onBeginMove = func(string) { ed.setDraining("b") } |
| } |
| act.owner = func(registry.Route) (string, int64, bool) { return tc.owner, 12, tc.ok } |
| rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| @@ -613,7 +784,7 @@ func TestDrainTakeTimeoutConfirmedByTheLock(t *testing.T) { |
| } |
| // A missing acknowledgement: re-asked every 5 s (shortened), failing at 2 |
| -// minutes (shortened), naming the box. No fence is wanted then. |
| +// minutes (shortened), naming the box and why. No fence is wanted then. |
| func TestDrainMissingAcknowledgement(t *testing.T) { |
| defer shorten(&drainAckBound, 120*time.Millisecond)() |
| defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| @@ -626,11 +797,11 @@ func TestDrainMissingAcknowledgement(t *testing.T) { |
| } |
| d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| rep := runDrain(t, d, "t1") |
| - if rep.Result != "failed" || rep.Step != "withdraw" || !strings.Contains(rep.Reasons[0], "[c]") { |
| + if rep.Result != "failed" || rep.Step != "withdraw" || !strings.Contains(rep.Reasons[0], "c (dial refused)") { |
| t.Fatalf("report %+v", rep) |
| } |
| - if ed.asks["c draining"] < 3 || ed.asks["b draining"] != 1 { |
| - t.Fatalf("asks %v: c re-asked, b asked once", ed.asks) |
| + if ed.askCount("c draining") < 3 || ed.askCount("b draining") != 1 { |
| + t.Fatalf("asks: c %d (want re-asked), b %d (want once)", ed.askCount("c draining"), ed.askCount("b draining")) |
| } |
| if _, err := d.start("t1", "move"); !errors.Is(err, errDrainStep) { |
| t.Fatalf("move after a failed withdraw: %v", err) |
| @@ -639,11 +810,56 @@ func TestDrainMissingAcknowledgement(t *testing.T) { |
| // every redirect kept. |
| act, ed, marks = healthyDrain() |
| ed.ack = func(peer string) (bool, error) { |
| - return !(peer == "c" && marks.drained > 0), nil |
| + _, drained, _ := marks.counts() |
| + return !(peer == "c" && drained > 0), nil |
| } |
| rep = runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| - if rep.Result != "failed" || act.ended != 0 || indexOf(*act.events, "connections") >= 0 { |
| - t.Fatalf("report %+v ended %d", rep, act.ended) |
| + if rep.Result != "failed" || act.endedMoves() != 0 || indexOf(act.rec.events(), "connections") >= 0 { |
| + t.Fatalf("report %+v ended %d", rep, act.endedMoves()) |
| + } |
| +} |
| + |
| +// Many peers answering at once (the acknowledgement map is the |
| +// coordinator's alone): run under -race. |
| +func TestDrainAcknowledgementsConcurrently(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + for i := 0; i < 32; i++ { |
| + ed.peers = append(ed.peers, fmt.Sprintf("p%02d", i)) |
| + } |
| + var n atomic.Int32 |
| + ed.ack = func(string) (bool, error) { |
| + // The first answers arrive while the rest are still being asked. |
| + return n.Add(1)%3 != 0, nil |
| + } |
| + defer shorten(&drainAckEvery, 5*time.Millisecond)() |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != "ok" || len(rep.Acked) != 34 { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// The connection drain fails the drain when zero cannot be established. |
| +func TestDrainConnectionsNotIdleFails(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + ed.connections = func() (int, error) { return 2, edge.ErrDrainNotIdle } |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != "failed" || rep.Closed != 2 || !strings.Contains(strings.Join(rep.Reasons, ";"), "connections") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// The hold statistics are read after the connection barrier: a held |
| +// request that ends after SetMoveTaken (here, during the connection |
| +// drain) is counted. |
| +func TestDrainStatsAfterTheBarrier(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + ed.connections = func() (int, error) { |
| + act.setStats(activator.DrainHoldStats{Longest: 4 * time.Second, Todays: 1, RefusedAtOnce: 2}) |
| + return 0, nil |
| + } |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Holds.LongestMS != 4000 || rep.Holds.Todays != 1 { |
| + t.Fatalf("holds %+v, want the waiter that ended at the barrier", rep.Holds) |
| } |
| } |
| @@ -681,7 +897,8 @@ func TestDrainMoveNeedsTheFence(t *testing.T) { |
| } |
| } |
| -// One transaction at a time; cancel of another transaction refuses. |
| +// One transaction at a time; cancel of another transaction refuses; no |
| +// step starts while a cancel runs. |
| func TestDrainOneTransaction(t *testing.T) { |
| act, ed, marks := healthyDrain() |
| d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| @@ -694,34 +911,45 @@ func TestDrainOneTransaction(t *testing.T) { |
| if err := d.cancel(context.Background(), "t2"); !errors.Is(err, errDrainOtherTxn) { |
| t.Fatalf("cancel t2: %v", err) |
| } |
| + d.mu.Lock() |
| + d.cancelling = true |
| + d.mu.Unlock() |
| + if _, err := d.start("t1", "withdraw"); !errors.Is(err, errDrainCancel) { |
| + t.Fatalf("start during a cancel: %v", err) |
| + } |
| + d.mu.Lock() |
| + d.cancelling = false |
| + d.mu.Unlock() |
| if err := d.cancel(context.Background(), "t1"); err != nil { |
| t.Fatal(err) |
| } |
| - if marks.cleared != 1 || act.ended != 1 || ed.ends != 1 || d.status().Transaction != "" || d.snapshot() != nil { |
| - t.Fatalf("after cancel: cleared %d ended %d conns %d status %+v", marks.cleared, act.ended, ed.ends, d.status()) |
| + ed.mu.Lock() |
| + ends := ed.ends |
| + ed.mu.Unlock() |
| + if _, _, cleared := marks.counts(); cleared != 1 || act.endedMoves() != 1 || ends != 1 || act.logEnds != 1 || d.status().Transaction != "" || d.snapshot() != nil { |
| + t.Fatalf("after cancel: cleared %d ended %d conns %d status %+v", cleared, act.endedMoves(), ends, d.status()) |
| } |
| if err := d.startWithdrawForTest("t2"); err != nil { |
| t.Fatalf("t2 after cancel: %v", err) |
| } |
| } |
| -// Hosts still held after the moves (a lease may name the box) fail it. |
| +// Hosts still held after the moves (a lease may name the box) fail it at |
| +// the deadline. |
| func TestDrainHeldAfterMovesFails(t *testing.T) { |
| + defer shorten(&drainDeadlineBase, 300*time.Millisecond)() |
| act, ed, marks := healthyDrain() |
| - act.stop = func(_ context.Context, host string) (activator.DrainRelease, error) { |
| - return activator.DrainRelease{HA: true, Marker: true, Clean: true}, nil |
| - } |
| - inner := act.stop |
| act.stop = func(ctx context.Context, host string) (activator.DrainRelease, error) { |
| - r, err := inner(ctx, host) |
| if host == "busy.example.com" { |
| - // A second entry for it appeared (it should be fenced). |
| - defer func() { act.mu.Lock(); act.awake["late.example.com"] = true; act.mu.Unlock() }() |
| + // A second entry appeared (it should have been fenced). |
| + act.mu.Lock() |
| + act.awake["late.example.com"] = true |
| + act.mu.Unlock() |
| } |
| - return r, err |
| + return activator.DrainRelease{HA: true, Marker: true, Clean: true}, nil |
| } |
| rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| - if rep.Result != "failed" || marks.drained != 0 { |
| + if _, drained, _ := marks.counts(); rep.Result != "failed" || drained != 0 || !strings.Contains(strings.Join(rep.Reasons, ";"), "late.example.com") { |
| t.Fatalf("report %+v", rep) |
| } |
| } |
diff --git a/internal/host/hadrainfence_linux_test.go b/internal/host/hadrainfence_linux_test.go| index d784a4871..ff2691cee 100644 |
| --- a/internal/host/hadrainfence_linux_test.go |
| +++ b/internal/host/hadrainfence_linux_test.go |
| @@ -161,13 +161,12 @@ func TestDrainSocketServesRootOnly(t *testing.T) { |
| t.Cleanup(func() { cancel(); <-done }) |
| waitSocket(t, path) |
| c := newDrainClient(path) |
| - if _, err := c.status(context.Background()); err == nil || os.Geteuid() == 0 { |
| - if os.Geteuid() != 0 { |
| - t.Fatalf("a non-root peer was served: %v", err) |
| - } |
| + if os.Geteuid() == 0 { |
| + t.Log("running as root: the non-root refusal is not exercised") |
| + } else if _, err := c.status(context.Background()); err == nil { |
| + t.Fatal("a non-root peer was served") |
| } |
| - defer func(prev func(uint32) bool) { drainPeerAllowed = prev }(drainPeerAllowed) |
| - drainPeerAllowed = func(uid uint32) bool { return int(uid) == os.Geteuid() } |
| + setDrainPeer(t, func(uid uint32) bool { return int(uid) == os.Geteuid() }) |
| s, err := c.status(context.Background()) |
| if err != nil || s.Incarnation != agentIncarnation || s.Result != "none" { |
| t.Fatalf("status: %+v %v", s, err) |
| @@ -217,9 +216,7 @@ func verbDrain(t *testing.T, d *drainDriver) (*groupMaintenanceCommand, fenceLoc |
| must(t, err) |
| t.Cleanup(func() { os.RemoveAll(dir) }) |
| path := filepath.Join(dir, "s", "drain.sock") |
| - prev := drainPeerAllowed |
| - t.Cleanup(func() { drainPeerAllowed = prev }) |
| - drainPeerAllowed = func(uint32) bool { return true } |
| + setDrainPeer(t, func(uint32) bool { return true }) |
| if d != nil { |
| ctx, cancel := context.WithCancel(context.Background()) |
| done := make(chan struct{}) |
| @@ -263,7 +260,7 @@ func TestDrainVerbFenceAndCancel(t *testing.T) { |
| if _, err := runDrainVerb(t, cmd, "drain", "t1"); !errors.Is(err, errFenceOther) { |
| t.Fatalf("drain over another fence: %v", err) |
| } |
| - if marks.begun != 0 { |
| + if begun, _, _ := marks.counts(); begun != 0 { |
| t.Fatal("the agent was asked under another transaction's fence") |
| } |
| if _, err := runDrainVerb(t, cmd, "fence-clear", "t1"); !errors.Is(err, errFenceOther) { |
| @@ -311,8 +308,8 @@ func TestDrainVerbFenceAndCancel(t *testing.T) { |
| if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil { |
| t.Fatal(err) |
| } |
| - if s := l.read(); s.Present || marks.cleared == 0 { |
| - t.Fatalf("after cancel: fence %+v, drain state cleared %d times", s, marks.cleared) |
| + if _, _, cleared := marks.counts(); l.read().Present || cleared == 0 { |
| + t.Fatalf("after cancel: fence %+v, drain state cleared %d times", l.read(), cleared) |
| } |
| } |
| @@ -320,6 +317,7 @@ func TestDrainVerbFenceAndCancel(t *testing.T) { |
| // drain state); fence-clear needs no agent at all. |
| func TestDrainCancelWithoutAgent(t *testing.T) { |
| cmd, l := verbDrain(t, nil) |
| + cmd.edge = func(context.Context) (int, string, error) { return 0, "", errors.New("edge MainPID unavailable") } |
| must(t, l.install("t1", time.Now())) |
| if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil { |
| t.Fatal(err) |
| @@ -384,3 +382,23 @@ func TestDrainVerbArguments(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// drain --cancel never lifts the fence of a live agent it cannot reach: |
| +// an edge process runs, its drain socket does not answer. |
| +func TestDrainCancelRefusedWhileTheEdgeRuns(t *testing.T) { |
| + cmd, l := verbDrain(t, nil) |
| + cmd.edge = func(context.Context) (int, string, error) { return 4242, "99", nil } |
| + must(t, l.install("t1", time.Now())) |
| + if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); !errors.Is(err, errDrainSocketDown) { |
| + t.Fatalf("cancel against a live edge with no socket: %v", err) |
| + } |
| + if s := l.read(); s.Transaction != "t1" { |
| + t.Fatalf("the fence was lifted: %+v", s) |
| + } |
| +} |
| + |
| +func setDrainPeer(t *testing.T, f func(uint32) bool) { |
| + t.Helper() |
| + drainPeerSeam.Store(&f) |
| + t.Cleanup(func() { drainPeerSeam.Store(nil) }) |
| +} |
diff --git a/internal/host/testdata/edges-p2b-golden.json b/internal/host/testdata/edges-p2b-golden.json| index 3bbb60d18..20d9c3248 100644 |
| --- a/internal/host/testdata/edges-p2b-golden.json |
| +++ b/internal/host/testdata/edges-p2b-golden.json |
| @@ -1 +1 @@ |
| -{"box_role":"serve","admitted":true,"drained":false,"v":1,"box":"leo","eip":"203.0.113.10","region":"eu-west-1","data_bucket":"test-data","data_bucket_region":"eu-west-1","hibernation_configured":true,"serves_shared_pool":false,"accepts_inbound":true,"named_pools":["cohort1","hapair"],"burst_notices":true,"secrets_key_fp":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","box_id":"leo","capabilities":["region-ha-1","names-2"],"headroom":{"mem_free_mib":512,"disk_free_mib":2048,"awake":0,"mem_total_mib":1024,"disk_total_mib":4096},"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-11-04T12:00:00Z","hosts":{"app.example.com":{"role":"home","platform":false}}} |
| \ No newline at end of file |
| +{"box_role":"serve","admitted":true,"drained":false,"v":1,"box":"leo","eip":"203.0.113.10","region":"eu-west-1","data_bucket":"test-data","data_bucket_region":"eu-west-1","hibernation_configured":true,"serves_shared_pool":false,"accepts_inbound":true,"named_pools":["cohort1","hapair"],"burst_notices":true,"ha_take":1,"secrets_key_fp":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","box_id":"leo","capabilities":["region-ha-1","names-2"],"headroom":{"mem_free_mib":512,"disk_free_mib":2048,"awake":0,"mem_total_mib":1024,"disk_total_mib":4096},"moves_protocol":0,"seeds_protocol":0,"addrs":null,"generation":"2026-11-04T12:00:00Z","hosts":{"app.example.com":{"role":"home","platform":false}}} |
| \ No newline at end of file |