region HA: the drain driver, the drain verbs and the start fence
Task 5 of the held-requests build (spec §25.4, H5, §25.15 R3.1). group-maintenance drain <txn> asks the agent, over a root-only unix socket, to withdraw (publish draining, acknowledged by every live box), installs a root-owned start fence bound to the transaction, then asks it to move: quiesce, move awake HA hosts busiest first (four at a time: hold, tickets and in-flight within 10 s, stop through finishStop with the drain reason, take to the roomiest successor that answers takes, taken), release always-on workers with their markers (never taken), publish drained and wait for its acknowledgement, drop the redirects, drain the connections (60 s), and report with the agent's incarnation. Failures (unclean release, no marker, a failed take, a missing acknowledgement, the deadline of 15 min + 1 min per 20 awake hosts) fail the drain and keep the drain state and the fence until drain --cancel. A take timeout is confirmed by one lock re-read when a non-draining owner in view holds the lock. The fence lives in /run/carlos-group-fence (root 0755, fence.json root 0644), beside the root-only maintenance directory, because the agent runs as carlos and must read it. The group start gate reads it at every start decision, so a restarted agent is fenced too. drain --cancel and fence-clear remove it, for the same transaction only. status shows the fence, the drain and the incarnation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/activator/activator.go+4 −0internal/activator/hadrainmove.go+262 −0internal/activator/hadrainmove_linux_test.go+27 −0internal/activator/hadrainmove_test.go+191 −0internal/activator/handover.go+20 −2internal/activator/harelease.go+1 −1internal/edge/edge.go+8 −0internal/edge/hadrainconns.go+176 −0internal/edge/hadrainconns_test.go+196 −0internal/host/agent.go+10 −0internal/host/group_admission.go+8 −1internal/host/group_maintenance_drain.go+102 −0internal/host/group_maintenance_verbs.go+82 −4internal/host/hadrain.go+653 −0internal/host/hadrain_socket.go+183 −0internal/host/hadrain_socket_linux.go+100 −0internal/host/hadrain_socket_other.go+8 −0internal/host/hadrain_test.go+751 −0internal/host/hadrainfence.go+87 −0internal/host/hadrainfence_linux.go+226 −0internal/host/hadrainfence_linux_test.go+386 −0internal/host/hadrainfence_other.go+11 −0
Intent
<task-notification> <task-id>a40e6294574b2458e</task-id> <tool-use-id>toolu_01KBPTwBKRD7dPD5ihAR1cZm</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>Waiting for the sweep to finish.</result> <usage><subagent_tokens>366988</subagent_tokens><tool_uses>130</tool_uses><duration_ms>2093868</duration_ms></usage> </task-notification>
<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" 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>Waiting for the sweep to finish.</result> <usage><subagent_tokens>365714</subagent_tokens><tool_uses>131</tool_uses><duration_ms>2181932</duration_ms></usage> </task-notification>
<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" 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 remaining mutations are running in the background; I'll wait for the completion notice.</result> <usage><subagent_tokens>370837</subagent_tokens><tool_uses>136</tool_uses><duration_ms>2676051</duration_ms></usage> </task-notification>
<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" 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 old monitor expired; it watched the first sweep, which no longer matters. Still waiting on the second run.</result> <usage><subagent_tokens>370966</subagent_tokens><tool_uses>136</tool_uses><duration_ms>3890270</duration_ms></usage> </task-notification>
<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" 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>Still waiting on the second mutation run.</result> <usage><subagent_tokens>371269</subagent_tokens><tool_uses>136</tool_uses><duration_ms>3894638</duration_ms></usage> </task-notification>
<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" 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>Waiting for the second mutation run to finish.</result> <usage><subagent_tokens>372763</subagent_tokens><tool_uses>138</tool_uses><duration_ms>4003021</duration_ms></usage> </task-notification>
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 3486d329c..3f00e0b65 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -597,6 +597,10 @@ type actEntry struct { |
| sidecarUncertain bool |
| + // haReleaseClean is the clean flag of the marker haReleased says was |
| + // written (§5.2), for the drain report (§25.4). Under a.mu. |
| + haReleaseClean bool |
| + |
| // Activity tracking: an instance is idle only when nothing is in flight |
| // AND the idle window has passed since the last request finished. In-flight |
| // counting (not just timestamps) is what keeps an instance with one open |
diff --git a/internal/activator/hadrainmove.go b/internal/activator/hadrainmove.go| new file mode 100644 |
| index 000000000..592e4f714 |
| --- /dev/null |
| +++ b/internal/activator/hadrainmove.go |
| @@ -0,0 +1,262 @@ |
| +package activator |
| + |
| +// The drain driver's activator hooks (region HA spec §25.4 steps 2 and 3, |
| +// H5, §25.15 R3.1). The driver itself lives in internal/host (hadrain.go); |
| +// these are the reads and the one stop it needs from the activator. None |
| +// of them is an input to hafresh.DecideAcquire (I1): the stop is the |
| +// ordinary stop path, and DrainTakeOwner only reads the lock. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// StopDrain is the drain's stop reason (§25.4 step 3.3). It reuses |
| +// StopRetired's approved text, which says what happens to the instance on |
| +// this box; nothing compares stop reasons but StopLeaseLost. |
| +const StopDrain = StopRetired |
| + |
| +// drainInflightPoll is how often WaitDrainInflight looks at a host's |
| +// in-flight count, which has no change signal. Memory only. |
| +const drainInflightPoll = 20 * time.Millisecond |
| + |
| +// DrainQuiet is what is still settling on this box (§25.4 step 2, H5): |
| +// every count must be zero before the box is quiescent. |
| +type DrainQuiet struct { |
| + // Waking are entries whose wake is under way: restoring, or an |
| + // acquire waiting on its conditional PUT. |
| + Waking int `json:"waking"` |
| + // Stopping are entries whose stop is under way or pending (an unproven |
| + // stop keeps its lease, renewing, until the sweep proves it). |
| + Stopping int `json:"stopping"` |
| + // Recovering are lost-lease recoveries (discovery or a recovery wake). |
| + Recovering int `json:"recovering"` |
| + // Owed are release obligations of every kind: owed markers |
| + // (lease.PendingObligations), owed legacy releases, retained failed |
| + // wakes and open release commands. |
| + Owed int `json:"owed"` |
| +} |
| + |
| +// Zero is whether nothing is settling. |
| +func (q DrainQuiet) Zero() bool { return q == DrainQuiet{} } |
| + |
| +// DrainQuietNow counts what is still settling, memory only. |
| +func (a *Service) DrainQuietNow() DrainQuiet { |
| + owed := len(lease.PendingObligations()) |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + q := DrainQuiet{Owed: owed + len(a.unprovenWakes) + len(a.owedReleases) + len(a.releaseOps)} |
| + for _, e := range a.entries { |
| + switch e.state { |
| + case actWaking: |
| + q.Waking++ |
| + case actStopping: |
| + q.Stopping++ |
| + } |
| + } |
| + for _, l := range a.haLoss.hosts { |
| + if l.running || l.recovery != nil { |
| + q.Recovering++ |
| + } |
| + } |
| + return q |
| +} |
| + |
| +// DrainHost is one awake host the drain must release (§25.4 step 3). |
| +type DrainHost struct { |
| + Route registry.Route |
| + // Movable is an awake HA instance with no loss latched: it is moved |
| + // (BeginMove, stop, take). Anything else awake is released through the |
| + // normal stop and listed as released: an always-on worker (build |
| + // ruling 2026-11-09: never taken, it resumes on its HRW box through |
| + // the departure import), or a host that is not HA. |
| + Movable bool |
| + Worker bool |
| + // Inflight and LastActive order the moves, busiest first. |
| + Inflight int |
| + LastActive time.Time |
| + // Lifetime and Gen are the host's record lifetime and the generation |
| + // of its lease, which its marker keeps: what the take names. |
| + Lifetime string |
| + Gen int64 |
| +} |
| + |
| +// DrainHosts is every entry that names this box, busiest first: awake |
| +// entries to move or release, and (Movable false, for the report) any |
| +// other entry. Called after quiescence, it is the awake set. |
| +func (a *Service) DrainHosts() []DrainHost { |
| + a.mu.Lock() |
| + var out []DrainHost |
| + for _, e := range a.entries { |
| + if e.state != actAwake { |
| + continue |
| + } |
| + _, ha := haEntryRep(e) |
| + movable := ha && !e.worker && a.haLeaseRefusalLocked(e.route) == nil |
| + out = append(out, DrainHost{Route: e.route, Movable: movable, Worker: e.worker, Inflight: e.inflight, LastActive: e.lastActive}) |
| + } |
| + a.mu.Unlock() |
| + for i := range out { |
| + if !out[i].Movable { |
| + continue |
| + } |
| + if hb, ok := a.backend.(haReleaser); ok { |
| + out[i].Lifetime = hb.haReleaseBase(out[i].Route).Lifetime |
| + } |
| + if tb := takeBackendFor(a.backend, out[i].Route); tb != nil { |
| + out[i].Gen, _ = tb.haAcquiredGeneration(out[i].Route.Host) |
| + } |
| + } |
| + sort.SliceStable(out, func(i, j int) bool { |
| + if out[i].Inflight != out[j].Inflight { |
| + return out[i].Inflight > out[j].Inflight |
| + } |
| + if !out[i].LastActive.Equal(out[j].LastActive) { |
| + return out[i].LastActive.After(out[j].LastActive) |
| + } |
| + return out[i].Route.Host < out[j].Route.Host |
| + }) |
| + return out |
| +} |
| + |
| +// DrainHeld is every host with an entry here, in any state: after the |
| +// moves, a non-empty answer is a lease that may still name this box. |
| +func (a *Service) DrainHeld() []string { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + out := make([]string, 0, len(a.entries)) |
| + for host := range a.entries { |
| + out = append(out, host) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +// WaitDrainInflight waits until host has no request in flight on its |
| +// entry (§25.4 step 3.2: today's 10 s HTTP drain bound is ctx's), or the |
| +// entry is gone. It returns ctx's error at the bound; the stop then ends |
| +// what is left, as a shutdown stop does. |
| +func (a *Service) WaitDrainInflight(ctx context.Context, host string) error { |
| + t := time.NewTicker(drainInflightPoll) |
| + defer t.Stop() |
| + for { |
| + a.mu.Lock() |
| + e := a.entries[host] |
| + busy := e != nil && e.state == actAwake && e.inflight > 0 |
| + a.mu.Unlock() |
| + if !busy { |
| + return nil |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-t.C: |
| + } |
| + } |
| +} |
| + |
| +// DrainRelease is how a drain stop ended. |
| +type DrainRelease struct { |
| + // Marker is a release marker written (or a 412: the lease was no |
| + // longer this box's, so nothing names it). False for an HA host means |
| + // none was written: an owed marker, or a stop that wrote nothing. |
| + Marker bool |
| + // Clean is the marker's clean flag (§5.2): false means writes or files |
| + // may be lost, and the drain fails (R2.11). |
| + Clean bool |
| + // HA is whether the entry held an HA lease. |
| + HA bool |
| +} |
| + |
| +// ErrDrainStopGone is DrainStop for a host with no awake entry. |
| +var ErrDrainStopGone = errors.New("activator: drain stop: host is not awake here") |
| + |
| +// DrainStop stops host through the existing stop path with the drain as |
| +// its reason (beginStopLocked, then stop and finishStop, which writes the |
| +// marker, §5.2), and waits for the stop to finish. A stop whose |
| +// termination is unproven stays pending, with the lease held and renewing, |
| +// and the activator keeps owning it; DrainStop then returns ctx's error, |
| +// and the sweep finishes the stop later as it does today. |
| +func (a *Service) DrainStop(ctx context.Context, host string) (DrainRelease, error) { |
| + a.mu.Lock() |
| + e := a.entries[host] |
| + if e == nil || (e.state != actAwake && e.state != actStopping) { |
| + a.mu.Unlock() |
| + return DrainRelease{}, ErrDrainStopGone |
| + } |
| + _, ha := haEntryRep(e) |
| + if e.state == actAwake { |
| + a.beginStopLocked(e, StopDrain) |
| + } |
| + stopped := e.stopped |
| + a.mu.Unlock() |
| + select { |
| + case <-stopped: |
| + case <-ctx.Done(): |
| + return DrainRelease{HA: ha}, ctx.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 |
| + } |
| + return r, nil |
| +} |
| + |
| +// DrainTakeOwner is the take timeout's one lock re-read (build ruling, |
| +// Task 4): the lock's unexpired HA owner other than this box, and the |
| +// lock's generation. ok is false when the lock names no such owner or the |
| +// read failed. It only reads, as ConfirmMoveHolder does; the driver checks |
| +// the owner is in view and not draining. |
| +func (a *Service) DrainTakeOwner(ctx context.Context, rt registry.Route) (ref string, gen int64, ok bool) { |
| + r := holderReaderFor(a.backend, rt) |
| + if r == nil { |
| + return "", 0, false |
| + } |
| + rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), holderReadTimeout) |
| + defer cancel() |
| + v, err := r.readHolderView(rctx, rt) |
| + if err != nil { |
| + return "", 0, false |
| + } |
| + if ref = otherHolder(v, r.self(), time.Now()); ref == "" { |
| + return "", 0, false |
| + } |
| + return ref, v.Lock.Generation, true |
| +} |
| + |
| +// DrainHoldStats is the moves' holds since ResetDrainHoldStats, for the |
| +// report (§25.4 step 5). |
| +type DrainHoldStats struct { |
| + // Longest is the longest any request was held. |
| + Longest time.Duration |
| + // Todays is the held requests that ended with today's answer. |
| + Todays int |
| + // RefusedAtOnce is the requests for a moving host answered at once |
| + // with today's answer, never held (a hop that is not replayable, a |
| + // request that cannot be forwarded, a cap). |
| + RefusedAtOnce int |
| +} |
| + |
| +// ResetDrainHoldStats starts a drain's hold statistics. |
| +func (a *Service) ResetDrainHoldStats() { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + a.moves.stats = DrainHoldStats{} |
| +} |
| + |
| +// DrainHoldStatsNow is the hold statistics so far. |
| +func (a *Service) DrainHoldStatsNow() DrainHoldStats { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return a.moves.stats |
| +} |
diff --git a/internal/activator/hadrainmove_linux_test.go b/internal/activator/hadrainmove_linux_test.go| new file mode 100644 |
| index 000000000..108e90d0f |
| --- /dev/null |
| +++ b/internal/activator/hadrainmove_linux_test.go |
| @@ -0,0 +1,27 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "path/filepath" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// Files Final incomplete: the marker is unclean, and the drain stop says |
| +// so (the drain fails on it). |
| +func TestDrainStopFilesFinalIncomplete(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + writeFiles(t, s.b, s.rt, map[string]string{"a.txt": "x"}) |
| + if err := syscall.Mkfifo(filepath.Join(filesDirOf(s.b, s.rt), "pipe"), 0o600); err != nil { |
| + t.Skipf("no FIFOs here: %v", err) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + rel, err := s.a.DrainStop(ctx, s.rt.Host) |
| + if err != nil || !rel.Marker || rel.Clean { |
| + t.Fatalf("drain stop: %+v %v, want an unclean marker", rel, err) |
| + } |
| +} |
diff --git a/internal/activator/hadrainmove_test.go b/internal/activator/hadrainmove_test.go| new file mode 100644 |
| index 000000000..d25d370a4 |
| --- /dev/null |
| +++ b/internal/activator/hadrainmove_test.go |
| @@ -0,0 +1,191 @@ |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/hafresh" |
| + "github.com/carlosframework/platform/internal/lease" |
| +) |
| + |
| +// A drain stop is the ordinary stop with the drain's reason: the marker |
| +// goes out through finishStop, clean, and the release says so. |
| +func TestDrainStopWritesTheMarker(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + hosts := s.a.DrainHosts() |
| + if len(hosts) != 1 || !hosts[0].Movable || hosts[0].Worker || hosts[0].Lifetime == "" || hosts[0].Gen <= 0 { |
| + t.Fatalf("drain hosts: %+v", hosts) |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + rel, err := s.a.DrainStop(ctx, s.rt.Host) |
| + if err != nil || !rel.HA || !rel.Marker || !rel.Clean { |
| + t.Fatalf("drain stop: %+v %v", rel, err) |
| + } |
| + if e.stopWhy != StopDrain { |
| + t.Fatalf("stop reason %q", e.stopWhy) |
| + } |
| + v := s.lockView(t) |
| + if v.Lock.Release == nil || !v.Lock.Release.Clean || v.Lock.Release.Lifetime != hosts[0].Lifetime || v.Lock.Generation != hosts[0].Gen { |
| + t.Fatalf("lock after a drain stop: %+v, want a clean marker at %d", v, hosts[0].Gen) |
| + } |
| + if held := s.a.DrainHeld(); len(held) != 0 { |
| + t.Fatalf("held after the stop: %v", held) |
| + } |
| + if q := s.a.DrainQuietNow(); !q.Zero() { |
| + t.Fatalf("not quiet: %+v", q) |
| + } |
| + if _, err := s.a.DrainStop(ctx, s.rt.Host); !errors.Is(err, ErrDrainStopGone) { |
| + t.Fatalf("a second stop: %v", err) |
| + } |
| +} |
| + |
| +// Finish fails while the marker succeeds: the marker is unclean, and the |
| +// release reports it (the drain fails on it, R2.11). |
| +func TestDrainStopFinishFailsMarkerUnclean(t *testing.T) { |
| + s, e, _, _, _ := shutdownFixture(t) |
| + r := e.rep.(*shutdownRep) |
| + inner := r.finish |
| + r.finish = func(ctx context.Context) (uint64, error) { |
| + txid, _ := inner(ctx) |
| + return txid, errors.New("final sync: the store refused") |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + rel, err := s.a.DrainStop(ctx, s.rt.Host) |
| + if err != nil || !rel.Marker || rel.Clean { |
| + t.Fatalf("drain stop: %+v %v, want an unclean marker", rel, err) |
| + } |
| + if v := s.lockView(t); v.Lock.Release == nil || v.Lock.Release.Clean { |
| + t.Fatalf("lock: %+v, want an unclean marker", v.Lock.Release) |
| + } |
| +} |
| + |
| +// A stop that is unproven stays pending, with the lease held and |
| +// renewing: DrainStop answers ctx's error, writes nothing, and the box is |
| +// not quiet. The activator keeps the stop. |
| +func TestDrainStopUnprovenKeepsTheLease(t *testing.T) { |
| + s, e := haServiceEntry(t, "shop.example.com") |
| + s.unit.set(func(u *haUnit) { u.stuck, u.slicePop = true, false }) |
| + before := len(s.lockWriteLog()) |
| + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) |
| + defer cancel() |
| + rel, err := s.a.DrainStop(ctx, s.rt.Host) |
| + if !errors.Is(err, context.DeadlineExceeded) || rel.Marker { |
| + t.Fatalf("drain stop: %+v %v", rel, err) |
| + } |
| + if q := s.a.DrainQuietNow(); q.Stopping != 1 { |
| + t.Fatalf("quiet: %+v, want the pending stop counted", q) |
| + } |
| + for _, w := range s.lockWriteLog()[before:] { |
| + if isMarker(w) { |
| + t.Fatal("a marker over an unproven stop") |
| + } |
| + } |
| + if v := s.lockView(t); v.Lock.Release != nil || !v.HAOn() || e.rep.Err() != nil { |
| + t.Fatalf("the lease is not held: %+v %v", v, e.rep.Err()) |
| + } |
| + if held := s.a.DrainHeld(); len(held) != 1 { |
| + t.Fatalf("held: %v", held) |
| + } |
| +} |
| + |
| +// A wake still restoring when the drain starts, here its acquire paused |
| +// before the lock PUT: the box is not quiet until it resolves, and then |
| +// the host is awake and movable. |
| +func TestDrainQuietWaitsForAnAcquireBeforeItsPUT(t *testing.T) { |
| + s := haService(t, "shop.example.com") |
| + key := s.lockKey() |
| + paused, release := make(chan struct{}), make(chan struct{}) |
| + var once bool |
| + s.fx.BeforeWrite(func(method, k string) { |
| + if k == key && method == "PUT" && !once { |
| + once = true |
| + close(paused) |
| + <-release |
| + } |
| + }) |
| + woke := make(chan error, 1) |
| + go func() { |
| + _, err := s.wakeForTest(context.Background()) |
| + woke <- err |
| + }() |
| + <-paused |
| + if q := s.a.DrainQuietNow(); q.Waking != 1 || q.Zero() { |
| + t.Fatalf("quiet with an acquire on its PUT: %+v", q) |
| + } |
| + if h := s.a.DrainHosts(); len(h) != 0 { |
| + t.Fatalf("a waking host listed to move: %+v", h) |
| + } |
| + close(release) |
| + if err := <-woke; err != nil { |
| + t.Fatal(err) |
| + } |
| + waitFor(t, "quiet", func() bool { return s.a.DrainQuietNow().Zero() }) |
| + if h := s.a.DrainHosts(); len(h) != 1 || !h[0].Movable { |
| + t.Fatalf("after the wake: %+v", h) |
| + } |
| +} |
| + |
| +// The take timeout's lock re-read names another box's unexpired lease, and |
| +// nothing else. |
| +func TestDrainTakeOwner(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + ctx := context.Background() |
| + if ref, _, ok := s.a.DrainTakeOwner(ctx, s.rt); ok { |
| + t.Fatalf("this box's own lease named %q", ref) |
| + } |
| + if _, err := s.a.DrainStop(ctx, s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ref, _, ok := s.a.DrainTakeOwner(ctx, s.rt); ok { |
| + t.Fatalf("a marker named %q", ref) |
| + } |
| + self := lease.CurrentSelf() |
| + p := s.peer(t) |
| + lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b", Account: self.Account, Region: self.Region}) |
| + _, err := p.wakeForTest(ctx) |
| + lease.SetSelf(self) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ref, gen, ok := s.a.DrainTakeOwner(ctx, s.rt) |
| + if !ok || ref != "b" || gen != s.lockView(t).Lock.Generation { |
| + t.Fatalf("owner %q %d %v, want b", ref, gen, ok) |
| + } |
| +} |
| + |
| +// The holds' statistics: the longest hold, holds that got today's answer, |
| +// and requests refused at once. |
| +func TestDrainHoldStats(t *testing.T) { |
| + s, _ := haServiceEntry(t, "shop.example.com") |
| + s.a.ResetDrainHoldStats() |
| + if err := s.a.BeginMove(s.rt.Host); err != nil { |
| + t.Fatal(err) |
| + } |
| + d := s.a.MoveState(s.rt, edge.MoveAsk{Forwardable: true}) |
| + if d.Phase != edge.MoveHolding { |
| + t.Fatalf("decision %+v", d) |
| + } |
| + if r := s.a.MoveState(s.rt, edge.MoveAsk{Hop: true}); r.Phase != edge.MoveRefused { |
| + t.Fatalf("a non-replayable hop: %+v", r) |
| + } |
| + go func() { |
| + time.Sleep(50 * time.Millisecond) |
| + s.a.SetMoveLeft(s.rt.Host, "test") |
| + }() |
| + if got := d.Wait(context.Background()); got.Phase != edge.MoveRefused { |
| + t.Fatalf("held: %+v", got) |
| + } |
| + st := s.a.DrainHoldStatsNow() |
| + if st.Todays != 1 || st.RefusedAtOnce != 1 || st.Longest < 40*time.Millisecond { |
| + t.Fatalf("stats %+v", st) |
| + } |
| + s.a.ResetDrainHoldStats() |
| + if st := s.a.DrainHoldStatsNow(); st != (DrainHoldStats{}) { |
| + t.Fatalf("after reset %+v", st) |
| + } |
| +} |
diff --git a/internal/activator/handover.go b/internal/activator/handover.go| index f3e091e77..1ebb9bd6e 100644 |
| --- a/internal/activator/handover.go |
| +++ b/internal/activator/handover.go |
| @@ -107,6 +107,8 @@ type moveTable struct { |
| tickets map[string]int |
| // ticketsDone is closed, and replaced, whenever a ticket ends. |
| ticketsDone chan struct{} |
| + // stats are the holds' outcomes for the drain report. |
| + stats DrainHoldStats |
| } |
| var ( |
| @@ -141,10 +143,14 @@ func (a *Service) MoveState(rt registry.Route, ask edge.MoveAsk) edge.MoveDecisi |
| return a.moveNoneLocked(rt) |
| } |
| if d, ok := a.moveDecideLocked(rt, m, ask); ok { |
| + if d.Phase == edge.MoveRefused || d.Phase == edge.MoveLost { |
| + a.moves.stats.RefusedAtOnce++ |
| + } |
| return d |
| } |
| // Held: reserve a slot within the caps, or today's answer at once. |
| if m.held >= moveHoldPerHost || a.moves.held >= moveHoldPerBox { |
| + a.moves.stats.RefusedAtOnce++ |
| return edge.MoveDecision{Phase: edge.MoveRefused} |
| } |
| m.held++ |
| @@ -228,14 +234,23 @@ func (a *Service) moveDecideLocked(rt registry.Route, m *hostMove, ask edge.Move |
| func (a *Service) waitMove(ctx context.Context, rt registry.Route, m *hostMove, ask edge.MoveAsk, bound time.Duration) edge.MoveDecision { |
| timer := time.NewTimer(bound) |
| defer timer.Stop() |
| + start := time.Now() |
| + var out edge.MoveDecision |
| a.mu.Lock() |
| defer func() { |
| m.held-- |
| a.moves.held-- |
| + if held := time.Since(start); held > a.moves.stats.Longest { |
| + a.moves.stats.Longest = held |
| + } |
| + if out.Phase == edge.MoveRefused || out.Phase == edge.MoveLost { |
| + a.moves.stats.Todays++ |
| + } |
| a.mu.Unlock() |
| }() |
| for { |
| if d, ok := a.moveDecideLocked(rt, m, ask); ok { |
| + out = d |
| return d |
| } |
| changed := m.changed |
| @@ -246,12 +261,15 @@ func (a *Service) waitMove(ctx context.Context, rt registry.Route, m *hostMove, |
| a.mu.Lock() |
| // A bound hit: today's answer, unless the lease was lost meanwhile. |
| if d, ok := a.moveDecideLocked(rt, m, ask); ok && d.Phase == edge.MoveLost { |
| + out = d |
| return d |
| } |
| - return edge.MoveDecision{Phase: edge.MoveRefused} |
| + out = edge.MoveDecision{Phase: edge.MoveRefused} |
| + return out |
| case <-ctx.Done(): |
| a.mu.Lock() |
| - return edge.MoveDecision{Phase: edge.MoveRefused} |
| + out = edge.MoveDecision{Phase: edge.MoveRefused} |
| + return out |
| } |
| a.mu.Lock() |
| } |
diff --git a/internal/activator/harelease.go b/internal/activator/harelease.go| index 85333846c..232fc2b35 100644 |
| --- a/internal/activator/harelease.go |
| +++ b/internal/activator/harelease.go |
| @@ -224,7 +224,7 @@ func (a *Service) releaseHAClean(ctx context.Context, e *actEntry) error { |
| mcancel() |
| if merr == nil { |
| a.mu.Lock() |
| - e.haReleased = true |
| + e.haReleased, e.haReleaseClean = true, m.Clean |
| a.mu.Unlock() |
| a.rememberDutyRelease(ctx, rt, m) |
| log.Printf("activator: %s: released with a marker (clean %v, txid %d, files %s)", rt.Host, m.Clean, txid, gen) |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 61e2da5ee..711c4fbc4 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -361,6 +361,9 @@ type Edge struct { |
| // peerDrained is the hook a fold runs when it first sees a peer's file |
| // say ha_drained (hadrain.go, SetPeerDrainedHook). |
| peerDrained atomic.Pointer[func(string)] |
| + // conns is the planned-handover connection drain (hadrainconns.go, |
| + // region HA §25.4 step 4): every request ServeHTTP serves, counted. |
| + conns connDrain |
| // certs is the certificate mirror newCertMirror built, which control |
| // requests choose their TLS name from (hadrain.go). |
| certs atomic.Pointer[certMirror] |
| @@ -1954,6 +1957,10 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| e.serveHAControl(w, r) |
| return |
| } |
| + // 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) |
| + defer untrack() |
| if e.handleDemoRequest(w, r, true) { |
| return |
| } |
| @@ -4870,6 +4877,7 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun |
| if err != nil { |
| log.Fatal(err) |
| } |
| + e.conns.serve(httpsSrv, httpSrv) |
| log.Print(listenersLine(httpLn, *httpAddr, httpsLn, *httpsAddr)) |
| // :80 serves the ACME HTTP-01 challenge and redirects everything else. |
diff --git a/internal/edge/hadrainconns.go b/internal/edge/hadrainconns.go| new file mode 100644 |
| index 000000000..fa53dc8e3 |
| --- /dev/null |
| +++ b/internal/edge/hadrainconns.go |
| @@ -0,0 +1,176 @@ |
| +package edge |
| + |
| +// The drain driver's edge half (region HA spec §25.4 steps 1, 3.4 and 4): |
| +// the boxes whose acknowledgement a drain needs, the successor set a move |
| +// chooses from, and the connection drain. The driver is internal/host's |
| +// hadrain.go; nothing here runs unless it asks. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "slices" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// DrainAckPeers is every other box of the deployment whose edges file is |
| +// live now (its generation fresh, boxchoice.HeadroomFresh): fixed boxes, |
| +// group members and boxes of other regions alike, since every live box |
| +// folds the whole deployment and so views this box's region (§25.4 step |
| +// 1). Memory only. Sorted. |
| +func (e *Edge) DrainAckPeers(now time.Time) []string { |
| + m := e.homes.Load() |
| + if m == nil { |
| + return nil |
| + } |
| + snap := m.snapshot() |
| + seen := map[string]bool{} |
| + var out []string |
| + for _, f := range snap.files { |
| + if f.Box == "" || f.Box == m.self || seen[f.Box] { |
| + continue |
| + } |
| + var gen string |
| + if !placementField(f.Generation, &gen) || !boxchoice.HeadroomFresh(gen, now) { |
| + continue |
| + } |
| + seen[f.Box] = true |
| + out = append(out, f.Box) |
| + } |
| + slices.Sort(out) |
| + return out |
| +} |
| + |
| +// DrainSnapshot is the wake snapshot a move chooses its successor from |
| +// (§25.4 step 3.4: ChooseRoomiest over the eligible serving set, §6.3). |
| +// This box is draining, so it is local-denied and never in Serving. |
| +func (e *Edge) DrainSnapshot(rt registry.Route) boxchoice.WakeSnapshot { |
| + m := e.homes.Load() |
| + s := m.wakeSnapshot(rt, time.Now()) |
| + s.LocalDenied = true |
| + serving := s.Serving[:0:0] |
| + for _, c := range s.Serving { |
| + if c.BoxID != s.Self { |
| + serving = append(serving, c) |
| + } |
| + } |
| + s.Serving = serving |
| + return s |
| +} |
| + |
| +// 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. |
| +type connDrain struct { |
| + draining atomic.Bool |
| + mu sync.Mutex |
| + next uint64 |
| + active map[uint64]context.CancelFunc |
| + // changed is closed and replaced whenever a request ends while |
| + // draining. |
| + changed chan struct{} |
| + servers []*http.Server |
| +} |
| + |
| +// 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()) |
| + d.mu.Lock() |
| + if d.active == nil { |
| + d.active = make(map[uint64]context.CancelFunc) |
| + } |
| + d.next++ |
| + id := d.next |
| + d.active[id] = cancel |
| + d.mu.Unlock() |
| + if d.draining.Load() { |
| + w.Header().Set("Connection", "close") |
| + } |
| + return r.WithContext(ctx), func() { |
| + cancel() |
| + d.mu.Lock() |
| + delete(d.active, id) |
| + if d.changed != nil { |
| + close(d.changed) |
| + d.changed = nil |
| + } |
| + d.mu.Unlock() |
| + } |
| +} |
| + |
| +// serve registers the edge's listeners' servers, whose idle keep-alive |
| +// connections the drain closes. |
| +func (d *connDrain) serve(srvs ...*http.Server) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + d.servers = append(d.servers, srvs...) |
| +} |
| + |
| +// 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() |
| + for { |
| + d.mu.Lock() |
| + if len(d.active) == 0 { |
| + d.mu.Unlock() |
| + return 0 |
| + } |
| + if d.changed == nil { |
| + d.changed = make(chan struct{}) |
| + } |
| + ch := d.changed |
| + d.mu.Unlock() |
| + select { |
| + case <-ch: |
| + continue |
| + case <-timer.C: |
| + case <-ctx.Done(): |
| + } |
| + d.mu.Lock() |
| + n := len(d.active) |
| + for _, cancel := range d.active { |
| + cancel() |
| + } |
| + d.mu.Unlock() |
| + return n |
| + } |
| +} |
| + |
| +// EndConnectionDrain undoes DrainConnections (drain --cancel): 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() |
| + srvs := append([]*http.Server(nil), d.servers...) |
| + d.mu.Unlock() |
| + for _, s := range srvs { |
| + s.SetKeepAlivesEnabled(true) |
| + } |
| +} |
| + |
| +// InFlight is the requests ServeHTTP is serving now. |
| +func (e *Edge) InFlight() int { |
| + e.conns.mu.Lock() |
| + defer e.conns.mu.Unlock() |
| + return len(e.conns.active) |
| +} |
diff --git a/internal/edge/hadrainconns_test.go b/internal/edge/hadrainconns_test.go| new file mode 100644 |
| index 000000000..68c0c105d |
| --- /dev/null |
| +++ b/internal/edge/hadrainconns_test.go |
| @@ -0,0 +1,196 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "slices" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The drain asks every other live box, whatever its region or kind, and |
| +// no box whose file is stale. |
| +func TestDrainAckPeersAreTheLiveBoxes(t *testing.T) { |
| + now := time.Now().UTC() |
| + fresh, stale := now.Format(time.RFC3339), now.Add(-time.Hour).Format(time.RFC3339) |
| + m := wakeMap(t, |
| + map[string]any{"v": 1, "box": "self", "generation": fresh, "region": "ie"}, |
| + map[string]any{"v": 1, "box": "b", "generation": fresh, "region": "ie"}, |
| + map[string]any{"v": 1, "box": "g-0123456789abcdef0123", "generation": fresh, "region": "ie"}, |
| + map[string]any{"v": 1, "box": "far", "generation": fresh, "region": "us-east-1"}, |
| + map[string]any{"v": 1, "box": "dead", "generation": stale, "region": "ie"}, |
| + map[string]any{"v": 1, "box": "nogen", "region": "ie"}, |
| + ) |
| + e := &Edge{} |
| + e.homes.Store(m) |
| + got := e.DrainAckPeers(now) |
| + if want := []string{"b", "far", "g-0123456789abcdef0123"}; !slices.Equal(got, want) { |
| + t.Fatalf("peers %v, want %v", got, want) |
| + } |
| + if (&Edge{}).DrainAckPeers(now) != nil { |
| + t.Fatal("peers without a fold") |
| + } |
| +} |
| + |
| +// drainServer is an edge-shaped server whose handler counts its requests |
| +// through the connection drain, as ServeHTTP does. |
| +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) |
| + defer done() |
| + h(w, r) |
| + })) |
| + d.serve(srv.Config) |
| + srv.Start() |
| + t.Cleanup(srv.Close) |
| + 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) { |
| + e := &Edge{} |
| + release := make(chan struct{}) |
| + ended := make(chan error, 1) |
| + 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 |
| + } |
| + return |
| + } |
| + io.WriteString(w, "ok") |
| + }) |
| + get := func(path string) *http.Response { |
| + resp, err := srv.Client().Get(srv.URL + path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp |
| + } |
| + resp := get("/short") |
| + resp.Body.Close() |
| + if resp.Close || resp.Header.Get("Connection") == "close" { |
| + t.Fatal("Connection: close before the drain") |
| + } |
| + // 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) |
| + } |
| + resp = get("/short") |
| + resp.Body.Close() |
| + if !resp.Close { |
| + t.Fatal("no Connection: close while draining") |
| + } |
| + 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) |
| + } |
| + if err := <-ended; err != nil { |
| + t.Fatalf("the waited-for request ended with %v", err) |
| + } |
| + 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() |
| + start := time.Now() |
| + if n := e.DrainConnections(context.Background(), 100*time.Millisecond); n != 1 { |
| + t.Fatalf("closed %d at the bound, want 1", n) |
| + } |
| + if time.Since(start) < 100*time.Millisecond { |
| + t.Fatal("the drain did not wait for its bound") |
| + } |
| + if err := <-ended; err == nil { |
| + t.Fatal("the request running at the bound was not ended") |
| + } |
| + waitInFlight(t, e, 0) |
| +} |
| + |
| +func waitInFlight(t *testing.T, e *Edge, n int) { |
| + t.Helper() |
| + for i := 0; i < 200; i++ { |
| + if e.InFlight() == n { |
| + return |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + 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. |
| +func TestDrainConnectionsThroughServeHTTP(t *testing.T) { |
| + release := make(chan struct{}) |
| + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/long" { |
| + w.WriteHeader(200) |
| + w.(http.Flusher).Flush() |
| + select { |
| + case <-r.Context().Done(): |
| + case <-release: |
| + } |
| + return |
| + } |
| + io.WriteString(w, "ok") |
| + })) |
| + defer backend.Close() |
| + defer close(release) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "app.example.com", Kind: "service", Addr: backend.Listener.Addr().String(), Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := httptest.NewUnstartedServer(e) |
| + e.conns.serve(srv.Config) |
| + srv.Start() |
| + defer srv.Close() |
| + get := func(path string) (*http.Response, error) { |
| + req, _ := http.NewRequest("GET", srv.URL+path, nil) |
| + req.Host = "app.example.com" |
| + return srv.Client().Do(req) |
| + } |
| + 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) }() |
| + time.Sleep(50 * time.Millisecond) |
| + short, err := get("/short") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + short.Body.Close() |
| + if !short.Close { |
| + t.Fatal("a response while draining kept its connection") |
| + } |
| + if n := <-done; n != 1 { |
| + t.Fatalf("closed %d at the bound, want 1", n) |
| + } |
| + // 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/agent.go b/internal/host/agent.go| index 3568ec80d..45332d518 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1209,6 +1209,16 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| svc.SetDrainingSource(boxDrain.IsDraining) |
| svc.SetPeerDrainView(e.PeerDraining) |
| e.SetPeerDrainedHook(svc.DropHoldersNaming) |
| + // The drain driver and its root-only socket (hadrain.go), |
| + // on group members only: the drain verbs are theirs. |
| + if admission != nil && admission.group { |
| + driver := newDrainDriver(svc, e, boxDrain, groupStartFence.read) |
| + healthWG.Add(1) |
| + go func() { |
| + defer healthWG.Done() |
| + serveHADrainSocket(healthCtx, haDrainSocketPath, driver) |
| + }() |
| + } |
| svc.SetDutyView(func(rt registry.Route) boxchoice.WakeSnapshot { |
| if rt.IsSidecar() { |
| entry, ok := boxLifetimes.Lookup(rt.Host) |
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go| index ced0d9a05..2360cae90 100644 |
| --- a/internal/host/group_admission.go |
| +++ b/internal/host/group_admission.go |
| @@ -113,8 +113,15 @@ func (a *fixedAdmission) applyRole(role boxroles.Role, known bool) error { |
| func (a *fixedAdmission) startAllowed() bool { |
| a.mu.Lock() |
| defer a.mu.Unlock() |
| - return !a.closed && a.refusal == "" && a.known && a.role == boxroles.Serve && a.TenantAdmitted() |
| + return !a.closed && a.refusal == "" && a.known && a.role == boxroles.Serve && a.TenantAdmitted() && !(a.group && startFenced()) |
| } |
| + |
| +// startFenced reads the retained start fence (hadrainfence.go, region HA |
| +// §25.15 R3.1) at every start decision: a group member refuses every |
| +// tenant start while a fence is present, from any agent incarnation. A |
| +// seam for tests. |
| +var startFenced = func() bool { return groupStartFence.fenced() } |
| + |
| func (a *fixedAdmission) EdgesRole() (boxroles.Role, bool, bool) { |
| a.mu.Lock() |
| defer a.mu.Unlock() |
diff --git a/internal/host/group_maintenance_drain.go b/internal/host/group_maintenance_drain.go| new file mode 100644 |
| index 000000000..1183efc27 |
| --- /dev/null |
| +++ b/internal/host/group_maintenance_drain.go |
| @@ -0,0 +1,102 @@ |
| +package host |
| + |
| +// The drain verbs (region HA spec §25.4, §25.6 steps 2 to 5, §25.15 R3.1): |
| +// group-maintenance drain, drain --cancel and fence-clear. They run as |
| +// root under the apply lock, as every mutating verb does, so no apply runs |
| +// beside a drain. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "time" |
| +) |
| + |
| +var errDrainFailed = errors.New("drain failed") |
| + |
| +// 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 |
| +// report's result is ok. A fence of another transaction refuses before |
| +// anything is asked. |
| +func (cmd *groupMaintenanceCommand) runDrain(ctx context.Context, out io.Writer) error { |
| + fence := cmd.fenceAt() |
| + if f := fence.read(); f.Present && (f.Err != nil || f.Transaction != cmd.txn) { |
| + return errFenceOther |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, haDrainCallBound) |
| + defer cancel() |
| + client := cmd.drainSocket() |
| + rep, err := client.step(ctx, "withdraw", cmd.txn) |
| + if err != nil { |
| + return err |
| + } |
| + if rep.Result == "ok" { |
| + // The withdrawal is acknowledged: close the start gate (§25.4 |
| + // step 2), retained across agent restarts. |
| + if err = fence.install(cmd.txn, time.Now()); err != nil { |
| + return err |
| + } |
| + if rep, err = client.step(ctx, "move", cmd.txn); err != nil { |
| + return err |
| + } |
| + } |
| + b, err := json.Marshal(rep) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err = out.Write(append(b, '\n')); err != nil { |
| + return err |
| + } |
| + if rep.Result != "ok" { |
| + return errDrainFailed |
| + } |
| + return nil |
| +} |
| + |
| +// 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. |
| +func (cmd *groupMaintenanceCommand) runDrainCancel(ctx context.Context) error { |
| + fence := cmd.fenceAt() |
| + if f := fence.read(); f.Present && (f.Err != nil || f.Transaction != cmd.txn) { |
| + return errFenceOther |
| + } |
| + 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 |
| + } |
| + return fence.remove(cmd.txn) |
| +} |
| + |
| +// handoverStatus is status's fence and drain fields: the fence read from |
| +// disk, and one bounded ask of the agent's drain socket. |
| +func (cmd *groupMaintenanceCommand) handoverStatus(ctx context.Context) (maintenanceFenceStatus, maintenanceDrainStatus) { |
| + fs := maintenanceFenceStatus{State: "absent"} |
| + switch f := cmd.fenceAt().read(); { |
| + case f.Present && f.Err != nil: |
| + fs.State, fs.Error = "unknown", maintenanceError(f.Err) |
| + case f.Present: |
| + txn := f.Transaction |
| + fs.State, fs.Transaction = "present", &txn |
| + } |
| + ds := maintenanceDrainStatus{State: "unknown"} |
| + sctx, cancel := context.WithTimeout(ctx, time.Second) |
| + defer cancel() |
| + s, err := cmd.drainSocket().status(sctx) |
| + if err != nil { |
| + ds.Error = maintenanceError(err) |
| + return fs, ds |
| + } |
| + ds.State = "known" |
| + ds.Incarnation, ds.Result = &s.Incarnation, &s.Result |
| + if s.Transaction != "" { |
| + ds.Transaction = &s.Transaction |
| + } |
| + if s.Step != "" { |
| + ds.Step = &s.Step |
| + } |
| + return fs, ds |
| +} |
diff --git a/internal/host/group_maintenance_verbs.go b/internal/host/group_maintenance_verbs.go| index a11cc2bbe..3a7c0a879 100644 |
| --- a/internal/host/group_maintenance_verbs.go |
| +++ b/internal/host/group_maintenance_verbs.go |
| @@ -18,7 +18,7 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -const groupMaintenanceHelp = `Usage: carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback} |
| +const groupMaintenanceHelp = `Usage: carlos system group-maintenance {status|permit|revoke|prepare|apply|rollback|drain|fence-clear} |
| Root only, on a group member. Use through the attended Session Manager operator. |
| prepare --sha256 <digest> |
| Verify the configured signed pointer, cache its artifact and write a request. |
| @@ -35,6 +35,16 @@ Root only, on a group member. Use through the attended Session Manager operator. |
| Local only. A consumed rollback permit cannot be replayed. |
| permit Read at most 4096 bytes of permit JSON from stdin and install it. |
| revoke Remove the permit. Keep all consumed-action records. |
| + drain <transaction> |
| + Drain this member for a planned handover: withdraw it and wait for every |
| + live box to acknowledge, install the start fence for the transaction, |
| + then move every awake host away and drain the connections. Print the |
| + agent's JSON report. Exit 0 only when the report's result is ok. |
| + drain --cancel <transaction> |
| + End the drain of the transaction and remove its start fence. |
| + fence-clear <transaction> |
| + Remove the start fence of the transaction. Another transaction's fence |
| + is refused. |
| status Print one v1 JSON object, at most 8192 bytes. Make one local health GET. |
| Status includes edge.started_at in UTC at second precision, derived from kernel boot time and clock ticks. |
| It is a lower bound, up to two seconds early; compare with a generation at least two seconds later and check the edge identity has not changed. |
| @@ -58,15 +68,19 @@ func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int |
| } |
| return 0 |
| } |
| - verb, digest, err := maintenanceArguments(args) |
| + verb, value, err := maintenanceArguments(args) |
| if err != nil { |
| fmt.Fprint(stderr, groupMaintenanceHelp) |
| return 2 |
| } |
| + digest, txn := value, "" |
| + if drainVerb(verb) { |
| + digest, txn = "", value |
| + } |
| cmd := groupMaintenanceCommand{ |
| a: &systemApplier{etcDir: "/etc", optDir: release.OptDir(), dataDir: dataDir(), ops: productionSysOps()}, |
| euid: os.Geteuid, root: "/", edge: maintenanceEdgeProcess, |
| - client: maintenanceHealthClient(nil), sha256: digest, |
| + client: maintenanceHealthClient(nil), sha256: digest, txn: txn, |
| startedAt: func(start string) (string, error) { return maintenanceProcessStartedAt("/proc", start) }, |
| configure: configureMaintenanceApplier, |
| } |
| @@ -88,6 +102,32 @@ type groupMaintenanceCommand struct { |
| sha256 string |
| startedAt func(string) (string, error) |
| configure func(*systemApplier, map[string]string) error |
| + // txn is the drain verbs' transaction. |
| + txn string |
| + // fence and drain are the start fence and the agent's drain socket; |
| + // zero means production's (groupStartFence, haDrainSocketPath). |
| + fence *fenceLocation |
| + drain *drainClient |
| +} |
| + |
| +// drainVerb is whether verb is one of the drain verbs, whose argument is a |
| +// transaction. |
| +func drainVerb(verb string) bool { |
| + return verb == "drain" || verb == "drain-cancel" || verb == "fence-clear" |
| +} |
| + |
| +func (cmd *groupMaintenanceCommand) fenceAt() fenceLocation { |
| + if cmd.fence != nil { |
| + return *cmd.fence |
| + } |
| + return groupStartFence |
| +} |
| + |
| +func (cmd *groupMaintenanceCommand) drainSocket() *drainClient { |
| + if cmd.drain != nil { |
| + return cmd.drain |
| + } |
| + return newDrainClient(haDrainSocketPath) |
| } |
| func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io.Reader, out io.Writer) error { |
| @@ -101,7 +141,7 @@ func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io. |
| if c == nil { |
| return errors.New("group marker required") |
| } |
| - if verb != "permit" && verb != "revoke" && verb != "status" && verb != "prepare" && verb != "apply" && verb != "rollback" { |
| + if verb != "permit" && verb != "revoke" && verb != "status" && verb != "prepare" && verb != "apply" && verb != "rollback" && !drainVerb(verb) { |
| return errors.New("unknown operation") |
| } |
| // Use the same lock and refusal behavior as system apply. Refuse before |
| @@ -145,6 +185,14 @@ func (cmd *groupMaintenanceCommand) run(ctx context.Context, verb string, in io. |
| if verb == "rollback" { |
| return cmd.rollback(ctx, c) |
| } |
| + switch verb { |
| + case "drain": |
| + return cmd.runDrain(ctx, out) |
| + case "drain-cancel": |
| + return cmd.runDrainCancel(ctx) |
| + case "fence-clear": |
| + return cmd.fenceAt().remove(cmd.txn) |
| + } |
| var body []byte |
| var permit groupMaintenancePermit |
| if verb == "permit" { |
| @@ -205,6 +253,24 @@ type groupMaintenanceStatus struct { |
| BinaryError *string `json:"binary_error"` |
| Permit maintenancePermitStatus `json:"permit"` |
| Health maintenanceHealthStatus `json:"health"` |
| + // Fence and Drain are the planned-handover state (region HA §25.4, |
| + // §25.15 R3.1): the start fence on disk, and the agent's drain and |
| + // incarnation, for the roll tool's pre-action check (H5). |
| + Fence maintenanceFenceStatus `json:"fence"` |
| + Drain maintenanceDrainStatus `json:"drain"` |
| +} |
| +type maintenanceFenceStatus struct { |
| + State string `json:"state"` |
| + Transaction *string `json:"transaction"` |
| + Error *string `json:"error"` |
| +} |
| +type maintenanceDrainStatus struct { |
| + State string `json:"state"` |
| + Incarnation *string `json:"incarnation"` |
| + Transaction *string `json:"transaction"` |
| + Step *string `json:"step"` |
| + Result *string `json:"result"` |
| + Error *string `json:"error"` |
| } |
| type maintenanceProcessStatus struct { |
| State string `json:"state"` |
| @@ -297,6 +363,7 @@ func (cmd *groupMaintenanceCommand) permitStatus(c *hostenv.GroupConfig, hasDir |
| func (cmd *groupMaintenanceCommand) status(ctx context.Context, c *hostenv.GroupConfig, permit maintenancePermitStatus, out io.Writer) error { |
| s := groupMaintenanceStatus{V: 1, Instance: c.InstanceID, BootID: c.BootID, Account: c.Account, Region: c.AWSRegion, Group: c.Group, ConfigDigest: c.ConfigDigest, BoxRef: groupReferenceOf(c.Account, c.InstanceID), Permit: permit, Health: maintenanceHealthStatus{State: "unknown"}, Edge: maintenanceProcessStatus{State: "unknown"}} |
| + s.Fence, s.Drain = cmd.handoverStatus(ctx) |
| digest, err := maintenanceBinaryDigest(systemBinaryPath(cmd.a.optDir)) |
| if err == nil { |
| s.BinarySHA256 = &digest |
| @@ -373,5 +440,16 @@ func maintenanceArguments(args []string) (string, string, error) { |
| if len(args) == 1 && (args[0] == "permit" || args[0] == "revoke" || args[0] == "status" || args[0] == "apply" || args[0] == "rollback") { |
| return args[0], "", nil |
| } |
| + // A transaction argument never starts with "-", so a flag is never |
| + // read as one. |
| + txn := func(s string) bool { return groupTransactionID.MatchString(s) && s[0] != '-' } |
| + switch { |
| + case len(args) == 2 && args[0] == "drain" && txn(args[1]): |
| + return "drain", args[1], nil |
| + case len(args) == 3 && args[0] == "drain" && args[1] == "--cancel" && txn(args[2]): |
| + return "drain-cancel", args[2], nil |
| + case len(args) == 2 && args[0] == "fence-clear" && txn(args[1]): |
| + return "fence-clear", args[1], nil |
| + } |
| return "", "", errGroupMaintenance |
| } |
diff --git a/internal/host/hadrain.go b/internal/host/hadrain.go| new file mode 100644 |
| index 000000000..db53253a6 |
| --- /dev/null |
| +++ b/internal/host/hadrain.go |
| @@ -0,0 +1,653 @@ |
| +package host |
| + |
| +// The drain driver (region HA spec §25.4 steps 1 to 5, H5, §25.15 R3.1): |
| +// the agent-side orchestration of a planned handover of this box. The |
| +// group-maintenance drain verb (root) asks for it over the agent's drain |
| +// socket (hadrain_socket.go) in two steps: |
| +// |
| +// 1. withdraw: publish the drain state and wait until every live box of |
| +// the deployment acknowledges it (step 1); |
| +// 2. the verb installs the start fence for the transaction |
| +// (hadrainfence.go), which closes the tenant start gate; |
| +// 3. move: check the fence, then quiesce (step 2), move each awake host |
| +// (step 3), publish drained and wait for its acknowledgement, drain the |
| +// connections (step 4), and report (step 5). |
| +// |
| +// The report carries this agent's incarnation, which changes at every |
| +// restart, and stays in memory until the agent exits. A restarted agent |
| +// has no drain state and no report, so the tool's pre-action check sees |
| +// the drain void (H5); the fence, on disk, still refuses every start. |
| +// |
| +// On a failure every hold still waiting ends with today's answer |
| +// (SetMoveLeft), release work already running goes on under the |
| +// activator's own budgets and obligations, and the drain state and the |
| +// fence stay until drain --cancel. There is no override. |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "sort" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The drain's bounds (§25.4). |
| +var ( |
| + drainAckEvery = 5 * time.Second |
| + drainAckBound = 2 * time.Minute |
| + drainInflightBound = 10 * time.Second |
| + drainConnBound = 60 * time.Second |
| + drainTakeBound = 40 * time.Second |
| + drainDeadlineBase = 15 * time.Minute |
| + drainDeadlinePer20 = time.Minute |
| + drainQuietPoll = 100 * time.Millisecond |
| + drainMovesAtOnce = 4 |
| + drainPublishTimeout = 2 * time.Minute |
| +) |
| + |
| +// agentIncarnation is this process's start identity: new at every agent |
| +// start, never reused (§25.3 H5: an agent restart voids the drain). |
| +var agentIncarnation = newIncarnation() |
| + |
| +func newIncarnation() string { |
| + var b [16]byte |
| + if _, err := rand.Read(b[:]); err != nil { |
| + return fmt.Sprintf("t%d", time.Now().UnixNano()) |
| + } |
| + return hex.EncodeToString(b[:]) |
| +} |
| + |
| +// drainDeadline is 15 minutes plus 1 minute per 20 awake hosts. |
| +func drainDeadline(awake int) time.Duration { |
| + return drainDeadlineBase + time.Duration(awake/20)*drainDeadlinePer20 |
| +} |
| + |
| +// drainActivator is the activator's half (internal/activator hadrainmove.go |
| +// and handover.go). |
| +type drainActivator interface { |
| + DrainQuietNow() activator.DrainQuiet |
| + DrainHosts() []activator.DrainHost |
| + DrainHeld() []string |
| + BeginMove(host string) error |
| + WaitMoveTickets(ctx context.Context, host string) error |
| + WaitDrainInflight(ctx context.Context, host string) error |
| + SetMoveReleasing(host string) error |
| + DrainStop(ctx context.Context, host string) (activator.DrainRelease, error) |
| + SetMoveTaken(host, holderRef string, lockGen int64) error |
| + SetMoveLeft(host, reason string) |
| + EndDrainMoves() |
| + DrainTakeOwner(ctx context.Context, rt registry.Route) (string, int64, bool) |
| + ResetDrainHoldStats() |
| + DrainHoldStatsNow() activator.DrainHoldStats |
| +} |
| + |
| +// drainEdge is the edge's half (internal/edge hadrain.go, hatake.go, |
| +// hadrainconns.go). |
| +type drainEdge interface { |
| + DrainAckPeers(now time.Time) []string |
| + AskDrainSeen(ctx context.Context, peer, txn, phase string, id uint64) (bool, error) |
| + PeerTakes(ref string) bool |
| + 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 |
| + EndConnectionDrain() |
| +} |
| + |
| +// drainMarks is the box's drain state (hadrainstate.go). |
| +type drainMarks interface { |
| + begin(txn string) error |
| + setDrained() error |
| + clear() |
| + waitPublished(ctx context.Context) (haDrainMark, error) |
| +} |
| + |
| +// drainReport is the drain's JSON report (§25.4 step 5), the contract the |
| +// roll tool reads (Task 6). |
| +type drainReport struct { |
| + V int `json:"v"` |
| + Transaction string `json:"transaction"` |
| + // Incarnation is the agent process that made the report. |
| + Incarnation string `json:"incarnation"` |
| + // Step is the last step run: "withdraw" or "move". |
| + Step string `json:"step"` |
| + // Result is "running", "ok" or "failed". |
| + Result string `json:"result"` |
| + Reasons []string `json:"reasons"` |
| + // Fence is the start fence's transaction as the move step read it, |
| + // at its start and again at its end. |
| + Fence string `json:"fence"` |
| + StartedAt time.Time `json:"started_at"` |
| + FinishedAt *time.Time `json:"finished_at"` |
| + Acked []string `json:"acked"` |
| + Moved []drainMoved `json:"moved"` |
| + Released []drainLeft `json:"released"` |
| + Unclean []string `json:"unclean"` |
| + Left []drainLeft `json:"left"` |
| + Holds drainHolds `json:"holds"` |
| + Closed int `json:"connections_closed_at_bound"` |
| + Quiet drainQuietOut `json:"quiet"` |
| +} |
| + |
| +// drainMoved is one host moved: its confirmed holder and lock generation. |
| +type drainMoved struct { |
| + Host string `json:"host"` |
| + Holder string `json:"holder"` |
| + Gen int64 `json:"gen"` |
| + // Confirmed is "take", or "lock" when the take timed out and the one |
| + // lock re-read named the holder (build ruling, Task 4). |
| + Confirmed string `json:"confirmed"` |
| +} |
| + |
| +// drainLeft is a host released without a move, or left by a failed one. |
| +type drainLeft struct { |
| + Host string `json:"host"` |
| + // Kind is "worker" (an always-on worker: released with its marker, |
| + // resumes at departure), "other" (awake, not an HA instance) or, for |
| + // Left, the failure. |
| + Kind string `json:"kind"` |
| + Marker bool `json:"marker"` |
| + Clean bool `json:"clean"` |
| + Reason string `json:"reason,omitempty"` |
| +} |
| + |
| +type drainHolds struct { |
| + LongestMS int64 `json:"longest_ms"` |
| + Todays int `json:"todays_answer"` |
| + RefusedAtOnce int `json:"refused_at_once"` |
| +} |
| + |
| +type drainQuietOut struct { |
| + activator.DrainQuiet |
| + Held []string `json:"held"` |
| +} |
| + |
| +// drainDriver is one agent's drains: at most one transaction at a time. |
| +type drainDriver struct { |
| + act drainActivator |
| + edge drainEdge |
| + marks drainMarks |
| + fence func() fenceState |
| + now func() time.Time |
| + |
| + mu sync.Mutex |
| + // txn is the drain transaction this agent is in, "" for none. |
| + txn string |
| + // run is the step running or last run, and report its report. |
| + run *drainRun |
| + report *drainReport |
| + deadline time.Time |
| + // withdrawn is set once the withdraw step succeeded for txn. |
| + withdrawn bool |
| +} |
| + |
| +type drainRun struct { |
| + step string |
| + cancel context.CancelFunc |
| + done chan struct{} |
| +} |
| + |
| +var ( |
| + errDrainOtherTxn = errors.New("another drain transaction is in progress") |
| + 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") |
| +) |
| + |
| +func newDrainDriver(act drainActivator, e drainEdge, marks drainMarks, fence func() fenceState) *drainDriver { |
| + return &drainDriver{act: act, edge: e, marks: marks, fence: fence, now: time.Now} |
| +} |
| + |
| +// start runs step for txn, or joins the same step already running, and |
| +// returns its completion and report. A finished move that succeeded is |
| +// answered again as it was. |
| +func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| + if !groupTransactionID.MatchString(txn) { |
| + return nil, errGroupMaintenance |
| + } |
| + if step != "withdraw" && step != "move" { |
| + return nil, errDrainUnknown |
| + } |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + if d.txn != "" && d.txn != txn { |
| + return nil, errDrainOtherTxn |
| + } |
| + if r := d.run; r != nil { |
| + select { |
| + case <-r.done: |
| + default: |
| + if r.step != step { |
| + return nil, fmt.Errorf("the %s step is running", r.step) |
| + } |
| + return r.done, nil |
| + } |
| + } |
| + if step == "move" && d.report != nil && d.report.Step == "move" && d.report.Result == "ok" { |
| + done := make(chan struct{}) |
| + close(done) |
| + return done, nil |
| + } |
| + if step == "move" && !d.withdrawn { |
| + return nil, errDrainStep |
| + } |
| + if step == "move" { |
| + if f := d.fence(); !f.Present || f.Err != nil || f.Transaction != txn { |
| + return nil, errDrainNoFence |
| + } |
| + } |
| + now := d.now() |
| + if step == "withdraw" || d.deadline.IsZero() { |
| + d.deadline = now.Add(drainDeadline(len(d.act.DrainHosts()))) |
| + } |
| + if step == "withdraw" { |
| + d.withdrawn = false |
| + } |
| + d.txn = txn |
| + ctx, cancel := context.WithDeadline(context.Background(), d.deadline) |
| + r := &drainRun{step: step, cancel: cancel, done: make(chan struct{})} |
| + rep := &drainReport{V: 1, Transaction: txn, Incarnation: agentIncarnation, Step: step, Result: "running", StartedAt: now, |
| + Reasons: []string{}, Acked: []string{}, Moved: []drainMoved{}, Released: []drainLeft{}, Unclean: []string{}, Left: []drainLeft{}} |
| + d.run, d.report = r, rep |
| + go func() { |
| + defer close(r.done) |
| + defer cancel() |
| + var reasons []string |
| + if step == "withdraw" { |
| + reasons = d.withdraw(ctx, txn, rep) |
| + } else { |
| + reasons = d.move(ctx, txn, rep) |
| + } |
| + if ctx.Err() == context.DeadlineExceeded { |
| + reasons = append(reasons, "the drain deadline passed") |
| + } |
| + end := d.now() |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + rep.FinishedAt = &end |
| + rep.Reasons = append(rep.Reasons, reasons...) |
| + rep.Result = "ok" |
| + if len(rep.Reasons) > 0 { |
| + rep.Result = "failed" |
| + } |
| + if step == "withdraw" { |
| + d.withdrawn = rep.Result == "ok" |
| + } |
| + }() |
| + return r.done, nil |
| +} |
| + |
| +// snapshot is a copy of the report, or nil. |
| +func (d *drainDriver) snapshot() *drainReport { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + if d.report == nil { |
| + return nil |
| + } |
| + c := *d.report |
| + c.Reasons = append([]string(nil), c.Reasons...) |
| + c.Acked = append([]string(nil), c.Acked...) |
| + c.Moved = append([]drainMoved(nil), c.Moved...) |
| + c.Released = append([]drainLeft(nil), c.Released...) |
| + c.Unclean = append([]string(nil), c.Unclean...) |
| + c.Left = append([]drainLeft(nil), c.Left...) |
| + c.Quiet.Held = append([]string(nil), c.Quiet.Held...) |
| + return &c |
| +} |
| + |
| +// cancel ends the drain of txn: a step running is cancelled and joined, |
| +// holds and redirects are dropped, the connection drain is undone and the |
| +// drain state cleared. The report goes. No drain is success; another |
| +// transaction refuses. |
| +func (d *drainDriver) cancel(ctx context.Context, txn string) error { |
| + if !groupTransactionID.MatchString(txn) { |
| + return errGroupMaintenance |
| + } |
| + d.mu.Lock() |
| + if d.txn != "" && d.txn != txn { |
| + d.mu.Unlock() |
| + return errDrainOtherTxn |
| + } |
| + r := d.run |
| + d.mu.Unlock() |
| + if r != nil { |
| + r.cancel() |
| + select { |
| + case <-r.done: |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| + } |
| + d.act.EndDrainMoves() |
| + d.edge.EndConnectionDrain() |
| + d.marks.clear() |
| + d.mu.Lock() |
| + d.txn, d.run, d.report, d.withdrawn, d.deadline = "", nil, nil, false, time.Time{} |
| + d.mu.Unlock() |
| + return nil |
| +} |
| + |
| +// drainStatus is the drain socket's status answer and the verb's status |
| +// field (H5's pre-action check). |
| +type drainStatus struct { |
| + Incarnation string `json:"incarnation"` |
| + Transaction string `json:"transaction"` |
| + Step string `json:"step"` |
| + Result string `json:"result"` |
| + Reasons int `json:"reasons"` |
| +} |
| + |
| +func (d *drainDriver) status() drainStatus { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + s := drainStatus{Incarnation: agentIncarnation, Transaction: d.txn, Result: "none"} |
| + if d.report != nil { |
| + s.Step, s.Result, s.Reasons = d.report.Step, d.report.Result, len(d.report.Reasons) |
| + } |
| + return s |
| +} |
| + |
| +func (d *drainDriver) note(f func()) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + f() |
| +} |
| + |
| +// withdraw is step 1: the drain state published and acknowledged. |
| +func (d *drainDriver) withdraw(ctx context.Context, txn string, rep *drainReport) []string { |
| + if err := d.marks.begin(txn); err != nil { |
| + return []string{err.Error()} |
| + } |
| + return d.publishAndAck(ctx, txn, edge.DrainPhaseDraining, rep) |
| +} |
| + |
| +// publishAndAck waits for the wanted drain state to be published, then |
| +// asks every live box until each has seen it: every 5 s, failing after 2 |
| +// minutes. |
| +func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep *drainReport) []string { |
| + pctx, cancel := context.WithTimeout(ctx, drainPublishTimeout) |
| + mark, err := d.marks.waitPublished(pctx) |
| + cancel() |
| + if err != nil { |
| + return []string{fmt.Sprintf("the %s state was not published: %v", phase, err)} |
| + } |
| + actx, acancel := context.WithTimeout(ctx, drainAckBound) |
| + defer acancel() |
| + peers := d.edge.DrainAckPeers(d.now()) |
| + seen := map[string]bool{} |
| + tick := time.NewTicker(drainAckEvery) |
| + defer tick.Stop() |
| + for { |
| + var wg sync.WaitGroup |
| + var mu sync.Mutex |
| + for _, p := range peers { |
| + if seen[p] { |
| + continue |
| + } |
| + wg.Add(1) |
| + 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() |
| + } |
| + }(p) |
| + } |
| + wg.Wait() |
| + var missing []string |
| + for _, p := range peers { |
| + if !seen[p] { |
| + missing = append(missing, 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)} |
| + case <-tick.C: |
| + } |
| + } |
| +} |
| + |
| +// move is steps 2 to 5. |
| +func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) []string { |
| + fence := func() bool { |
| + f := d.fence() |
| + return f.Present && f.Err == nil && f.Transaction == txn |
| + } |
| + if !fence() { |
| + return []string{errDrainNoFence.Error()} |
| + } |
| + d.note(func() { rep.Fence = txn }) |
| + // Step 2: the fence has closed the start gate; settle what crossed it. |
| + 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. |
| + d.act.ResetDrainHoldStats() |
| + var reasons []string |
| + var rmu sync.Mutex |
| + fail := func(s string) { |
| + rmu.Lock() |
| + reasons = append(reasons, s) |
| + rmu.Unlock() |
| + } |
| + sem := make(chan struct{}, drainMovesAtOnce) |
| + 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) |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + defer func() { <-sem }() |
| + if s := d.moveOne(ctx, txn, h, began, rep); 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)} |
| + } |
| + // Step 4: drained, acknowledged; then the connections. |
| + if err := d.marks.setDrained(); err != nil { |
| + return []string{err.Error()} |
| + } |
| + if r := d.publishAndAck(ctx, txn, edge.DrainPhaseDrained, rep); len(r) > 0 { |
| + return r |
| + } |
| + d.act.EndDrainMoves() |
| + closed := d.edge.DrainConnections(ctx, drainConnBound) |
| + d.note(func() { rep.Closed = closed }) |
| + // Step 5: certify (H5) from this incarnation. |
| + q := d.act.DrainQuietNow() |
| + held := d.act.DrainHeld() |
| + d.note(func() { rep.Quiet = drainQuietOut{DrainQuiet: q, Held: held} }) |
| + switch { |
| + case !q.Zero() || len(held) > 0: |
| + return []string{fmt.Sprintf("the box is not quiet at the report: %+v %v", q, held)} |
| + case !fence(): |
| + return []string{"the start fence for this transaction is gone"} |
| + } |
| + return nil |
| +} |
| + |
| +// 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 { |
| + t := time.NewTicker(drainQuietPoll) |
| + defer t.Stop() |
| + for { |
| + q := d.act.DrainQuietNow() |
| + if q.Zero() { |
| + return nil |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return fmt.Errorf("%w: %+v", ctx.Err(), 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 |
| + leave := func(kind, reason string, rel activator.DrainRelease) string { |
| + d.act.SetMoveLeft(host, reason) |
| + d.note(func() { |
| + rep.Left = append(rep.Left, drainLeft{Host: host, Kind: kind, Marker: rel.Marker, Clean: rel.Clean, Reason: reason}) |
| + }) |
| + return host + ": " + reason |
| + } |
| + 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. |
| + return "" |
| + } |
| + return leave("begin", err.Error(), activator.DrainRelease{}) |
| + } |
| + // 3.2: tickets and the in-flight drain share today's 10 s bound. At the |
| + // bound the stop ends what is left, as a shutdown stop does. |
| + ictx, icancel := context.WithTimeout(ctx, drainInflightBound) |
| + _ = d.act.WaitMoveTickets(ictx, host) |
| + _ = d.act.WaitDrainInflight(ictx, host) |
| + icancel() |
| + if err := d.act.SetMoveReleasing(host); err != nil { |
| + return leave("release", err.Error(), activator.DrainRelease{}) |
| + } |
| + // 3.3: the stop and its marker, through finishStop. |
| + rel, err := d.act.DrainStop(ctx, host) |
| + switch { |
| + case err != nil: |
| + return leave("release", fmt.Sprintf("the release did not finish: %v", err), rel) |
| + case !rel.Marker: |
| + return leave("release", "released without a marker", rel) |
| + case !rel.Clean: |
| + d.note(func() { rep.Unclean = append(rep.Unclean, host) }) |
| + return leave("unclean", "the release was unclean", rel) |
| + } |
| + // 3.4: the take. |
| + holder, gen, how, err := d.take(ctx, txn, h) |
| + if err != nil { |
| + return leave("take", err.Error(), rel) |
| + } |
| + // 3.5: release the holds to the confirmed holder. |
| + if err := d.act.SetMoveTaken(host, holder, gen); err != nil { |
| + return leave("take", err.Error(), rel) |
| + } |
| + d.note(func() { |
| + rep.Moved = append(rep.Moved, drainMoved{Host: host, Holder: holder, Gen: gen, Confirmed: how}) |
| + }) |
| + return "" |
| +} |
| + |
| +// take chooses successors with ChooseRoomiest among the serving peers |
| +// that answer takes, and asks them in turn while they refuse before any |
| +// acquire. A take that times out is checked with one lock re-read: a |
| +// non-draining owner in view is the confirmed holder. |
| +func (d *drainDriver) take(ctx context.Context, txn string, h activator.DrainHost) (string, int64, string, error) { |
| + rt := h.Route |
| + s := d.edge.DrainSnapshot(rt) |
| + var cands []boxchoice.Candidate |
| + for _, c := range s.Serving { |
| + if c.BoxID != s.Self && d.edge.PeerTakes(c.BoxID) && !d.edge.PeerDraining(c.BoxID) { |
| + cands = append(cands, c) |
| + } |
| + } |
| + for len(cands) > 0 { |
| + pool := boxchoice.Placeable(cands, nil, d.now()) |
| + if len(pool) == 0 { |
| + pool = cands // wakes are never refused for headroom (A20) |
| + } |
| + c, ok := boxchoice.ChooseRoomiest(rt.Host, pool, s.Running, rt.App) |
| + if !ok { |
| + break |
| + } |
| + tctx, cancel := context.WithTimeout(ctx, drainTakeBound) |
| + holder, gen, err := d.edge.Take(tctx, c.BoxID, rt.Host, h.Lifetime, h.Gen, txn) |
| + timedOut := tctx.Err() == context.DeadlineExceeded |
| + cancel() |
| + if err == nil { |
| + return holder, gen, "take", nil |
| + } |
| + var refused *edge.TakeRefusedError |
| + if errors.As(err, &refused) { |
| + cands = slicesDeleteCandidate(cands, c.BoxID) |
| + continue |
| + } |
| + if timedOut || errors.Is(err, context.DeadlineExceeded) { |
| + if ref, g, ok := d.act.DrainTakeOwner(ctx, rt); ok && ref != s.Self && s.Peers[ref] && !d.edge.PeerDraining(ref) { |
| + return ref, g, "lock", nil |
| + } |
| + } |
| + return "", 0, "", fmt.Errorf("the take by %s failed: %v", c.BoxID, err) |
| + } |
| + return "", 0, "", errors.New("no successor takes the host") |
| +} |
| + |
| +func slicesDeleteCandidate(cands []boxchoice.Candidate, box string) []boxchoice.Candidate { |
| + out := cands[:0:0] |
| + for _, c := range cands { |
| + if c.BoxID != box { |
| + out = append(out, c) |
| + } |
| + } |
| + return out |
| +} |
diff --git a/internal/host/hadrain_socket.go b/internal/host/hadrain_socket.go| new file mode 100644 |
| index 000000000..430870337 |
| --- /dev/null |
| +++ b/internal/host/hadrain_socket.go |
| @@ -0,0 +1,183 @@ |
| +package host |
| + |
| +// The agent's drain socket: how the root group-maintenance verbs reach the |
| +// drain driver (hadrain.go). It is a unix socket in a directory only the |
| +// agent's user can enter (0700), and the listener serves only a peer the |
| +// kernel reports as root (SO_PEERCRED). Instances never see it: their |
| +// namespaces replace /run/carlos with an empty tmpfs. |
| +// |
| +// POST /v1/drain/withdraw {"transaction":T} step 1; answers the report |
| +// POST /v1/drain/move {"transaction":T} steps 2-5; answers the report |
| +// POST /v1/drain/cancel {"transaction":T} drain --cancel |
| +// GET /v1/drain/status incarnation and drain state |
| +// |
| +// A step runs on the agent, not on the request: a caller that goes away |
| +// leaves it running, and asking again with the same transaction joins it. |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "time" |
| +) |
| + |
| +const ( |
| + haDrainSocketDir = "/run/carlos/.ha-drain" |
| + haDrainSocketPath = haDrainSocketDir + "/drain.sock" |
| + haDrainBodyMax = 4096 |
| + // haDrainCallBound is the verb's backstop on one step: the agent ends |
| + // every step by the drain deadline itself. |
| + haDrainCallBound = 3 * time.Hour |
| +) |
| + |
| +type drainAsk struct { |
| + Transaction string `json:"transaction"` |
| +} |
| + |
| +type drainError struct { |
| + Error string `json:"error"` |
| +} |
| + |
| +// handler is the socket's HTTP surface over d. |
| +func (d *drainDriver) handler() http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Content-Type", "application/json") |
| + if r.URL.RawQuery != "" { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if r.Method == http.MethodGet && r.URL.Path == "/v1/drain/status" { |
| + _ = json.NewEncoder(w).Encode(d.status()) |
| + return |
| + } |
| + if r.Method != http.MethodPost { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + var step string |
| + switch r.URL.Path { |
| + case "/v1/drain/withdraw": |
| + step = "withdraw" |
| + case "/v1/drain/move": |
| + step = "move" |
| + case "/v1/drain/cancel": |
| + step = "cancel" |
| + default: |
| + http.NotFound(w, r) |
| + return |
| + } |
| + b, err := io.ReadAll(io.LimitReader(r.Body, haDrainBodyMax+1)) |
| + var ask drainAsk |
| + dec := json.NewDecoder(bytes.NewReader(b)) |
| + dec.DisallowUnknownFields() |
| + if err != nil || len(b) > haDrainBodyMax || dec.Decode(&ask) != nil || !groupTransactionID.MatchString(ask.Transaction) { |
| + w.WriteHeader(http.StatusBadRequest) |
| + _ = json.NewEncoder(w).Encode(drainError{Error: errGroupMaintenance.Error()}) |
| + return |
| + } |
| + if step == "cancel" { |
| + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) |
| + defer cancel() |
| + if err := d.cancel(ctx, ask.Transaction); err != nil { |
| + w.WriteHeader(http.StatusConflict) |
| + _ = json.NewEncoder(w).Encode(drainError{Error: err.Error()}) |
| + return |
| + } |
| + _ = json.NewEncoder(w).Encode(struct{}{}) |
| + return |
| + } |
| + done, err := d.start(ask.Transaction, step) |
| + if err != nil { |
| + w.WriteHeader(http.StatusConflict) |
| + _ = json.NewEncoder(w).Encode(drainError{Error: err.Error()}) |
| + return |
| + } |
| + select { |
| + case <-done: |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + _ = json.NewEncoder(w).Encode(d.snapshot()) |
| + }) |
| +} |
| + |
| +// drainClient is the root verbs' side of the socket. |
| +type drainClient struct { |
| + c *http.Client |
| +} |
| + |
| +func newDrainClient(path string) *drainClient { |
| + tr := &http.Transport{Proxy: nil, DisableKeepAlives: true, |
| + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + var dl net.Dialer |
| + return dl.DialContext(ctx, "unix", path) |
| + }} |
| + return &drainClient{c: &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} |
| +} |
| + |
| +// errDrainAgentDown is a socket nobody listens on: no agent runs, so no |
| +// agent holds drain state. |
| +var errDrainAgentDown = errors.New("the agent's drain socket is not answering") |
| + |
| +func (c *drainClient) call(ctx context.Context, method, path string, body any, out any) error { |
| + var rd io.Reader |
| + if body != nil { |
| + b, err := json.Marshal(body) |
| + if err != nil { |
| + return err |
| + } |
| + rd = bytes.NewReader(b) |
| + } |
| + req, err := http.NewRequestWithContext(ctx, method, "http://agent"+path, rd) |
| + if err != nil { |
| + return err |
| + } |
| + resp, err := c.c.Do(req) |
| + if err != nil { |
| + var op *net.OpError |
| + if errors.As(err, &op) && op.Op == "dial" { |
| + return errors.Join(errDrainAgentDown, err) |
| + } |
| + return err |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) |
| + if err != nil { |
| + return err |
| + } |
| + if resp.StatusCode != http.StatusOK { |
| + var e drainError |
| + if json.Unmarshal(b, &e) == nil && e.Error != "" { |
| + return errors.New(e.Error) |
| + } |
| + return fmt.Errorf("drain socket answered %d", resp.StatusCode) |
| + } |
| + if out != nil { |
| + return json.Unmarshal(b, out) |
| + } |
| + return nil |
| +} |
| + |
| +func (c *drainClient) step(ctx context.Context, step, txn string) (*drainReport, error) { |
| + var rep drainReport |
| + if err := c.call(ctx, http.MethodPost, "/v1/drain/"+step, drainAsk{Transaction: txn}, &rep); err != nil { |
| + return nil, err |
| + } |
| + return &rep, nil |
| +} |
| + |
| +func (c *drainClient) cancel(ctx context.Context, txn string) error { |
| + return c.call(ctx, http.MethodPost, "/v1/drain/cancel", drainAsk{Transaction: txn}, nil) |
| +} |
| + |
| +func (c *drainClient) status(ctx context.Context) (drainStatus, error) { |
| + var s drainStatus |
| + err := c.call(ctx, http.MethodGet, "/v1/drain/status", nil, &s) |
| + return s, err |
| +} |
diff --git a/internal/host/hadrain_socket_linux.go b/internal/host/hadrain_socket_linux.go| new file mode 100644 |
| index 000000000..d092bcceb |
| --- /dev/null |
| +++ b/internal/host/hadrain_socket_linux.go |
| @@ -0,0 +1,100 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "log" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "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 } |
| + |
| +type drainPeerKey struct{} |
| + |
| +// serveHADrainSocket serves d on path until ctx ends. Errors are logged: |
| +// a box without the socket cannot be drained, and the verb says so. |
| +func serveHADrainSocket(ctx context.Context, path string, d *drainDriver) { |
| + if err := serveHADrain(ctx, path, d.handler()); err != nil && ctx.Err() == nil { |
| + log.Printf("agent: drain socket %s: %v", path, err) |
| + } |
| +} |
| + |
| +func serveHADrain(ctx context.Context, path string, h http.Handler) error { |
| + dir := filepath.Dir(path) |
| + if err := os.MkdirAll(dir, 0700); err != nil { |
| + return err |
| + } |
| + info, err := os.Lstat(dir) |
| + if err != nil { |
| + return err |
| + } |
| + if st, ok := info.Sys().(*syscall.Stat_t); !ok || !info.IsDir() || st.Uid != uint32(os.Geteuid()) { |
| + return os.ErrPermission |
| + } |
| + if err := os.Chmod(dir, 0700); err != nil { |
| + return err |
| + } |
| + lock, err := os.Open(dir) |
| + if err != nil { |
| + return err |
| + } |
| + defer lock.Close() |
| + if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| + return err |
| + } |
| + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + ln, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) |
| + if err != nil { |
| + return err |
| + } |
| + defer ln.Close() |
| + if err := os.Chmod(path, 0600); err != nil { |
| + return err |
| + } |
| + srv := &http.Server{ReadHeaderTimeout: time.Second, MaxHeaderBytes: 4096, |
| + ConnContext: func(ctx context.Context, c net.Conn) context.Context { |
| + ok := false |
| + if uc, isUnix := c.(*net.UnixConn); isUnix { |
| + if raw, err := uc.SyscallConn(); err == nil { |
| + _ = raw.Control(func(fd uintptr) { |
| + cred, err := unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED) |
| + ok = err == nil && drainPeerAllowed(cred.Uid) |
| + }) |
| + } |
| + } |
| + return context.WithValue(ctx, drainPeerKey{}, ok) |
| + }, |
| + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if ok, _ := r.Context().Value(drainPeerKey{}).(bool); !ok { |
| + http.Error(w, "", http.StatusForbidden) |
| + return |
| + } |
| + h.ServeHTTP(w, r) |
| + })} |
| + done := make(chan error, 1) |
| + go func() { done <- srv.Serve(ln) }() |
| + select { |
| + case err := <-done: |
| + if errors.Is(err, http.ErrServerClosed) { |
| + return nil |
| + } |
| + return err |
| + case <-ctx.Done(): |
| + _ = srv.Close() |
| + <-done |
| + return nil |
| + } |
| +} |
diff --git a/internal/host/hadrain_socket_other.go b/internal/host/hadrain_socket_other.go| new file mode 100644 |
| index 000000000..e89d177ad |
| --- /dev/null |
| +++ b/internal/host/hadrain_socket_other.go |
| @@ -0,0 +1,8 @@ |
| +//go:build !linux |
| + |
| +package host |
| + |
| +import "context" |
| + |
| +// The drain socket is Linux-only, as group members are. |
| +func serveHADrainSocket(context.Context, string, *drainDriver) {} |
diff --git a/internal/host/hadrain_test.go b/internal/host/hadrain_test.go| new file mode 100644 |
| index 000000000..e8cc94687 |
| --- /dev/null |
| +++ b/internal/host/hadrain_test.go |
| @@ -0,0 +1,751 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/boxchoice" |
| + "github.com/carlosframework/platform/internal/edge" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// The drain driver against a fake activator and edge: each fake records |
| +// the calls in order (events), so the tests can check the sequence §25.4 |
| +// fixes. The real activator hooks are tested in internal/activator |
| +// (hadrainmove_test.go) over the lease fixture. |
| + |
| +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 |
| + |
| + 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 { |
| + return activator.DrainQuiet{} |
| + } |
| + return q() |
| +} |
| +func (f *fakeDrainAct) DrainHosts() []activator.DrainHost { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var out []activator.DrainHost |
| + for _, h := range f.hosts { |
| + if f.awake[h.Route.Host] { |
| + out = append(out, h) |
| + } |
| + } |
| + // As the activator does: busiest first. |
| + slices.SortStableFunc(out, func(a, b activator.DrainHost) int { return b.Inflight - a.Inflight }) |
| + return out |
| +} |
| +func (f *fakeDrainAct) DrainHeld() []string { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + var out []string |
| + for h, up := range f.awake { |
| + if up { |
| + out = append(out, h) |
| + } |
| + } |
| + slices.Sort(out) |
| + return out |
| +} |
| +func (f *fakeDrainAct) BeginMove(host string) error { |
| + f.ev("begin " + host) |
| + f.mu.Lock() |
| + f.begun = append(f.begun, host) |
| + cb := f.onBeginMove |
| + f.mu.Unlock() |
| + if cb != nil { |
| + cb(host) |
| + } |
| + 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) |
| + 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() |
| + rel, err := activator.DrainRelease{HA: true, Marker: true, Clean: true}, error(nil) |
| + if stop != nil { |
| + rel, err = stop(ctx, host) |
| + } |
| + if err == nil { |
| + f.mu.Lock() |
| + f.awake[host] = false |
| + f.mu.Unlock() |
| + } |
| + return rel, err |
| +} |
| +func (f *fakeDrainAct) SetMoveTaken(host, ref string, gen int64) error { |
| + f.ev(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) SetMoveLeft(host, reason string) { |
| + f.ev("left " + host) |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.left[host] = reason |
| +} |
| +func (f *fakeDrainAct) EndDrainMoves() { |
| + f.ev("end-moves") |
| + f.mu.Lock() |
| + f.ended++ |
| + f.mu.Unlock() |
| +} |
| +func (f *fakeDrainAct) DrainTakeOwner(_ context.Context, rt registry.Route) (string, int64, bool) { |
| + f.ev("owner " + rt.Host) |
| + if f.owner == nil { |
| + return "", 0, false |
| + } |
| + return f.owner(rt) |
| +} |
| +func (f *fakeDrainAct) ResetDrainHoldStats() { |
| + f.mu.Lock() |
| + f.resets++ |
| + f.mu.Unlock() |
| +} |
| +func (f *fakeDrainAct) DrainHoldStatsNow() activator.DrainHoldStats { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.stats |
| +} |
| + |
| +type fakeDrainEdge struct { |
| + 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 |
| +} |
| + |
| +func (f *fakeDrainEdge) ev(s string) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + if f.events != nil { |
| + *f.events = append(*f.events, s) |
| + } |
| +} |
| +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) |
| + } |
| + 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) DrainSnapshot(rt registry.Route) boxchoice.WakeSnapshot { |
| + now := time.Now().UTC().Format(time.RFC3339) |
| + return boxchoice.WakeSnapshot{Self: "a", Usable: true, LocalDenied: true, |
| + Serving: []boxchoice.Candidate{ |
| + {BoxID: "b", Generation: now, MemFreeMiB: 900, MemTotalMiB: 1000, DiskFreeMiB: 900, DiskTotalMiB: 1000}, |
| + {BoxID: "c", Generation: now, MemFreeMiB: 500, MemTotalMiB: 1000, DiskFreeMiB: 900, DiskTotalMiB: 1000}, |
| + }, |
| + 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.mu.Lock() |
| + f.takes = append(f.takes, host+"@"+peer) |
| + take, takeErr := f.take, f.takeErr |
| + f.mu.Unlock() |
| + if take != nil { |
| + return take(ctx, peer, host) |
| + } |
| + if takeErr != nil { |
| + return "", 0, takeErr |
| + } |
| + if lifetime == "" || gen <= 0 || txn == "" { |
| + return "", 0, errors.New("take without lifetime, generation or transaction") |
| + } |
| + return peer, gen + 1, nil |
| +} |
| +func (f *fakeDrainEdge) DrainConnections(context.Context, time.Duration) int { |
| + f.ev("connections") |
| + return f.closed |
| +} |
| +func (f *fakeDrainEdge) EndConnectionDrain() { |
| + f.mu.Lock() |
| + f.ends++ |
| + f.mu.Unlock() |
| +} |
| + |
| +type fakeMarks struct { |
| + 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") |
| + return nil |
| +} |
| +func (f *fakeMarks) setDrained() error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.drained++ |
| + f.id++ |
| + f.ev("drained") |
| + return nil |
| +} |
| +func (f *fakeMarks) clear() { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.cleared++ |
| +} |
| +func (f *fakeMarks) waitPublished(ctx context.Context) (haDrainMark, error) { |
| + f.mu.Lock() |
| + stuck, id := f.stuck, f.id |
| + f.mu.Unlock() |
| + if stuck { |
| + <-ctx.Done() |
| + return haDrainMark{}, ctx.Err() |
| + } |
| + return haDrainMark{Txn: "t", ID: id}, nil |
| +} |
| + |
| +func drainHost(host string, inflight int) activator.DrainHost { |
| + return activator.DrainHost{Route: registry.Route{Host: host, App: "app"}, Movable: true, Inflight: inflight, Lifetime: "life-" + host, Gen: 5} |
| +} |
| + |
| +// 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{}, |
| + hosts: []activator.DrainHost{ |
| + drainHost("quiet.example.com", 1), |
| + drainHost("busy.example.com", 5), |
| + {Route: registry.Route{Host: "worker.example.com"}, Worker: true}, |
| + {Route: registry.Route{Host: "plain.example.com"}}, |
| + }, |
| + 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} |
| +} |
| + |
| +func fenceOf(txn string) func() fenceState { |
| + return func() fenceState { return fenceState{Present: true, Transaction: txn} } |
| +} |
| + |
| +func shorten(v *time.Duration, d time.Duration) func() { |
| + prev := *v |
| + *v = d |
| + return func() { *v = prev } |
| +} |
| + |
| +func (d *drainDriver) startWithdrawForTest(txn string) error { |
| + done, err := d.start(txn, "withdraw") |
| + if err != nil { |
| + return err |
| + } |
| + <-done |
| + return nil |
| +} |
| + |
| +// runDrain runs both steps as the verb does, the fence installed between. |
| +func runDrain(t *testing.T, d *drainDriver, txn string) *drainReport { |
| + t.Helper() |
| + done, err := d.start(txn, "withdraw") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + <-done |
| + if r := d.snapshot(); r.Result != "ok" { |
| + return r |
| + } |
| + done, err = d.start(txn, "move") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + <-done |
| + return d.snapshot() |
| +} |
| + |
| +func indexOf(events []string, prefix string) int { |
| + for i, e := range events { |
| + if strings.HasPrefix(e, prefix) { |
| + return i |
| + } |
| + } |
| + return -1 |
| +} |
| + |
| +// 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. |
| +func TestDrainDriverWholeSequence(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + rep := runDrain(t, d, "t1") |
| + if rep.Result != "ok" || len(rep.Reasons) != 0 { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if rep.Incarnation != agentIncarnation || rep.Transaction != "t1" || rep.Fence != "t1" || rep.Step != "move" || rep.FinishedAt == nil { |
| + t.Fatalf("report header %+v", rep) |
| + } |
| + if len(rep.Moved) != 2 { |
| + t.Fatalf("moved %+v", rep.Moved) |
| + } |
| + for _, m := range rep.Moved { |
| + // ChooseRoomiest: b has the most free memory. |
| + if m.Holder != "b" || m.Gen != 6 || m.Confirmed != "take" { |
| + t.Fatalf("moved %+v", m) |
| + } |
| + } |
| + if len(rep.Released) != 2 || rep.Released[0].Kind == rep.Released[1].Kind { |
| + t.Fatalf("released %+v", rep.Released) |
| + } |
| + for _, r := range rep.Released { |
| + if !r.Marker || !r.Clean { |
| + t.Fatalf("released %+v", r) |
| + } |
| + } |
| + for _, take := range ed.takes { |
| + if strings.HasPrefix(take, "worker.") || strings.HasPrefix(take, "plain.") { |
| + t.Fatalf("a %s was taken", take) |
| + } |
| + } |
| + if act.begun[0] != "busy.example.com" { |
| + t.Fatalf("moves began %v, want the busiest first", act.begun) |
| + } |
| + 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"} |
| + last := -1 |
| + for _, step := range order { |
| + i := indexOf(ev, step) |
| + if i < 0 || i < last { |
| + t.Fatalf("%q out of order in %v", step, ev) |
| + } |
| + last = i |
| + } |
| + // Every move and release finished before drained was published. |
| + drained := indexOf(ev, "drained") |
| + for i, e := range ev { |
| + if (strings.HasPrefix(e, "stop ") || strings.HasPrefix(e, "taken ")) && i > drained { |
| + t.Fatalf("%q after drained: %v", e, ev) |
| + } |
| + } |
| + if marks.cleared != 0 { |
| + t.Fatal("a successful drain cleared the drain state") |
| + } |
| + // The move step is answered again as it was; a withdraw restarts it. |
| + done, err := d.start("t1", "move") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + <-done |
| + if again := d.snapshot(); again.StartedAt != rep.StartedAt { |
| + t.Fatal("a finished move ran again") |
| + } |
| +} |
| + |
| +// A wake still restoring, or an acquire paused before its PUT, when the |
| +// drain starts: nothing moves until the box is quiet. |
| +func TestDrainWaitsForQuiescence(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + var mu sync.Mutex |
| + settling := true |
| + act.quiet = func() activator.DrainQuiet { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if settling { |
| + return activator.DrainQuiet{Waking: 1} |
| + } |
| + return activator.DrainQuiet{} |
| + } |
| + 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) |
| + } |
| + time.Sleep(4 * drainQuietPoll) |
| + act.mu.Lock() |
| + begun := len(act.begun) |
| + act.mu.Unlock() |
| + if begun != 0 { |
| + t.Fatal("a move began while a wake was settling") |
| + } |
| + mu.Lock() |
| + settling = false |
| + mu.Unlock() |
| + <-done |
| + if rep := d.snapshot(); rep.Result != "ok" || len(rep.Moved) != 2 { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// The deadline: a box that never settles fails the drain at 15 minutes |
| +// plus a minute per 20 awake hosts, here shortened. |
| +func TestDrainDeadline(t *testing.T) { |
| + if got := drainDeadline(0); got != 15*time.Minute { |
| + t.Fatalf("deadline(0) = %s", got) |
| + } |
| + if got := drainDeadline(45); got != 17*time.Minute { |
| + t.Fatalf("deadline(45) = %s", got) |
| + } |
| + defer shorten(&drainDeadlineBase, 200*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + act.quiet = func() activator.DrainQuiet { return activator.DrainQuiet{Recovering: 1} } |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + rep := runDrain(t, d, "t1") |
| + 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 { |
| + t.Fatal("a failed drain left the drain state or published drained") |
| + } |
| +} |
| + |
| +// A stop that is unproven and still renewing: the release does not finish |
| +// by the deadline, the move is left (its holds get today's answer), and |
| +// the drain fails with the drain state kept. |
| +func TestDrainUnprovenStopFails(t *testing.T) { |
| + defer shorten(&drainDeadlineBase, 300*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + act.stop = func(ctx context.Context, host string) (activator.DrainRelease, error) { |
| + if host == "busy.example.com" { |
| + <-ctx.Done() |
| + return activator.DrainRelease{HA: true}, ctx.Err() |
| + } |
| + return activator.DrainRelease{HA: true, Marker: true, Clean: true}, nil |
| + } |
| + 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 marks.drained != 0 || marks.cleared != 0 || act.ended != 0 { |
| + t.Fatal("a failed drain went on to drained, or dropped the drain state") |
| + } |
| +} |
| + |
| +// An unclean release (Finish failed or files Final incomplete while the |
| +// marker succeeded) fails the drain; the host is not taken. |
| +func TestDrainUncleanReleaseFails(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + act.stop = func(_ context.Context, host string) (activator.DrainRelease, error) { |
| + return activator.DrainRelease{HA: true, Marker: true, Clean: host != "quiet.example.com"}, nil |
| + } |
| + 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"] == "" { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if act.taken["busy.example.com"] != "b" { |
| + t.Fatal("the clean host was not moved") |
| + } |
| + // A released worker's unclean marker fails it too. |
| + act, ed, marks = healthyDrain() |
| + act.stop = func(_ context.Context, host string) (activator.DrainRelease, error) { |
| + return activator.DrainRelease{HA: true, Marker: true, Clean: host != "worker.example.com"}, nil |
| + } |
| + rep = runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != "failed" || !slices.Equal(rep.Unclean, []string{"worker.example.com"}) { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// No marker (S3 down: an owed marker) fails the drain. |
| +func TestDrainNoMarkerFails(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + act.stop = func(context.Context, string) (activator.DrainRelease, error) { |
| + return activator.DrainRelease{HA: true}, nil |
| + } |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != "failed" || len(rep.Moved) != 0 { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// A take that fails fails the drain; the other host still moves. |
| +func TestDrainTakeFails(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + ed.take = func(_ context.Context, peer, host string) (string, int64, error) { |
| + if host == "quiet.example.com" { |
| + return "", 0, fmt.Errorf("ha-take: %w", edge.ErrTakeNoHolder) |
| + } |
| + 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"] == "" { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if indexOf(*act.events, "owner ") >= 0 { |
| + t.Fatal("a take that answered was re-read") |
| + } |
| +} |
| + |
| +// A take refused before any acquire tries the next roomiest successor. |
| +func TestDrainTakeRefusedTriesNext(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + ed.take = func(_ context.Context, peer, host string) (string, int64, error) { |
| + if peer == "b" { |
| + return "", 0, &edge.TakeRefusedError{Peer: "b", Reason: edge.TakeRefusedPool} |
| + } |
| + return peer, 9, nil |
| + } |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != "ok" || rep.Moved[0].Holder != "c" { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + // 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} |
| + 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) |
| + } |
| +} |
| + |
| +// A take that times out while the lock shows the successor counts as |
| +// taken, with the lock's holder and generation. An owner that is draining, |
| +// or out of view, does not. |
| +func TestDrainTakeTimeoutConfirmedByTheLock(t *testing.T) { |
| + defer shorten(&drainTakeBound, 50*time.Millisecond)() |
| + for _, tc := range []struct { |
| + owner string |
| + ok bool |
| + drain bool |
| + want string |
| + }{ |
| + {"b", true, false, "ok"}, |
| + {"b", true, true, "failed"}, |
| + {"z", true, false, "failed"}, |
| + {"", false, false, "failed"}, |
| + } { |
| + act, ed, marks := healthyDrain() |
| + ed.take = func(ctx context.Context, peer, host string) (string, int64, error) { |
| + <-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.owner = func(registry.Route) (string, int64, bool) { return tc.owner, 12, tc.ok } |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != tc.want { |
| + t.Fatalf("%+v: report %+v", tc, rep) |
| + } |
| + if tc.want == "ok" && (rep.Moved[0].Holder != "b" || rep.Moved[0].Gen != 12 || rep.Moved[0].Confirmed != "lock") { |
| + t.Fatalf("moved %+v", rep.Moved) |
| + } |
| + } |
| +} |
| + |
| +// A missing acknowledgement: re-asked every 5 s (shortened), failing at 2 |
| +// minutes (shortened), naming the box. No fence is wanted then. |
| +func TestDrainMissingAcknowledgement(t *testing.T) { |
| + defer shorten(&drainAckBound, 120*time.Millisecond)() |
| + defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + ed.ack = func(peer string) (bool, error) { |
| + if peer == "c" { |
| + return false, errors.New("dial refused") |
| + } |
| + return true, nil |
| + } |
| + 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]") { |
| + 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 _, err := d.start("t1", "move"); !errors.Is(err, errDrainStep) { |
| + t.Fatalf("move after a failed withdraw: %v", err) |
| + } |
| + // A drained acknowledgement missing fails the move step too, with |
| + // every redirect kept. |
| + act, ed, marks = healthyDrain() |
| + ed.ack = func(peer string) (bool, error) { |
| + return !(peer == "c" && marks.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) |
| + } |
| +} |
| + |
| +// The move step needs this transaction's fence, at its start and at its |
| +// report. |
| +func TestDrainMoveNeedsTheFence(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + var mu sync.Mutex |
| + f := fenceState{} |
| + d := newDrainDriver(act, ed, marks, func() fenceState { mu.Lock(); defer mu.Unlock(); return f }) |
| + if err := d.startWithdrawForTest("t1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.start("t1", "move"); !errors.Is(err, errDrainNoFence) { |
| + t.Fatalf("no fence: %v", err) |
| + } |
| + mu.Lock() |
| + f = fenceState{Present: true, Transaction: "other"} |
| + mu.Unlock() |
| + if _, err := d.start("t1", "move"); !errors.Is(err, errDrainNoFence) { |
| + t.Fatalf("another fence: %v", err) |
| + } |
| + mu.Lock() |
| + f = fenceState{Present: true, Transaction: "t1"} |
| + mu.Unlock() |
| + // The fence goes during the moves: the report fails. |
| + act.onBeginMove = func(string) { mu.Lock(); f = fenceState{}; mu.Unlock() } |
| + done, err := d.start("t1", "move") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + <-done |
| + if rep := d.snapshot(); rep.Result != "failed" || !strings.Contains(strings.Join(rep.Reasons, ";"), "fence") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// One transaction at a time; cancel of another transaction refuses. |
| +func TestDrainOneTransaction(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + if err := d.startWithdrawForTest("t1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := d.start("t2", "withdraw"); !errors.Is(err, errDrainOtherTxn) { |
| + t.Fatalf("t2: %v", err) |
| + } |
| + if err := d.cancel(context.Background(), "t2"); !errors.Is(err, errDrainOtherTxn) { |
| + t.Fatalf("cancel t2: %v", err) |
| + } |
| + 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()) |
| + } |
| + 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. |
| +func TestDrainHeldAfterMovesFails(t *testing.T) { |
| + 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() }() |
| + } |
| + return r, err |
| + } |
| + rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| + if rep.Result != "failed" || marks.drained != 0 { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// An agent restart between the report and the provider action: the |
| +// incarnation changes, the drain state and the report are gone, and a |
| +// move needs a new withdraw. (The fence on disk still blocks starts: |
| +// TestStartFenceRefusesStartsAcrossRestart.) |
| +func TestDrainAgentRestartVoidsTheReport(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + rep := runDrain(t, d, "t1") |
| + if rep.Result != "ok" { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + before := agentIncarnation |
| + defer func() { agentIncarnation = before }() |
| + agentIncarnation = newIncarnation() // the process restarted |
| + restarted := newDrainDriver(act, ed, &fakeMarks{}, fenceOf("t1")) |
| + s := restarted.status() |
| + if s.Incarnation == rep.Incarnation || s.Transaction != "" || s.Result != "none" || restarted.snapshot() != nil { |
| + t.Fatalf("after a restart: %+v (report incarnation %s)", s, rep.Incarnation) |
| + } |
| + if _, err := restarted.start("t1", "move"); !errors.Is(err, errDrainStep) { |
| + t.Fatalf("move on a restarted agent: %v", err) |
| + } |
| +} |
diff --git a/internal/host/hadrainfence.go b/internal/host/hadrainfence.go| new file mode 100644 |
| index 000000000..08679f32f |
| --- /dev/null |
| +++ b/internal/host/hadrainfence.go |
| @@ -0,0 +1,87 @@ |
| +package host |
| + |
| +// The retained start fence (region HA spec §25.15 R3.1, H5 amended). |
| +// group-maintenance drain installs it, bound to the drain transaction, |
| +// and only drain --cancel and fence-clear of the same transaction remove |
| +// it. While it is present the agent's tenant start gate refuses every |
| +// start. The agent reads it at start and at every start decision, so a |
| +// restarted agent is fenced too. |
| +// |
| +// Where it lives. The group-maintenance verbs own |
| +// /run/carlos-group-maintenance, but that directory is root's alone |
| +// (0700; tmpfiles, openMaintenanceDirectory, consumeGroupAction and |
| +// checkGroupMaintenanceDirectory all insist on it), and the agent runs as |
| +// carlos, so it could never read a fence there. The fence is therefore |
| +// its sibling, /run/carlos-group-fence, which the same verbs create and |
| +// own: root's, 0755, holding fence.json, root's, 0644. The agent can read |
| +// it and cannot write, rename or remove it (only root writes /run and the |
| +// directory). /run is a tmpfs, so a reboot clears the fence; that is |
| +// safe, because a terminated member never boots again and a roll |
| +// restarts only the edge (the box does not reboot). |
| +// |
| +// Reading fails closed: an absent directory or file is no fence; a fence |
| +// that is present but cannot be read, is not root's, is writable by |
| +// others or does not parse is a fence of an unknown transaction, which |
| +// refuses starts as any fence does and which only fence-clear by hand |
| +// (after the operator removes it) ends. |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "errors" |
| +) |
| + |
| +const ( |
| + groupFenceDir = "/run/carlos-group-fence" |
| + groupFenceFile = "fence.json" |
| + // groupFenceMax bounds the fence body read. |
| + groupFenceMax = 1024 |
| +) |
| + |
| +var ( |
| + errFenceOther = errors.New("another transaction's start fence is installed") |
| + errFenceInvalid = errors.New("the start fence is not valid") |
| +) |
| + |
| +// startFence is the fence file's body. |
| +type startFence struct { |
| + V int `json:"v"` |
| + Transaction string `json:"transaction"` |
| + At int64 `json:"at"` |
| +} |
| + |
| +// fenceState is one read of the fence: Present, and Transaction when it |
| +// parsed. Present with Err set is a fence that cannot be read or is not |
| +// valid: it fences all the same. |
| +type fenceState struct { |
| + Present bool |
| + Transaction string |
| + Err error |
| +} |
| + |
| +func decodeStartFence(b []byte) (startFence, error) { |
| + var f startFence |
| + if len(b) > groupFenceMax { |
| + return f, errFenceInvalid |
| + } |
| + d := json.NewDecoder(bytes.NewReader(b)) |
| + d.DisallowUnknownFields() |
| + if d.Decode(&f) != nil || d.More() || f.V != 1 || !groupTransactionID.MatchString(f.Transaction) { |
| + return startFence{}, errFenceInvalid |
| + } |
| + return f, nil |
| +} |
| + |
| +// groupStartFence is the fence the agent reads: the production path, |
| +// owned by root. Tests point it at a fixture with their own owner. |
| +var groupStartFence = fenceLocation{root: "/", dir: groupFenceDir, owner: 0} |
| + |
| +// fenceLocation names a fence directory, the root its ancestors are |
| +// opened from, and the owner it and its file must have. |
| +type fenceLocation struct { |
| + root, dir string |
| + owner int |
| +} |
| + |
| +// fenced is the agent's start-gate read: whether any fence is present. |
| +func (l fenceLocation) fenced() bool { return l.read().Present } |
diff --git a/internal/host/hadrainfence_linux.go b/internal/host/hadrainfence_linux.go| new file mode 100644 |
| index 000000000..10068befa |
| --- /dev/null |
| +++ b/internal/host/hadrainfence_linux.go |
| @@ -0,0 +1,226 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "crypto/rand" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// read is one read of the fence: the directory, then the file, both by |
| +// descriptor with no symlink followed. Absence of either is no fence; |
| +// anything else unexpected fences (fail closed). |
| +func (l fenceLocation) read() fenceState { |
| + fd, err := unix.Openat2(unix.AT_FDCWD, l.dir, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS}) |
| + if errors.Is(err, unix.ENOENT) { |
| + return fenceState{} |
| + } |
| + if err != nil { |
| + return fenceState{Present: true, Err: err} |
| + } |
| + defer unix.Close(fd) |
| + var st unix.Stat_t |
| + if unix.Fstat(fd, &st) != nil || int(st.Uid) != l.owner || st.Mode&0022 != 0 { |
| + return fenceState{Present: true, Err: errFenceInvalid} |
| + } |
| + leaf, err := unix.Openat2(fd, groupFenceFile, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_NONBLOCK | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH}) |
| + if errors.Is(err, unix.ENOENT) { |
| + return fenceState{} |
| + } |
| + if err != nil { |
| + return fenceState{Present: true, Err: err} |
| + } |
| + f := os.NewFile(uintptr(leaf), groupFenceFile) |
| + defer f.Close() |
| + if unix.Fstat(leaf, &st) != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || int(st.Uid) != l.owner || st.Mode&0022 != 0 || st.Nlink != 1 { |
| + return fenceState{Present: true, Err: errFenceInvalid} |
| + } |
| + b, err := io.ReadAll(io.LimitReader(f, groupFenceMax+1)) |
| + if err != nil { |
| + return fenceState{Present: true, Err: err} |
| + } |
| + p, err := decodeStartFence(b) |
| + if err != nil { |
| + return fenceState{Present: true, Err: err} |
| + } |
| + return fenceState{Present: true, Transaction: p.Transaction} |
| +} |
| + |
| +// openFenceDir opens the fence directory under the root's protected |
| +// ancestors (as openMaintenanceDirectory does), creating it 0755 when |
| +// create is set. Its owner must be l.owner and it must not be writable by |
| +// group or others. |
| +func (l fenceLocation) openDir(create bool) (*os.File, error) { |
| + rel, err := filepath.Rel(l.root, l.dir) |
| + if err != nil || !filepath.IsLocal(rel) || rel == "." { |
| + return nil, errGroupMaintenance |
| + } |
| + parent, err := openFenceParent(l.root, filepath.Dir(rel), l.owner) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer unix.Close(parent) |
| + name := filepath.Base(rel) |
| + how := &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH} |
| + fd, err := unix.Openat2(parent, name, how) |
| + if errors.Is(err, unix.ENOENT) && create { |
| + if err = unix.Mkdirat(parent, name, 0755); err != nil && !errors.Is(err, unix.EEXIST) { |
| + return nil, err |
| + } |
| + if err = unix.Fsync(parent); err != nil { |
| + return nil, err |
| + } |
| + fd, err = unix.Openat2(parent, name, how) |
| + if err == nil { |
| + // The umask may have taken bits away; the agent needs to |
| + // traverse and read. |
| + err = unix.Fchmod(fd, 0755) |
| + } |
| + } |
| + if err != nil { |
| + if fd > 0 { |
| + unix.Close(fd) |
| + } |
| + return nil, err |
| + } |
| + var st unix.Stat_t |
| + if unix.Fstat(fd, &st) != nil || int(st.Uid) != l.owner || st.Mode&0022 != 0 { |
| + unix.Close(fd) |
| + return nil, errGroupMaintenance |
| + } |
| + return os.NewFile(uintptr(fd), l.dir), nil |
| +} |
| + |
| +// openFenceParent opens rel under root by descriptor, each ancestor owned |
| +// by owner or root and not writable by group or others. |
| +func openFenceParent(root, rel string, owner int) (int, error) { |
| + fd, err := unix.Openat2(unix.AT_FDCWD, root, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS}) |
| + if err != nil { |
| + return -1, err |
| + } |
| + check := func(fd int) bool { |
| + var st unix.Stat_t |
| + return unix.Fstat(fd, &st) == nil && (int(st.Uid) == owner || st.Uid == 0) && st.Mode&0022 == 0 |
| + } |
| + if rel == "." { |
| + if !check(fd) { |
| + unix.Close(fd) |
| + return -1, errGroupMaintenance |
| + } |
| + return fd, nil |
| + } |
| + for _, part := range strings.Split(rel, string(filepath.Separator)) { |
| + if !check(fd) { |
| + unix.Close(fd) |
| + return -1, errGroupMaintenance |
| + } |
| + next, e := unix.Openat2(fd, part, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH}) |
| + unix.Close(fd) |
| + if e != nil { |
| + return -1, e |
| + } |
| + fd = next |
| + } |
| + if !check(fd) { |
| + unix.Close(fd) |
| + return -1, errGroupMaintenance |
| + } |
| + return fd, nil |
| +} |
| + |
| +// install writes the fence for txn: a fence of the same transaction is |
| +// kept as it is, and one of another transaction (or an invalid one) |
| +// refuses. The write is a new file renamed into place, fsynced. |
| +func (l fenceLocation) install(txn string, now time.Time) error { |
| + if !groupTransactionID.MatchString(txn) { |
| + return errGroupMaintenance |
| + } |
| + dir, err := l.openDir(true) |
| + if err != nil { |
| + return err |
| + } |
| + defer dir.Close() |
| + switch s := l.read(); { |
| + case s.Present && s.Err != nil: |
| + return errors.Join(errFenceInvalid, s.Err) |
| + case s.Present && s.Transaction != txn: |
| + return errFenceOther |
| + case s.Present: |
| + return nil |
| + } |
| + body, err := json.Marshal(startFence{V: 1, Transaction: txn, At: now.Unix()}) |
| + if err != nil { |
| + return err |
| + } |
| + var nonce [16]byte |
| + if _, err := rand.Read(nonce[:]); err != nil { |
| + return err |
| + } |
| + name := ".fence-" + hex.EncodeToString(nonce[:]) |
| + fd := int(dir.Fd()) |
| + leaf, err := unix.Openat2(fd, name, &unix.OpenHow{Flags: unix.O_WRONLY | unix.O_CREAT | unix.O_EXCL | unix.O_CLOEXEC, Mode: 0644, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH}) |
| + if err != nil { |
| + return err |
| + } |
| + defer unix.Unlinkat(fd, name, 0) |
| + f := os.NewFile(uintptr(leaf), name) |
| + defer f.Close() |
| + if err = f.Chmod(0644); err != nil { |
| + return err |
| + } |
| + if _, err = f.Write(body); err != nil { |
| + return err |
| + } |
| + if err = f.Sync(); err != nil { |
| + return err |
| + } |
| + if err = f.Close(); err != nil { |
| + return err |
| + } |
| + // RENAME_NOREPLACE: a fence another writer installed meanwhile stays. |
| + if err = unix.Renameat2(fd, name, fd, groupFenceFile, unix.RENAME_NOREPLACE); err != nil { |
| + if errors.Is(err, unix.EEXIST) { |
| + return errFenceOther |
| + } |
| + return err |
| + } |
| + return dir.Sync() |
| +} |
| + |
| +// remove removes the fence of txn. No fence is success; a fence of |
| +// another transaction refuses; an invalid fence refuses (the operator |
| +// removes it by hand). |
| +func (l fenceLocation) remove(txn string) error { |
| + if !groupTransactionID.MatchString(txn) { |
| + return errGroupMaintenance |
| + } |
| + dir, err := l.openDir(false) |
| + if errors.Is(err, unix.ENOENT) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + defer dir.Close() |
| + switch s := l.read(); { |
| + case !s.Present: |
| + return nil |
| + case s.Err != nil: |
| + return errors.Join(errFenceInvalid, s.Err) |
| + case s.Transaction != txn: |
| + return errFenceOther |
| + } |
| + if err := unix.Unlinkat(int(dir.Fd()), groupFenceFile, 0); err != nil && !errors.Is(err, unix.ENOENT) { |
| + return err |
| + } |
| + return dir.Sync() |
| +} |
diff --git a/internal/host/hadrainfence_linux_test.go b/internal/host/hadrainfence_linux_test.go| new file mode 100644 |
| index 000000000..d784a4871 |
| --- /dev/null |
| +++ b/internal/host/hadrainfence_linux_test.go |
| @@ -0,0 +1,386 @@ |
| +//go:build linux |
| + |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/groupadmission" |
| +) |
| + |
| +// testFence is a fence fixture owned by this test's user. |
| +func testFence(t *testing.T) fenceLocation { |
| + t.Helper() |
| + root := t.TempDir() |
| + if err := os.Chmod(root, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + return fenceLocation{root: root, dir: filepath.Join(root, "carlos-group-fence"), owner: os.Geteuid()} |
| +} |
| + |
| +func TestStartFenceInstallReadRemove(t *testing.T) { |
| + l := testFence(t) |
| + if s := l.read(); s.Present { |
| + t.Fatalf("no fence yet: %+v", s) |
| + } |
| + if err := l.remove("t1"); err != nil { |
| + t.Fatalf("removing no fence: %v", err) |
| + } |
| + if err := l.install("t1", time.Unix(100, 0)); err != nil { |
| + t.Fatal(err) |
| + } |
| + st, err := os.Stat(filepath.Join(l.dir, groupFenceFile)) |
| + if err != nil || st.Mode().Perm() != 0644 { |
| + t.Fatalf("fence file: %v %v, want 0644", st, err) |
| + } |
| + if dst, _ := os.Stat(l.dir); dst.Mode().Perm() != 0755 { |
| + t.Fatalf("fence dir mode %v, want 0755", dst.Mode().Perm()) |
| + } |
| + if s := l.read(); !s.Present || s.Err != nil || s.Transaction != "t1" { |
| + t.Fatalf("read: %+v", s) |
| + } |
| + if err := l.install("t1", time.Now()); err != nil { |
| + t.Fatalf("same transaction again: %v", err) |
| + } |
| + if err := l.install("t2", time.Now()); !errors.Is(err, errFenceOther) { |
| + t.Fatalf("another transaction's install: %v, want refused", err) |
| + } |
| + if err := l.remove("t2"); !errors.Is(err, errFenceOther) { |
| + t.Fatalf("another transaction's remove: %v, want refused", err) |
| + } |
| + if s := l.read(); s.Transaction != "t1" { |
| + t.Fatalf("a refused remove changed the fence: %+v", s) |
| + } |
| + if err := l.remove("../x"); err == nil { |
| + t.Fatal("a bad transaction id was accepted") |
| + } |
| + if err := l.remove("t1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := l.read(); s.Present { |
| + t.Fatalf("fence after remove: %+v", s) |
| + } |
| +} |
| + |
| +// Anything unexpected is a fence (fail closed): garbage, a symlink, a |
| +// file writable by others, two links. |
| +func TestStartFenceFailsClosed(t *testing.T) { |
| + for _, kind := range []string{"garbage", "unknown-field", "symlink", "group-writable", "hardlink", "dir-writable", "oversize"} { |
| + t.Run(kind, func(t *testing.T) { |
| + l := testFence(t) |
| + if err := l.install("t1", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + file := filepath.Join(l.dir, groupFenceFile) |
| + switch kind { |
| + case "garbage": |
| + must(t, os.WriteFile(file, []byte("{"), 0644)) |
| + case "unknown-field": |
| + must(t, os.WriteFile(file, []byte(`{"v":1,"transaction":"t1","at":1,"x":1}`), 0644)) |
| + case "oversize": |
| + must(t, os.WriteFile(file, []byte(`{"v":1,"transaction":"t1","at":1}`+strings.Repeat(" ", groupFenceMax)), 0644)) |
| + case "symlink": |
| + other := filepath.Join(t.TempDir(), "f") |
| + must(t, os.WriteFile(other, []byte(`{"v":1,"transaction":"t1","at":1}`), 0644)) |
| + must(t, os.Remove(file)) |
| + must(t, os.Symlink(other, file)) |
| + case "group-writable": |
| + must(t, os.Chmod(file, 0666)) |
| + case "hardlink": |
| + must(t, os.Link(file, filepath.Join(l.dir, "second"))) |
| + case "dir-writable": |
| + must(t, os.Chmod(l.dir, 0777)) |
| + } |
| + s := l.read() |
| + if !s.Present || s.Err == nil { |
| + t.Fatalf("%s: %+v, want a fence of unknown transaction", kind, s) |
| + } |
| + if err := l.remove("t1"); err == nil { |
| + t.Fatalf("%s: an invalid fence was removed", kind) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func must(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// The fence refuses every start, and a restarted agent (a new admission |
| +// over the same disk) is fenced too until the fence goes. |
| +func TestStartFenceRefusesStartsAcrossRestart(t *testing.T) { |
| + l := testFence(t) |
| + defer func(prev func() bool) { startFenced = prev }(startFenced) |
| + startFenced = l.fenced |
| + admit := func() *fixedAdmission { |
| + a := readyGroupAdmission(t) |
| + a.observe(groupadmission.Facts{TerminationStarted: true}) |
| + a.tick(t.Context()) |
| + return a |
| + } |
| + a := admit() |
| + if !a.startAllowed() { |
| + t.Fatal("an admitted member without a fence refuses starts") |
| + } |
| + must(t, l.install("t1", time.Now())) |
| + if a.startAllowed() || a.departureAllowed() { |
| + t.Fatal("a fenced member allows a start") |
| + } |
| + restarted := admit() |
| + if restarted.startAllowed() { |
| + t.Fatal("a restarted agent is not fenced") |
| + } |
| + must(t, l.remove("t1")) |
| + if !restarted.startAllowed() || !a.startAllowed() { |
| + t.Fatal("starts still refused after fence-clear") |
| + } |
| +} |
| + |
| +// The drain socket serves root only. |
| +func TestDrainSocketServesRootOnly(t *testing.T) { |
| + dir, err := os.MkdirTemp("", "hd") |
| + must(t, err) |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + path := filepath.Join(dir, "s", "drain.sock") |
| + d := newDrainDriver(&fakeDrainAct{}, &fakeDrainEdge{}, &fakeMarks{}, func() fenceState { return fenceState{} }) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + go func() { defer close(done); serveHADrainSocket(ctx, path, d) }() |
| + 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) |
| + } |
| + } |
| + defer func(prev func(uint32) bool) { drainPeerAllowed = prev }(drainPeerAllowed) |
| + drainPeerAllowed = 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) |
| + } |
| + // An unknown path, a query, a bad body: refused, nothing started. |
| + for _, req := range []struct{ method, path, body string }{ |
| + {"POST", "/v1/drain/stop", `{"transaction":"t1"}`}, |
| + {"GET", "/v1/drain/status?x=1", ""}, |
| + {"POST", "/v1/drain/withdraw", `{"transaction":"../x"}`}, |
| + {"POST", "/v1/drain/withdraw", `{"transaction":"t1","extra":1}`}, |
| + } { |
| + r, _ := http.NewRequest(req.method, "http://agent"+req.path, strings.NewReader(req.body)) |
| + resp, err := c.c.Do(r) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode == http.StatusOK { |
| + t.Fatalf("%s %s answered 200", req.method, req.path) |
| + } |
| + } |
| + if d.status().Transaction != "" { |
| + t.Fatal("a refused ask started a drain") |
| + } |
| +} |
| + |
| +func waitSocket(t *testing.T, path string) { |
| + t.Helper() |
| + for i := 0; i < 200; i++ { |
| + if c, err := net.Dial("unix", path); err == nil { |
| + c.Close() |
| + return |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + t.Fatal("the socket never listened") |
| +} |
| + |
| +// verbDrain is the verbs' fixture with a fence and a drain socket served |
| +// by d. |
| +func verbDrain(t *testing.T, d *drainDriver) (*groupMaintenanceCommand, fenceLocation) { |
| + t.Helper() |
| + _, _, cmd := maintenanceVerbFixture(t) |
| + l := fenceLocation{root: cmd.root, dir: filepath.Join(cmd.root, "carlos-group-fence"), owner: os.Geteuid()} |
| + cmd.fence = &l |
| + dir, err := os.MkdirTemp("", "hv") |
| + 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 } |
| + if d != nil { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + go func() { defer close(done); serveHADrainSocket(ctx, path, d) }() |
| + t.Cleanup(func() { cancel(); <-done }) |
| + waitSocket(t, path) |
| + } |
| + cmd.drain = newDrainClient(path) |
| + cmd.txn = "" |
| + return cmd, l |
| +} |
| + |
| +func runDrainVerb(t *testing.T, cmd *groupMaintenanceCommand, verb, txn string) (*drainReport, error) { |
| + t.Helper() |
| + cmd.txn = txn |
| + out, err := runMaintenanceVerb(cmd, verb, nil) |
| + if len(out) == 0 { |
| + return nil, err |
| + } |
| + var rep drainReport |
| + if jerr := json.Unmarshal(out, &rep); jerr != nil { |
| + t.Fatalf("report %q: %v", out, jerr) |
| + } |
| + return &rep, err |
| +} |
| + |
| +// drain: withdraw, then the fence, then the move; the report printed; the |
| +// fence stays. drain --cancel and fence-clear refuse a wrong transaction. |
| +func TestDrainVerbFenceAndCancel(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + var d *drainDriver |
| + var fenceAtMove fenceState |
| + act.onBeginMove = func(string) { |
| + fenceAtMove = d.fence() |
| + } |
| + d = newDrainDriver(act, ed, marks, nil) |
| + cmd, l := verbDrain(t, d) |
| + d.fence = l.read |
| + // Another transaction's fence refuses before anything is asked. |
| + must(t, l.install("other", time.Now())) |
| + if _, err := runDrainVerb(t, cmd, "drain", "t1"); !errors.Is(err, errFenceOther) { |
| + t.Fatalf("drain over another fence: %v", err) |
| + } |
| + if marks.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) { |
| + t.Fatalf("fence-clear of the wrong transaction: %v", err) |
| + } |
| + if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); !errors.Is(err, errFenceOther) { |
| + t.Fatalf("cancel of the wrong transaction: %v", err) |
| + } |
| + if _, err := runDrainVerb(t, cmd, "fence-clear", "other"); err != nil { |
| + t.Fatal(err) |
| + } |
| + rep, err := runDrainVerb(t, cmd, "drain", "t1") |
| + if err != nil || rep == nil || rep.Result != "ok" || rep.Fence != "t1" || rep.Incarnation != agentIncarnation { |
| + t.Fatalf("drain: %+v %v", rep, err) |
| + } |
| + if fenceAtMove.Transaction != "t1" { |
| + t.Fatalf("the fence at the first move: %+v, want t1's", fenceAtMove) |
| + } |
| + if s := l.read(); s.Transaction != "t1" { |
| + t.Fatalf("the fence after the drain: %+v", s) |
| + } |
| + // Status shows the fence, the drain and the incarnation. |
| + out, err := runMaintenanceVerb(cmd, "status", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var st groupMaintenanceStatus |
| + must(t, json.Unmarshal(out, &st)) |
| + if st.Fence.State != "present" || *st.Fence.Transaction != "t1" || st.Drain.State != "known" || *st.Drain.Incarnation != agentIncarnation || *st.Drain.Result != "ok" || *st.Drain.Transaction != "t1" { |
| + t.Fatalf("status: %s", out) |
| + } |
| + // A wrong transaction's cancel is refused by the fence and by the agent. |
| + if _, err := runDrainVerb(t, cmd, "drain-cancel", "t2"); !errors.Is(err, errFenceOther) { |
| + t.Fatalf("cancel t2: %v", err) |
| + } |
| + must(t, d.cancel(context.Background(), "t1")) // the agent forgot t1... |
| + must(t, d.startWithdrawForTest("t3")) // ...and now drains t3 |
| + if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); err == nil || !strings.Contains(err.Error(), errDrainOtherTxn.Error()) { |
| + t.Fatalf("cancel of t1 while the agent drains t3: %v", err) |
| + } |
| + if s := l.read(); s.Transaction != "t1" { |
| + t.Fatal("a refused cancel removed the fence") |
| + } |
| + must(t, d.cancel(context.Background(), "t3")) |
| + 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) |
| + } |
| +} |
| + |
| +// drain --cancel with no agent running removes the fence (no agent holds |
| +// drain state); fence-clear needs no agent at all. |
| +func TestDrainCancelWithoutAgent(t *testing.T) { |
| + cmd, l := verbDrain(t, nil) |
| + must(t, l.install("t1", time.Now())) |
| + if _, err := runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if l.read().Present { |
| + t.Fatal("fence left") |
| + } |
| + must(t, l.install("t1", time.Now())) |
| + if _, err := runDrainVerb(t, cmd, "fence-clear", "t1"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if l.read().Present { |
| + t.Fatal("fence left") |
| + } |
| + // A drain with no agent fails before installing a fence. |
| + if _, err := runDrainVerb(t, cmd, "drain", "t1"); err == nil || l.read().Present { |
| + t.Fatalf("drain with no agent: %v, fence %+v", err, l.read()) |
| + } |
| +} |
| + |
| +// A failed withdraw installs no fence; a failed move keeps it. |
| +func TestDrainVerbFailures(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + ed.ack = func(string) (bool, error) { return false, nil } |
| + defer shorten(&drainAckBound, 50*time.Millisecond)() |
| + defer shorten(&drainAckEvery, 10*time.Millisecond)() |
| + d := newDrainDriver(act, ed, marks, nil) |
| + cmd, l := verbDrain(t, d) |
| + d.fence = l.read |
| + rep, err := runDrainVerb(t, cmd, "drain", "t1") |
| + if !errors.Is(err, errDrainFailed) || rep.Result != "failed" || rep.Step != "withdraw" || l.read().Present { |
| + t.Fatalf("withdraw failure: %+v %v fence %+v", rep, err, l.read()) |
| + } |
| + ed.ack = nil |
| + ed.takeErr = errors.New("boom") |
| + rep, err = runDrainVerb(t, cmd, "drain", "t1") |
| + if !errors.Is(err, errDrainFailed) || rep.Result != "failed" || rep.Step != "move" || l.read().Transaction != "t1" { |
| + t.Fatalf("move failure: %+v %v fence %+v", rep, err, l.read()) |
| + } |
| +} |
| + |
| +func TestDrainVerbArguments(t *testing.T) { |
| + for _, tc := range []struct { |
| + args []string |
| + verb, txn string |
| + shouldFail bool |
| + }{ |
| + {[]string{"drain", "t1"}, "drain", "t1", false}, |
| + {[]string{"drain", "--cancel", "t1"}, "drain-cancel", "t1", false}, |
| + {[]string{"fence-clear", "t1"}, "fence-clear", "t1", false}, |
| + {[]string{"drain"}, "", "", true}, |
| + {[]string{"drain", "../x"}, "", "", true}, |
| + {[]string{"drain", "--cancel"}, "", "", true}, |
| + {[]string{"drain-cancel", "t1"}, "", "", true}, |
| + {[]string{"fence-clear"}, "", "", true}, |
| + {[]string{"drain", "t1", "extra"}, "", "", true}, |
| + {[]string{"fence-clear", "-x"}, "", "", true}, |
| + } { |
| + verb, txn, err := maintenanceArguments(tc.args) |
| + if (err != nil) != tc.shouldFail || verb != tc.verb || txn != tc.txn { |
| + t.Fatalf("%v: %q %q %v", tc.args, verb, txn, err) |
| + } |
| + } |
| +} |
diff --git a/internal/host/hadrainfence_other.go b/internal/host/hadrainfence_other.go| new file mode 100644 |
| index 000000000..91a27dca2 |
| --- /dev/null |
| +++ b/internal/host/hadrainfence_other.go |
| @@ -0,0 +1,11 @@ |
| +//go:build !linux |
| + |
| +package host |
| + |
| +import "time" |
| + |
| +// The fence is Linux-only, as the group-maintenance verbs are. Elsewhere |
| +// no fence can be installed, and none is read. |
| +func (l fenceLocation) read() fenceState { return fenceState{} } |
| +func (l fenceLocation) install(string, time.Time) error { return errSystemUnsupported } |
| +func (l fenceLocation) remove(string) error { return errSystemUnsupported } |