region HA: the verb's floor listing is the drain's ack population
Astra r2 F2.1: the member's DrainAckPeers trusted its last-good fold (read/departureComplete) as a complete population, so after a failed LIST, all GETs failing or no poll since a box published, the drain could skip a box the floor counted. Ruling 8a3d302: one population, read once, by the party that decides. - The verb passes the floor row's counted boxes, the member excluded, as drain --peers=a,b,... (grouproll drainPeers, RemoteCommand); root validates it (maintenanceArguments), hands it to the __drain-call child as the same flag (drainCallArgs), which posts it as "peers" on the agent socket (handler, validDrainPeers). At most 256 refs in the edges-key grammar, no duplicates; an empty list means the floor counted no other box. - The agent refuses withdraw or move without a valid list before anything runs (errDrainNoPeers). publishAndAck asks every listed box plus any its fold adds, re-read each round; the fold never removes one and its completeness flags are no longer read. - AskDrainSeen reads the fold once when a listed box has no file in it, so a box that published after the last poll can answer; otherwise the ask fails naming it. - The SSM operator document's drain pattern gains --peers=.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
infra/modules/region-group-operator-document/README.md+1 −1infra/modules/region-group-operator-document/tool-pattern.txt+1 −1internal/edge/hadrain.go+17 −1internal/edge/hadrain_test.go+67 −5internal/edge/hadrainconns.go+13 −24internal/edge/hadrainconns_test.go+9 −22internal/grouproll/box.go+31 −1internal/grouproll/box_test.go+61 −7internal/grouproll/depart.go+35 −2internal/grouproll/depart_test.go+21 −0internal/grouproll/engine.go+7 −0internal/grouproll/fake_test.go+7 −0internal/grouproll/text.go+1 −0internal/grouproll/text_test.go+5 −5internal/host/group_maintenance_drain.go+4 −4internal/host/group_maintenance_verbs.go+22 −5internal/host/hadrain.go+43 −26internal/host/hadrain_call.go+85 −16internal/host/hadrain_call_linux.go+5 −5internal/host/hadrain_call_linux_test.go+29 −13internal/host/hadrain_call_other.go+1 −1internal/host/hadrain_socket.go+24 −8internal/host/hadrain_test.go+96 −53internal/host/hadrainfence_linux_test.go+35 −0
Intent
<paseo-system version="1" kind="agent-message" source-agent-id="c8d659b6-a1e8-48ce-91e3-377b461b8114" message-id="4dadf044-71b2-48cd-9e0b-ad9cd493adb0"> From 81058f97 (#802 author), on the red main / TestDrainReleaseSnapshotEarlyRefusalReleasesTheWAL: - Cannot reproduce locally at 63706d9c: full lease package 3/3, the test 90/90 under 6-way parallel load, 20/20 pinned to one starved CPU, 10/10 with -race. - My 3a8eabde change only swaps the store's and DB's slog loggers for the same loggers held to WARN (internal/lease/quietlog.go, called once in newStore after NewStore). No fds, goroutines or locks. I can't see a path from that to the snapshot goroutine keeping app.db-wal open; the only effect I can think of is timing (no synchronous INFO writes to stderr). - CI log shows the process stalled just before the failure ("this process did not run for 1.503s (pause limit 400ms)") against the test's 2 s wall-clock deadline. - Decisive A/B running now: branch lease-quietlog-ab = main 63706d9c minus quietStoreLogs only (unit LOG_LEVEL=warn kept). If it goes green twice I'll propose merging it to unblock v0.34.40 and look at the cause separately; if it fails, it's not my change. Will report here. </paseo-system>
<task-notification> <task-id>b59ge2udn</task-id> <tool-use-id>toolu_012R1FpnDnsJ3s1bWstqNHdd</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/b59ge2udn.output</output-file> <status>completed</status> <summary>Background command "Tell the #802 owner it is not their change" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>baaanf0qm</task-id> <tool-use-id>toolu_01PkZf1rQnCSPPMVM8GDJsaU</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/baaanf0qm.output</output-file> <status>completed</status> <summary>Background command "Astra round 2 on held-floor-capability" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bbbuvjpg0</task-id> <tool-use-id>toolu_014HxfWC7ALBdJa5uCyugkFE</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a99cbe46-f458-4f72-8b8a-294aae9cdf21/tasks/bbbuvjpg0.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on the WAL fix" completed (exit code 0)</summary> </task-notification>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="55d4ef81-ceea-4ef7-a4a7-2208930d4077"> Agent manager 8a3d302: (3), the invariant: one population, read once, by the party that decides. The verb's fresh LIST at transaction time is the ack list, carried in the signed transaction request; the member must get a signed answer from every box on it (plus anything newer in its own fold), failing closed otherwise; no last-good map is authority. State the residual (a brand-new box publishing during the drain window) in the spec with why it's bounded (members can't serve before admission; new fixed boxes are operator-added). R3 is the LAST round. If it finds this family again, stop: I'll take the step-back route, not a fourth fix. No merge before R3 is clean. </paseo-system>
diff --git a/infra/modules/region-group-operator-document/README.md b/infra/modules/region-group-operator-document/README.md| index 3e0829112..0483cf6cb 100644 |
| --- a/infra/modules/region-group-operator-document/README.md |
| +++ b/infra/modules/region-group-operator-document/README.md |
| @@ -59,7 +59,7 @@ printf %s B64 | base64 -d | /opt/carlos/carlos system group-maintenance permit & |
| /opt/carlos/carlos system group-maintenance revoke |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance apply |
| /usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance rollback |
| -/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain TX |
| +/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain --peers=PEERS TX |
| /usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel TX && /opt/carlos/carlos system group-maintenance status |
| /opt/carlos/carlos system group-maintenance fence-clear TX && /opt/carlos/carlos system group-maintenance status |
| /usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge.service |
diff --git a/infra/modules/region-group-operator-document/tool-pattern.txt b/infra/modules/region-group-operator-document/tool-pattern.txt| index cfbd1c7b1..7d9224b5d 100644 |
| --- a/infra/modules/region-group-operator-document/tool-pattern.txt |
| +++ b/infra/modules/region-group-operator-document/tool-pattern.txt |
| @@ -1 +1 @@ |
| -/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback)|/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain [A-Za-z0-9_][A-Za-z0-9_-]{0,79}|/usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/opt/carlos/carlos system group-maintenance fence-clear [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge\.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge\.service)\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
| +/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback)|/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain --peers=[A-Za-z0-9._,-]* [A-Za-z0-9_][A-Za-z0-9_-]{0,79}|/usr/bin/timeout --signal=TERM --kill-after=30s 300s /opt/carlos/carlos system group-maintenance drain --cancel [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/opt/carlos/carlos system group-maintenance fence-clear [A-Za-z0-9_][A-Za-z0-9_-]{0,79} && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=10s 120s /usr/bin/systemctl stop carlos-edge\.service; /usr/bin/systemctl show --property=MainPID --property=ActiveState carlos-edge\.service)\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
diff --git a/internal/edge/hadrain.go b/internal/edge/hadrain.go| index 68f855b46..662644f10 100644 |
| --- a/internal/edge/hadrain.go |
| +++ b/internal/edge/hadrain.go |
| @@ -525,6 +525,19 @@ func (e *Edge) AskDrainSeen(ctx context.Context, peer, txn, phase string, id uin |
| return false, errors.New("ha-drain: no mesh key to sign with") |
| } |
| dial, host, err := m.controlTarget(peer, e.certs.Load()) |
| + if errors.Is(err, errNoControlFile) { |
| + // A box on the verb's list that this fold has not read yet (it |
| + // published after the last poll, or polls have failed): read the |
| + // fold once now, as a receiver does for an ask, then try again. |
| + // Still absent, or unreadable, the ask fails and names the box. |
| + rctx, rcancel := context.WithTimeout(ctx, haDrainRefreshTimeout) |
| + rerr := m.refreshHostsNow(rctx) |
| + rcancel() |
| + if rerr != nil { |
| + return false, fmt.Errorf("%w (fold read: %v)", err, rerr) |
| + } |
| + dial, host, err = m.controlTarget(peer, e.certs.Load()) |
| + } |
| if err != nil { |
| return false, err |
| } |
| @@ -572,6 +585,9 @@ func (e *Edge) AskDrainSeen(ctx context.Context, peer, txn, phase string, id uin |
| return *ans.Seen, nil |
| } |
| +// errNoControlFile is a peer with no edges file in this edge's fold. |
| +var errNoControlFile = errors.New("ha-drain: no edges file") |
| + |
| // controlTarget is where a control request to peer goes: its dial address, |
| // by the same rule a hop uses, and a name to ask for. Every edge serves |
| // every mirrored certificate (certsync.go), and a group member may publish |
| @@ -586,7 +602,7 @@ func (m *homeMap) controlTarget(peer string, certs *certMirror) (dial, host stri |
| snap := m.snapshot() |
| f, ok := snap.files[edgesPrefix+peer+".json"] |
| if !ok || f.Box != peer { |
| - return "", "", fmt.Errorf("ha-drain: no edges file for %s", peer) |
| + return "", "", fmt.Errorf("%w for %s", errNoControlFile, peer) |
| } |
| own, ownKnown := snap.files[edgesPrefix+m.self+".json"] |
| ownKnown = ownKnown && own.Box == m.self |
diff --git a/internal/edge/hadrain_test.go b/internal/edge/hadrain_test.go| index de77f083f..efec042a7 100644 |
| --- a/internal/edge/hadrain_test.go |
| +++ b/internal/edge/hadrain_test.go |
| @@ -35,6 +35,8 @@ type drainStore struct { |
| lists int |
| gets int |
| fail bool |
| + // failList and failGet fail only that half. |
| + failList, failGet bool |
| } |
| func (d *drainStore) List(ctx context.Context, prefix string) ([]string, error) { |
| @@ -42,7 +44,7 @@ func (d *drainStore) List(ctx context.Context, prefix string) ([]string, error) |
| defer d.mu.Unlock() |
| if prefix == edgesPrefix { |
| d.lists++ |
| - if d.fail { |
| + if d.fail || d.failList { |
| return nil, errors.New("SlowDown: please reduce your request rate") |
| } |
| } |
| @@ -53,7 +55,7 @@ func (d *drainStore) Get(ctx context.Context, key string) ([]byte, string, error |
| d.mu.Lock() |
| if strings.HasPrefix(key, edgesPrefix) { |
| d.gets++ |
| - if d.fail { |
| + if d.fail || d.failGet { |
| d.mu.Unlock() |
| return nil, "", errors.New("SlowDown: please reduce your request rate") |
| } |
| @@ -820,9 +822,8 @@ func TestHADrainAckEveryFiledBox(t *testing.T) { |
| t.Fatalf("the rolled-back box's stored file lost the capability: %s %v", stored, err) |
| } |
| - peers, err := a.edge().DrainAckPeers() |
| - if want := []string{"gone", "olden", "quiet"}; err != nil || !slices.Equal(peers, want) { |
| - t.Fatalf("peers %v, %v; want %v", peers, err, want) |
| + if peers, want := a.edge().DrainAckPeers(), []string{"gone", "olden", "quiet"}; !slices.Equal(peers, want) { |
| + t.Fatalf("peers %v; want %v", peers, want) |
| } |
| s.file(t, a, drainGen0.Add(time.Minute), draining1) |
| if seen, err := askDrain1(a, "quiet"); err != nil || !seen { |
| @@ -902,3 +903,64 @@ func TestHADrainAnswerMustBeSignedForTheAsk(t *testing.T) { |
| t.Fatalf("a replayed answer: seen=%v err=%v, want refused", seen, err) |
| } |
| } |
| + |
| +// Astra r2 F2.1: the member's fold is a last-good map. After a failed |
| +// LIST, a LIST whose every GET fails, or with no poll since olden first |
| +// published, the fold does not hold olden. So the fold cannot be the |
| +// population: the verb's list is, and the member asks every box on it. An |
| +// ask for a box the fold lacks reads the fold once; if olden still cannot |
| +// be read, the ask fails naming it. Once the store answers again, within |
| +// the same bound, olden is read and answers (the recovery case). |
| +func TestHADrainAckListedBoxTheFoldLacks(t *testing.T) { |
| + for _, tc := range []string{"failed LIST", "every GET fails", "no poll since"} { |
| + t.Run(tc, func(t *testing.T) { |
| + s := newDrainScene(t) |
| + a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "eu-west-1") |
| + olden := s.add(t, "olden", "127.0.0.12", "blog.example.com", "eu-west-1") |
| + s.file(t, a, drainGen0, notDrain) |
| + // annie's fold is read before olden publishes. |
| + if err := a.be.mirror.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + refreshHomeMap(t, a.be.homes) |
| + s.file(t, olden, drainGen0, notDrain) |
| + if err := olden.be.mirror.Refresh(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + refreshHomeMap(t, olden.be.homes) |
| + s.key, _ = a.be.homes.meshKeys() |
| + s.file(t, a, drainGen0.Add(time.Minute), draining1) |
| + switch tc { |
| + case "failed LIST": |
| + a.store.mu.Lock() |
| + a.store.failList = true |
| + a.store.mu.Unlock() |
| + case "every GET fails": |
| + a.store.mu.Lock() |
| + a.store.failGet = true |
| + a.store.mu.Unlock() |
| + } |
| + if tc != "no poll since" { |
| + // A poll runs and fails: the fold keeps its last-good map. |
| + if err := a.be.homes.Refresh(context.Background()); err == nil { |
| + t.Fatal("the failing poll succeeded") |
| + } |
| + } |
| + if slices.Contains(a.edge().DrainAckPeers(), "olden") { |
| + t.Fatal("the fold already holds olden: the case is vacuous") |
| + } |
| + if tc != "no poll since" { |
| + if seen, err := askDrain1(a, "olden"); err == nil || seen || !strings.Contains(err.Error(), "olden") { |
| + t.Fatalf("a listed box the fold cannot read: seen=%v err=%v, want a failed ask naming it", seen, err) |
| + } |
| + a.store.mu.Lock() |
| + a.store.failList, a.store.failGet = false, false |
| + a.store.mu.Unlock() |
| + } |
| + // The ask reads the fold once and olden answers. |
| + if seen, err := askDrain1(a, "olden"); err != nil || !seen { |
| + t.Fatalf("recovery: seen=%v err=%v", seen, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/edge/hadrainconns.go b/internal/edge/hadrainconns.go| index ec36059a1..e290c3681 100644 |
| --- a/internal/edge/hadrainconns.go |
| +++ b/internal/edge/hadrainconns.go |
| @@ -20,33 +20,22 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| -// DrainAckPeers is every other box of the deployment with an edges file in |
| -// this edge's fold, whatever the file's age: fixed boxes, group members |
| -// and boxes of other regions alike, since every box folds the whole |
| -// deployment and so views this box's region (§25.4 step 1). The file is a |
| -// hint, not proof (held floor capability ruling, 2026-11-10): a box that |
| -// publishes only on change may be hours quiet and still forward, and a |
| -// rolled-back binary leaves the newer binary's file in place. Only a live |
| -// acknowledgement proves a box holds requests, so a stale file's box is |
| -// asked like any other, and one that cannot answer (an old binary, a dead |
| -// box's leftover file) fails the drain by name. |
| -// |
| -// A peer is named by its file's key, so a file whose box field differs |
| -// from its key is asked by its key and its ask fails (controlTarget). An |
| -// error, and no peers, when the fold has not been read in full: a key the |
| -// last poll could not read or parse may be a box that must answer. Memory |
| -// only. Sorted. |
| -func (e *Edge) DrainAckPeers() ([]string, error) { |
| +// DrainAckPeers is every other box with an edges file in this edge's fold, |
| +// by its key, whatever the file's age. It only ADDS to a drain's |
| +// acknowledgement population: the population is the verb's list, read once |
| +// from its own listing of control/edges/ and carried in the drain request |
| +// (§25.4 step 1; held floor capability ruling, 2026-11-10). The fold is a |
| +// last-good routing map, so its completeness is never evidence: a failed |
| +// LIST, unreadable files or a poll not yet run leave it as it was. A box |
| +// the fold adds (one that published after the verb's listing) is asked |
| +// like any other. Memory only. Sorted. |
| +func (e *Edge) DrainAckPeers() []string { |
| m := e.homes.Load() |
| if m == nil { |
| - return nil, errors.New("ha-drain: this edge has no home map") |
| - } |
| - snap := m.snapshot() |
| - if !snap.read || !snap.departureComplete { |
| - return nil, errors.New("ha-drain: the edges files have not all been read") |
| + return nil |
| } |
| var out []string |
| - for key := range snap.files { |
| + for key := range m.snapshot().files { |
| box := strings.TrimSuffix(strings.TrimPrefix(key, edgesPrefix), ".json") |
| if box == "" || box == m.self { |
| continue |
| @@ -54,7 +43,7 @@ func (e *Edge) DrainAckPeers() ([]string, error) { |
| out = append(out, box) |
| } |
| slices.Sort(out) |
| - return out, nil |
| + return out |
| } |
| // DrainSnapshot is the wake snapshot a move chooses its successor from |
diff --git a/internal/edge/hadrainconns_test.go b/internal/edge/hadrainconns_test.go| index 1de5aaab7..831810156 100644 |
| --- a/internal/edge/hadrainconns_test.go |
| +++ b/internal/edge/hadrainconns_test.go |
| @@ -39,11 +39,10 @@ func ackMap(t *testing.T, files ...map[string]any) *homeMap { |
| return m |
| } |
| -// The drain asks every other box with an edges file, whatever its region, |
| -// kind or the file's age (held floor capability ruling, 2026-11-10): the |
| -// file is a hint and only a live answer proves the box runs a binary that |
| -// holds requests. A quiet box publishes hours apart, and a stale file may |
| -// be a rolled-back or dead box, which must fail the drain, not be skipped. |
| +// The fold adds every other box with an edges file, whatever its region, |
| +// kind or the file's age, named by its key. It is never proof of a |
| +// complete population (held floor capability ruling, 2026-11-10): that is |
| +// the verb's list, so its flags are not read here. |
| func TestDrainAckPeersAreEveryFiledBox(t *testing.T) { |
| now := time.Now().UTC() |
| fresh, stale := now.Format(time.RFC3339), now.Add(-6*time.Hour).Format(time.RFC3339) |
| @@ -58,26 +57,14 @@ func TestDrainAckPeersAreEveryFiledBox(t *testing.T) { |
| // ask fails (controlTarget) and the drain names it. |
| map[string]any{"v": 1, "box": "other", "key": edgesPrefix + "misfiled.json", "generation": fresh}, |
| ) |
| + m.snap.departureComplete = false // not read: the fold only adds |
| e := &Edge{} |
| e.homes.Store(m) |
| - got, err := e.DrainAckPeers() |
| - if want := []string{"b", "dead", "far", "g-0123456789abcdef0123", "misfiled", "nogen"}; err != nil || !slices.Equal(got, want) { |
| - t.Fatalf("peers %v, %v; want %v", got, err, want) |
| + if got, want := e.DrainAckPeers(), []string{"b", "dead", "far", "g-0123456789abcdef0123", "misfiled", "nogen"}; !slices.Equal(got, want) { |
| + t.Fatalf("peers %v, want %v", got, want) |
| } |
| - // No fold, or a fold not read in full, is no answer: a file the poll |
| - // could not parse could be a box that must acknowledge. |
| - if p, err := (&Edge{}).DrainAckPeers(); err == nil || p != nil { |
| - t.Fatalf("peers without a fold: %v, %v", p, err) |
| - } |
| - unread := newHomeMap(nil, "self") |
| - e.homes.Store(unread) |
| - if p, err := e.DrainAckPeers(); err == nil || p != nil { |
| - t.Fatalf("peers from an unread fold: %v, %v", p, err) |
| - } |
| - m.snap.departureComplete = false |
| - e.homes.Store(m) |
| - if p, err := e.DrainAckPeers(); err == nil || p != nil { |
| - t.Fatalf("peers from a partial fold: %v, %v", p, err) |
| + if p := (&Edge{}).DrainAckPeers(); p != nil { |
| + t.Fatalf("peers without a fold: %v", p) |
| } |
| } |
diff --git a/internal/grouproll/box.go b/internal/grouproll/box.go| index d543a4cc3..8da092302 100644 |
| --- a/internal/grouproll/box.go |
| +++ b/internal/grouproll/box.go |
| @@ -49,6 +49,32 @@ type BoxArgs struct { |
| SHA256 string |
| Transaction string |
| Permit map[string]any |
| + // Peers is drain's acknowledgement population (region HA §25.4 step |
| + // 1): every box the floor counted, the member excluded, read once by |
| + // the verb. drain refuses nil; an empty list is a floor that counted |
| + // no other box. |
| + Peers []string |
| +} |
| + |
| +// MaxDrainPeers bounds the boxes one drain request names (the member's |
| +// drain socket and the session command carry the list whole). |
| +const MaxDrainPeers = 256 |
| + |
| +// drainPeersArg is drain's --peers argument for peers: references in the |
| +// edges-key grammar, comma separated, no duplicates, at most |
| +// MaxDrainPeers. Every character is shell-safe. ok is false otherwise. |
| +func drainPeersArg(peers []string) (string, bool) { |
| + if peers == nil || len(peers) > MaxDrainPeers { |
| + return "", false |
| + } |
| + seen := map[string]bool{} |
| + for _, p := range peers { |
| + if !boxRef.MatchString(p) || seen[p] { |
| + return "", false |
| + } |
| + seen[p] = true |
| + } |
| + return "--peers=" + strings.Join(peers, ","), true |
| } |
| // Box runs one maintenance verb on a member. Run reports each Session |
| @@ -109,7 +135,11 @@ func RemoteCommand(verb string, a BoxArgs, nonce string) (string, error) { |
| command = fmt.Sprintf("/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s system group-maintenance "+ |
| "drain --cancel %s && %s system group-maintenance status", CancelBound, carlosBinary, tx, carlosBinary) |
| case "drain": |
| - command = fmt.Sprintf("/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s %s", DrainBound, command, tx) |
| + peers, ok := drainPeersArg(a.Peers) |
| + if !ok { |
| + return "", Refusal{Key: "record"} |
| + } |
| + command = fmt.Sprintf("/usr/bin/timeout --signal=TERM --kill-after=30s %ds %s %s %s", DrainBound, command, peers, tx) |
| default: |
| command += " " + tx + status |
| } |
diff --git a/internal/grouproll/box_test.go b/internal/grouproll/box_test.go| index 818b1f75f..735ca714a 100644 |
| --- a/internal/grouproll/box_test.go |
| +++ b/internal/grouproll/box_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "os" |
| "reflect" |
| "regexp" |
| + "slices" |
| "strings" |
| "testing" |
| ) |
| @@ -89,17 +90,30 @@ func goldenArgs(t *testing.T, raw json.RawMessage) BoxArgs { |
| return a |
| } |
| +// goldenDrain is the one deliberate divergence from the script's drain |
| +// command (held floor capability ruling, 2026-11-10): the verb always names |
| +// the acknowledgement population, so the script's drain rows run with an |
| +// empty list and gain "--peers= " before the transaction. |
| +func goldenDrain(verb string, a BoxArgs, command string) (BoxArgs, string) { |
| + if verb != "drain" { |
| + return a, command |
| + } |
| + a.Peers = []string{} |
| + return a, strings.Replace(command, " drain "+a.Transaction+")", " drain --peers= "+a.Transaction+")", 1) |
| +} |
| + |
| func TestRemoteCommandGolden(t *testing.T) { |
| g := loadBoxGolden(t) |
| verbs := map[string]bool{} |
| for _, c := range g.RemoteCommands { |
| t.Run(c.Name, func(t *testing.T) { |
| - got, err := RemoteCommand(c.Verb, goldenArgs(t, c.Args), c.Nonce) |
| + a, want := goldenDrain(c.Verb, goldenArgs(t, c.Args), c.Command) |
| + got, err := RemoteCommand(c.Verb, a, c.Nonce) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if got != c.Command { |
| - t.Fatalf("command differs from the script's\n got: %s\nwant: %s", got, c.Command) |
| + if got != want { |
| + t.Fatalf("command differs from the script's\n got: %s\nwant: %s", got, want) |
| } |
| }) |
| verbs[c.Verb] = true |
| @@ -181,7 +195,8 @@ func TestRemoteCommandMatchesDocumentPattern(t *testing.T) { |
| re := documentPattern(t) |
| g := loadBoxGolden(t) |
| for _, c := range g.RemoteCommands { |
| - got, err := RemoteCommand(c.Verb, goldenArgs(t, c.Args), c.Nonce) |
| + a, _ := goldenDrain(c.Verb, goldenArgs(t, c.Args), c.Command) |
| + got, err := RemoteCommand(c.Verb, a, c.Nonce) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -204,7 +219,18 @@ func TestRemoteCommandMatchesDocumentPattern(t *testing.T) { |
| for n := rng.Intn(80); n > 0; n-- { |
| tx += string(txChars[rng.Intn(len(txChars))]) |
| } |
| - a := BoxArgs{SHA256: hex(64), Transaction: tx, Permit: map[string]any{ |
| + refChars := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" |
| + peers := []string{} |
| + for n := rng.Intn(6); n > 0; n-- { |
| + p := string(refChars[rng.Intn(62)]) |
| + for m := rng.Intn(30); m > 0; m-- { |
| + p += string(refChars[rng.Intn(len(refChars))]) |
| + } |
| + if !slices.Contains(peers, p) { |
| + peers = append(peers, p) |
| + } |
| + } |
| + a := BoxArgs{SHA256: hex(64), Transaction: tx, Peers: peers, Permit: map[string]any{ |
| "v": int64(1), "transaction": tx, "boot_id": hex(8) + "-\u00e9", "expires": rng.Int63(), |
| "allow_rollback": rng.Intn(2) == 0}} |
| for _, verb := range []string{"status", "prepare", "permit", "revoke", "apply", "rollback", "drain", |
| @@ -220,9 +246,11 @@ func TestRemoteCommandMatchesDocumentPattern(t *testing.T) { |
| } |
| // The pattern is not vacuous: a leading-dash transaction (which |
| // RemoteCommand refuses) and an altered frame both fail it. |
| - drain, _ := RemoteCommand("drain", BoxArgs{Transaction: "t6"}, hex(32)) |
| + drain, _ := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: []string{"adi", "g-0123456789abcdef0123"}}, hex(32)) |
| for _, bad := range []string{ |
| - strings.Replace(drain, "drain t6", "drain -t6", 1), |
| + strings.Replace(drain, "drain --peers=adi,g-0123456789abcdef0123 t6", "drain --peers=adi,g-0123456789abcdef0123 -t6", 1), |
| + strings.Replace(drain, "--peers=adi,g-0123456789abcdef0123", "--peers=adi;g-0123456789abcdef0123", 1), |
| + strings.Replace(drain, "--peers=adi,g-0123456789abcdef0123 ", "", 1), |
| strings.Replace(drain, "3600s", "3601s", 1), |
| strings.Replace(drain, "exit 77", "exit 78", 1), |
| drain + "\n", |
| @@ -454,3 +482,29 @@ func TestUncertainDetails(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// drain always names its acknowledgement population: the exact --peers |
| +// argument, and refusals for no list, a bad reference, a duplicate and too |
| +// many boxes (held floor capability ruling, 2026-11-10). |
| +func TestRemoteCommandDrainPeers(t *testing.T) { |
| + nonce := "0123456789abcdef0123456789abcdef" |
| + got, err := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: []string{"adi", "g-0123456789abcdef0123", "edge.b_1"}}, nonce) |
| + if err != nil || !strings.Contains(got, "(/usr/bin/timeout --signal=TERM --kill-after=30s 3600s /opt/carlos/carlos system group-maintenance drain --peers=adi,g-0123456789abcdef0123,edge.b_1 t6);") { |
| + t.Fatalf("got %s, %v", got, err) |
| + } |
| + many := make([]string, MaxDrainPeers+1) |
| + for i := range many { |
| + many[i] = fmt.Sprintf("b%d", i) |
| + } |
| + for name, peers := range map[string][]string{ |
| + "no list": nil, "blank": {""}, "comma": {"a,b"}, "space": {"a b"}, "dash first": {"-a"}, |
| + "quote": {"a'b"}, "duplicate": {"adi", "adi"}, "too many": many, |
| + } { |
| + if _, err := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: peers}, nonce); refusalKey(err) != "record" { |
| + t.Errorf("%s: %v, want record", name, err) |
| + } |
| + } |
| + if _, err := RemoteCommand("drain", BoxArgs{Transaction: "t6", Peers: many[:MaxDrainPeers]}, nonce); err != nil { |
| + t.Errorf("%d peers: %v", MaxDrainPeers, err) |
| + } |
| +} |
diff --git a/internal/grouproll/depart.go b/internal/grouproll/depart.go| index 91a9d6256..d6e11179c 100644 |
| --- a/internal/grouproll/depart.go |
| +++ b/internal/grouproll/depart.go |
| @@ -332,6 +332,35 @@ func (e *Engine) drainFailed(reasons []string, report any) error { |
| return stopped("drain-failed", "drain_failed") |
| } |
| +// drainPeers is the drain's acknowledgement population (§25.4 step 1, held |
| +// floor capability ruling, 2026-11-10: one population, read once, by the |
| +// party that decides): the boxes this transaction's floor row counted from |
| +// its listing of control/edges/, the member itself excluded. The member |
| +// asks every one of them, plus any its own fold adds; its fold never |
| +// removes one. A transaction with no drain floor row is a damaged record. |
| +func (e *Engine) drainPeers() ([]string, error) { |
| + row, ok := e.last("floor", nil) |
| + if !ok || row["rule"] != "drain" { |
| + return nil, refuse("record") |
| + } |
| + self, _ := e.hIdentity()["box_ref"].(string) |
| + live, _ := row["live"].([]any) |
| + peers := []string{} |
| + for _, v := range live { |
| + s, ok := v.(string) |
| + if !ok { |
| + return nil, refuse("record") |
| + } |
| + if s != self { |
| + peers = append(peers, s) |
| + } |
| + } |
| + if len(peers) > MaxDrainPeers { |
| + return nil, refuse("drain_peers_many", "count", strconv.Itoa(len(peers)), "max", strconv.Itoa(MaxDrainPeers)) |
| + } |
| + return peers, nil |
| +} |
| + |
| // drain is the script's Operator.drain: up to DrainTries drain sessions |
| // (an uncertain one is run again and joins the move), then the report |
| // must be this transaction's finished move, fenced, from a known agent |
| @@ -341,10 +370,14 @@ func (e *Engine) drain(ctx context.Context) error { |
| if _, err := e.event("phase", map[string]any{"phase": "drain"}); err != nil { |
| return err |
| } |
| + peers, err := e.drainPeers() |
| + if err != nil { |
| + return err |
| + } |
| var r BoxResult |
| for attempt := 1; ; attempt++ { |
| var err error |
| - r, err = e.box(ctx, iid, "drain", BoxArgs{Transaction: tx}) |
| + r, err = e.box(ctx, iid, "drain", BoxArgs{Transaction: tx, Peers: peers}) |
| if err == nil { |
| break |
| } |
| @@ -385,7 +418,7 @@ func (e *Engine) drain(ctx context.Context) error { |
| } |
| return e.drainFailed(reasons, report) |
| } |
| - _, err := e.event("drained", map[string]any{"incarnation": incarnation, "report": report}) |
| + _, err = e.event("drained", map[string]any{"incarnation": incarnation, "report": report}) |
| return err |
| } |
diff --git a/internal/grouproll/depart_test.go b/internal/grouproll/depart_test.go| index 8158000fe..3cb52d4e6 100644 |
| --- a/internal/grouproll/depart_test.go |
| +++ b/internal/grouproll/depart_test.go |
| @@ -1179,6 +1179,27 @@ func TestDepartDeclaredFixedBoxWithoutAFile(t *testing.T) { |
| mustFloorRefused(t, h, Text("floor_fixed_missing", "box", "adi")) |
| } |
| +// The drain request names the floor's population, read once: every box |
| +// the floor row counted, the member excluded (held floor capability |
| +// ruling, 2026-11-10). An old file and a fixed box are on it like a peer. |
| +func TestDepartDrainNamesTheFloorPopulation(t *testing.T) { |
| + h := newHeldHarness(t, 2, nil) |
| + h.f.fixed["olden"] = fixedEdges{haHandover: int64(1), age: 6 * time.Hour} |
| + if err := h.depart("replace", heldTx); err != nil { |
| + t.Fatal(err) |
| + } |
| + j := h.txJournal(heldTx) |
| + var peers any |
| + for _, r := range j.Rows() { |
| + if a, ok := r["args"].(map[string]any); ok && r["kind"] == "intent" && a["verb"] == "drain" { |
| + peers = a["peers"] |
| + } |
| + } |
| + if !sameValue(peers, []any{"adi", ref(fakePeer), "olden"}) { |
| + t.Fatalf("drain peers %v, want the floor's live list without the member", peers) |
| + } |
| +} |
| + |
| // RemoveTests and RemoveMinimumTests. |
| func removeHarness(t *testing.T, pools map[string]any) *harness { |
diff --git a/internal/grouproll/engine.go b/internal/grouproll/engine.go| index 3093c4148..614c938e6 100644 |
| --- a/internal/grouproll/engine.go |
| +++ b/internal/grouproll/engine.go |
| @@ -349,6 +349,13 @@ func (e *Engine) box(ctx context.Context, iid, verb string, a BoxArgs) (BoxResul |
| if a.Permit != nil { |
| args["permit"] = a.Permit |
| } |
| + if a.Peers != nil { |
| + peers := make([]any, len(a.Peers)) |
| + for i, p := range a.Peers { |
| + peers[i] = p |
| + } |
| + args["peers"] = peers |
| + } |
| var res BoxResult |
| _, err := e.call(ctx, "session", args, time.Time{}, func(ctx context.Context, onSession func(string)) (any, error) { |
| r, err := e.b.Run(ctx, iid, verb, a, onSession) |
diff --git a/internal/grouproll/fake_test.go b/internal/grouproll/fake_test.go| index da0d79528..5382e95d8 100644 |
| --- a/internal/grouproll/fake_test.go |
| +++ b/internal/grouproll/fake_test.go |
| @@ -653,6 +653,13 @@ func (f *fake) Run(ctx context.Context, iid, verb string, a BoxArgs, onSession f |
| if a.Permit != nil { |
| args["permit"] = a.Permit |
| } |
| + if a.Peers != nil { |
| + peers := make([]any, len(a.Peers)) |
| + for i, p := range a.Peers { |
| + peers[i] = p |
| + } |
| + args["peers"] = peers |
| + } |
| r, err := f.request("session", args, func() (any, error) { |
| if f.sessions != nil { |
| for _, id := range f.sessions(iid, verb) { |
diff --git a/internal/grouproll/text.go b/internal/grouproll/text.go| index bad9eeb6d..055ba55ce 100644 |
| --- a/internal/grouproll/text.go |
| +++ b/internal/grouproll/text.go |
| @@ -94,6 +94,7 @@ var text = map[string]string{ |
| "floor_box": "Box {box} does not publish ha_handover: 1", |
| "floor_fixed_missing": "Fixed box {box} is in fixed_boxes but has no edges file", |
| "floor_fixed_boxes": "The config must list the deployment's fixed boxes in fixed_boxes, or set no_fixed_boxes to true if it has none", |
| + "drain_peers_many": "The floor counted {count} other boxes, more than the {max} one drain request can name", |
| "floor_fixed_both": "The config lists fixed_boxes and also sets no_fixed_boxes to true. Keep only one", |
| "floor_unreadable": "The edges file {key} cannot be read", |
| "floor_template": "The pinned launch template boots release {release}, below ha_floor", |
diff --git a/internal/grouproll/text_test.go b/internal/grouproll/text_test.go| index 65a058f68..067c27c0a 100644 |
| --- a/internal/grouproll/text_test.go |
| +++ b/internal/grouproll/text_test.go |
| @@ -12,11 +12,11 @@ var placeholderPattern = regexp.MustCompile(`\{([a-z_]+)\}`) |
| // for every placeholder it names. A key whose text names a placeholder |
| // Text cannot fill, or leaves a brace behind, fails here. |
| func TestTextRendersEveryKey(t *testing.T) { |
| - // 139 approved, plus floor_fixed_missing, floor_fixed_boxes and |
| - // floor_fixed_both (held floor capability, 2026-11-10), not yet |
| - // copy-reviewed. |
| - if len(text) != 142 { |
| - t.Fatalf("text has %d keys, want the 139 approved plus 3", len(text)) |
| + // 139 approved, plus floor_fixed_missing, floor_fixed_boxes, |
| + // floor_fixed_both and drain_peers_many (held floor capability, |
| + // 2026-11-10), not yet copy-reviewed. |
| + if len(text) != 143 { |
| + t.Fatalf("text has %d keys, want the 139 approved plus 4", len(text)) |
| } |
| for key, raw := range text { |
| var args []string |
diff --git a/internal/host/group_maintenance_drain.go b/internal/host/group_maintenance_drain.go| index 36079b092..8f8e15d1c 100644 |
| --- a/internal/host/group_maintenance_drain.go |
| +++ b/internal/host/group_maintenance_drain.go |
| @@ -118,7 +118,7 @@ func (cmd *groupMaintenanceCommand) runDrain(ctx context.Context, out io.Writer) |
| func (cmd *groupMaintenanceCommand) moveUnderway(ctx context.Context, agent drainCaller) bool { |
| sctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| defer cancel() |
| - r, err := agent(sctx, "status", "") |
| + r, err := agent(sctx, "status", "", nil) |
| if err != nil || r.err() != nil || r.Status == nil { |
| return false |
| } |
| @@ -128,7 +128,7 @@ func (cmd *groupMaintenanceCommand) moveUnderway(ctx context.Context, agent drai |
| // drainStep asks the agent for one step and returns its report. |
| func (cmd *groupMaintenanceCommand) drainStep(ctx context.Context, agent drainCaller, step string) (*drainReport, error) { |
| - r, err := agent(ctx, step, cmd.txn) |
| + r, err := agent(ctx, step, cmd.txn, cmd.peers) |
| if err != nil { |
| return nil, err |
| } |
| @@ -158,7 +158,7 @@ func (cmd *groupMaintenanceCommand) runDrainCancel(ctx context.Context) error { |
| } |
| ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) |
| defer cancel() |
| - r, callErr := cmd.agent()(ctx, "cancel", cmd.txn) |
| + r, callErr := cmd.agent()(ctx, "cancel", cmd.txn, nil) |
| if callErr == nil { |
| callErr = r.err() |
| } |
| @@ -193,7 +193,7 @@ func (cmd *groupMaintenanceCommand) handoverStatus(ctx context.Context) (mainten |
| ds := maintenanceDrainStatus{State: "unknown"} |
| sctx, cancel := context.WithTimeout(ctx, 5*time.Second) |
| defer cancel() |
| - r, err := cmd.agent()(sctx, "status", "") |
| + r, err := cmd.agent()(sctx, "status", "", nil) |
| if err == nil { |
| err = r.err() |
| } |
diff --git a/internal/host/group_maintenance_verbs.go b/internal/host/group_maintenance_verbs.go| index 1c8e2ef5a..173785bd0 100644 |
| --- a/internal/host/group_maintenance_verbs.go |
| +++ b/internal/host/group_maintenance_verbs.go |
| @@ -11,6 +11,7 @@ import ( |
| "net/http" |
| "os" |
| "path/filepath" |
| + "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/hostenv" |
| @@ -35,11 +36,13 @@ 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 --peers=<box,...> <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. |
| + listed box, and any other box with an edges file, to acknowledge, install |
| + the start fence for the transaction, then move every awake host away and |
| + drain the connections. --peers lists every other box the operator's |
| + floor counted (empty when it counted none). 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> |
| @@ -73,6 +76,10 @@ func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int |
| fmt.Fprint(stderr, groupMaintenanceHelp) |
| return 2 |
| } |
| + var peers []string |
| + if verb == "drain" && len(args) == 3 { |
| + peers, _ = parseDrainPeersFlag(args[1]) |
| + } |
| digest, txn := value, "" |
| if drainVerb(verb) { |
| digest, txn = "", value |
| @@ -80,7 +87,7 @@ func RunGroupMaintenance(args []string, in io.Reader, out, stderr io.Writer) int |
| cmd := groupMaintenanceCommand{ |
| a: &systemApplier{etcDir: "/etc", optDir: release.OptDir(), dataDir: dataDir(), ops: productionSysOps()}, |
| euid: os.Geteuid, root: "/", edge: maintenanceEdgeProcess, |
| - client: maintenanceHealthClient(nil), sha256: digest, txn: txn, |
| + client: maintenanceHealthClient(nil), sha256: digest, txn: txn, peers: peers, |
| startedAt: func(start string) (string, error) { return maintenanceProcessStartedAt("/proc", start) }, |
| configure: configureMaintenanceApplier, |
| } |
| @@ -104,6 +111,9 @@ type groupMaintenanceCommand struct { |
| configure func(*systemApplier, map[string]string) error |
| // txn is the drain verbs' transaction. |
| txn string |
| + // peers is drain's --peers list, nil when the caller passed none (the |
| + // agent then refuses the drain). |
| + peers []string |
| // fence and drainCall are the start fence and the agent call; zero |
| // means production's (groupStartFence, execDrainCall: a child as the |
| // agent's user, hadrain_call.go). |
| @@ -448,7 +458,14 @@ func maintenanceArguments(args []string) (string, string, error) { |
| txn := func(s string) bool { return groupTransactionID.MatchString(s) && s[0] != '-' } |
| switch { |
| case len(args) == 2 && args[0] == "drain" && txn(args[1]): |
| + // No --peers: an older verb. Accepted here so the agent's refusal |
| + // is reported; the drain refuses before any move. |
| return "drain", args[1], nil |
| + case len(args) == 3 && args[0] == "drain" && strings.HasPrefix(args[1], drainPeersFlag) && txn(args[2]): |
| + if _, ok := parseDrainPeersFlag(args[1]); !ok { |
| + return "", "", errGroupMaintenance |
| + } |
| + return "drain", args[2], 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]): |
diff --git a/internal/host/hadrain.go b/internal/host/hadrain.go| index 03462a250..701404fd0 100644 |
| --- a/internal/host/hadrain.go |
| +++ b/internal/host/hadrain.go |
| @@ -98,7 +98,7 @@ type drainActivator interface { |
| // drainEdge is the edge's half (internal/edge hadrain.go, hatake.go, |
| // hadrainconns.go). |
| type drainEdge interface { |
| - DrainAckPeers() ([]string, error) |
| + DrainAckPeers() []string |
| AskDrainSeen(ctx context.Context, peer, txn, phase string, id uint64) (bool, error) |
| PeerTakes(ref string) bool |
| PeerDraining(ref string) bool |
| @@ -202,7 +202,10 @@ type drainDriver struct { |
| } |
| type drainRun struct { |
| - step string |
| + step string |
| + // peers is the step's acknowledgement population as the verb passed |
| + // it (§25.4 step 1). |
| + peers []string |
| cancel context.CancelFunc |
| done chan struct{} |
| } |
| @@ -212,6 +215,7 @@ var ( |
| errDrainNoFence = errors.New("the start fence for this transaction is not installed") |
| errDrainStep = errors.New("withdraw must succeed before move") |
| errDrainUnknown = errors.New("unknown drain step") |
| + errDrainNoPeers = errors.New("the drain request names no acknowledgement peers; the operator's tool is older than this agent") |
| errDrainCancel = errors.New("the drain is being cancelled") |
| ) |
| @@ -222,13 +226,20 @@ func newDrainDriver(act drainActivator, e drainEdge, marks drainMarks, fence fun |
| // 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) { |
| +func (d *drainDriver) start(txn, step string, peers []string) (<-chan struct{}, error) { |
| if !groupTransactionID.MatchString(txn) { |
| return nil, errGroupMaintenance |
| } |
| if step != "withdraw" && step != "move" { |
| return nil, errDrainUnknown |
| } |
| + // The verb's list is the acknowledgement population, read once from |
| + // its listing of control/edges/ (held floor capability ruling, |
| + // 2026-11-10). Without it nothing runs: no move is made on this box's |
| + // own fold alone. |
| + if !validDrainPeers(peers) { |
| + return nil, errDrainNoPeers |
| + } |
| d.mu.Lock() |
| defer d.mu.Unlock() |
| if d.cancelling { |
| @@ -272,7 +283,7 @@ func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| } |
| d.txn = txn |
| ctx, cancel := context.WithDeadline(context.Background(), d.deadline) |
| - r := &drainRun{step: step, cancel: cancel, done: make(chan struct{})} |
| + r := &drainRun{step: step, peers: append([]string{}, peers...), 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 |
| @@ -281,9 +292,9 @@ func (d *drainDriver) start(txn, step string) (<-chan struct{}, error) { |
| defer cancel() |
| var reasons []string |
| if step == "withdraw" { |
| - reasons = d.withdraw(ctx, txn, rep) |
| + reasons = d.withdraw(ctx, txn, rep, r.peers) |
| } else { |
| - reasons = d.move(ctx, txn, rep) |
| + reasons = d.move(ctx, txn, rep, r.peers) |
| } |
| if ctx.Err() == context.DeadlineExceeded { |
| reasons = append(reasons, "the drain deadline passed") |
| @@ -399,20 +410,23 @@ func (d *drainDriver) note(f func()) { |
| } |
| // withdraw is step 1: the drain state published and acknowledged. |
| -func (d *drainDriver) withdraw(ctx context.Context, txn string, rep *drainReport) []string { |
| +func (d *drainDriver) withdraw(ctx context.Context, txn string, rep *drainReport, listed []string) []string { |
| if err := d.marks.begin(txn); err != nil { |
| return []string{err.Error()} |
| } |
| - return d.publishAndAck(ctx, txn, edge.DrainPhaseDraining, rep) |
| + return d.publishAndAck(ctx, txn, edge.DrainPhaseDraining, rep, listed) |
| } |
| // publishAndAck waits for the wanted drain state to be published, then |
| -// asks every box with an edges file, whatever the file's age, until each |
| -// has seen it: every 5 s, failing after 2 minutes, naming each box that |
| -// did not (held floor capability ruling, 2026-11-10: the file is a hint, |
| -// the live answer is the proof). A fold not yet read in full is retried on |
| -// the same ticks within the same bound. |
| -func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep *drainReport) []string { |
| +// asks every box on listed, the verb's population (§25.4 step 1), until |
| +// each has given a signed answer that it has seen it: every 5 s, failing |
| +// after 2 minutes, naming each box that did not. The edge's fold may only |
| +// add boxes, never remove one: a box in the fold that the list lacks (one |
| +// that published after the verb's listing) is asked too, re-read each |
| +// round. The fold's completeness is never evidence (held floor capability |
| +// ruling, 2026-11-10: one population, read once, by the party that |
| +// decides). |
| +func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep *drainReport, listed []string) []string { |
| pctx, cancel := context.WithTimeout(ctx, drainPublishTimeout) |
| mark, err := d.marks.waitPublished(pctx) |
| cancel() |
| @@ -423,14 +437,10 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| defer acancel() |
| tick := time.NewTicker(drainAckEvery) |
| defer tick.Stop() |
| - peers, perr := d.edge.DrainAckPeers() |
| - for perr != nil { |
| - select { |
| - case <-actx.Done(): |
| - return []string{fmt.Sprintf("the %s state could not be acknowledged: %v", phase, perr)} |
| - case <-tick.C: |
| - } |
| - peers, perr = d.edge.DrainAckPeers() |
| + peers := append([]string{}, listed...) |
| + known := make(map[string]bool, len(peers)) |
| + for _, p := range peers { |
| + known[p] = true |
| } |
| // Only this goroutine reads or writes seen and why; the askers send |
| // their answers back on a channel. |
| @@ -442,6 +452,12 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| err error |
| } |
| for { |
| + for _, p := range d.edge.DrainAckPeers() { |
| + if !known[p] { |
| + known[p] = true |
| + peers = append(peers, p) |
| + } |
| + } |
| var pending []string |
| for _, p := range peers { |
| if !seen[p] { |
| @@ -449,6 +465,7 @@ func (d *drainDriver) publishAndAck(ctx context.Context, txn, phase string, rep |
| } |
| } |
| if len(pending) == 0 { |
| + sort.Strings(peers) |
| d.note(func() { rep.Acked = append([]string(nil), peers...) }) |
| return nil |
| } |
| @@ -501,8 +518,8 @@ func allSeen(peers []string, seen map[string]bool) bool { |
| // move is steps 2 to 5, then the transaction's release audit and the |
| // hold statistics, both read after the connection barrier has joined |
| // every request (so every held request's outcome is counted). |
| -func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport) []string { |
| - reasons := d.moveSteps(ctx, txn, rep) |
| +func (d *drainDriver) move(ctx context.Context, txn string, rep *drainReport, listed []string) []string { |
| + reasons := d.moveSteps(ctx, txn, rep, listed) |
| reasons = append(reasons, d.auditReleases(rep)...) |
| d.note(func() { |
| st := d.act.DrainHoldStatsNow() |
| @@ -556,7 +573,7 @@ func (d *drainDriver) auditReleases(rep *drainReport) []string { |
| } |
| // moveSteps is steps 2 to 5. |
| -func (d *drainDriver) moveSteps(ctx context.Context, txn string, rep *drainReport) []string { |
| +func (d *drainDriver) moveSteps(ctx context.Context, txn string, rep *drainReport, listed []string) []string { |
| fence := func() bool { |
| f := d.fence() |
| return f.Present && f.Err == nil && f.Transaction == txn |
| @@ -618,7 +635,7 @@ func (d *drainDriver) moveSteps(ctx context.Context, txn string, rep *drainRepor |
| if err := d.marks.setDrained(); err != nil { |
| return []string{err.Error()} |
| } |
| - if r := d.publishAndAck(ctx, txn, edge.DrainPhaseDrained, rep); len(r) > 0 { |
| + if r := d.publishAndAck(ctx, txn, edge.DrainPhaseDrained, rep, listed); len(r) > 0 { |
| return r |
| } |
| d.act.EndDrainMoves() |
diff --git a/internal/host/hadrain_call.go b/internal/host/hadrain_call.go| index 940d072bc..e3778298a 100644 |
| --- a/internal/host/hadrain_call.go |
| +++ b/internal/host/hadrain_call.go |
| @@ -32,8 +32,61 @@ import ( |
| "encoding/json" |
| "errors" |
| "io" |
| + "regexp" |
| + "strings" |
| ) |
| +// maxDrainPeers bounds the boxes one drain request names (the verb's |
| +// grouproll.MaxDrainPeers). |
| +const maxDrainPeers = 256 |
| + |
| +// drainPeerRef is a box reference as an edges key names it. |
| +var drainPeerRef = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`) |
| + |
| +// validDrainPeers is whether peers is a drain request's acknowledgement |
| +// population (region HA §25.4 step 1): present (never nil), at most |
| +// maxDrainPeers references in the edges-key grammar, no duplicates. An |
| +// empty list is valid: the verb's floor counted no other box. |
| +func validDrainPeers(peers []string) bool { |
| + if peers == nil || len(peers) > maxDrainPeers { |
| + return false |
| + } |
| + seen := make(map[string]bool, len(peers)) |
| + for _, p := range peers { |
| + if !drainPeerRef.MatchString(p) || seen[p] { |
| + return false |
| + } |
| + seen[p] = true |
| + } |
| + return true |
| +} |
| + |
| +// drainPeersFlag is the --peers=<a,b,...> argument the verb passes to drain |
| +// and root passes to the child; "--peers=" is the empty list. |
| +const drainPeersFlag = "--peers=" |
| + |
| +// parseDrainPeersFlag reads a --peers= argument; ok is false for anything |
| +// that is not one, or whose list is not valid. |
| +func parseDrainPeersFlag(arg string) ([]string, bool) { |
| + list, ok := strings.CutPrefix(arg, drainPeersFlag) |
| + if !ok { |
| + return nil, false |
| + } |
| + peers := []string{} |
| + if list != "" { |
| + peers = strings.Split(list, ",") |
| + } |
| + if !validDrainPeers(peers) { |
| + return nil, false |
| + } |
| + return peers, true |
| +} |
| + |
| +// drainPeersArg is peers as a --peers= argument. |
| +func drainPeersArg(peers []string) string { |
| + return drainPeersFlag + strings.Join(peers, ",") |
| +} |
| + |
| // drainCallCommand is the child's private entry point, before CLI dispatch. |
| const drainCallCommand = "__drain-call" |
| @@ -65,10 +118,12 @@ func (r drainCallResult) err() error { |
| } |
| // drainCaller makes one call of the agent's drain socket: op is withdraw, |
| -// move, cancel or status. A transport failure of the caller itself (the |
| +// move, cancel or status. peers is withdraw's and move's acknowledgement |
| +// population as the verb passed it, nil when it passed none (the agent |
| +// then refuses the step). A transport failure of the caller itself (the |
| // child did not run or answered nothing usable) is the error; the agent's |
| // answer, a refusal included, is the result. |
| -type drainCaller func(ctx context.Context, op, txn string) (drainCallResult, error) |
| +type drainCaller func(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) |
| // drainCallOp is whether op is a call the child makes. |
| func drainCallOp(op string) bool { |
| @@ -78,12 +133,12 @@ func drainCallOp(op string) bool { |
| // socketDrainCall is the call itself over c: the child's body, and the |
| // in-process caller tests use. |
| func socketDrainCall(c *drainClient) drainCaller { |
| - return func(ctx context.Context, op, txn string) (drainCallResult, error) { |
| + return func(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) { |
| r := drainCallResult{V: 1} |
| var err error |
| switch op { |
| case "withdraw", "move": |
| - r.Report, err = c.step(ctx, op, txn) |
| + r.Report, err = c.step(ctx, op, txn, peers) |
| case "cancel": |
| err = c.cancel(ctx, txn) |
| case "status": |
| @@ -103,34 +158,44 @@ func socketDrainCall(c *drainClient) drainCaller { |
| } |
| // drainCallArgs reads the child's arguments: an op and a transaction ("-" |
| -// for status). |
| -func drainCallArgs(args []string) (op, txn string, err error) { |
| - if len(args) != 2 || !drainCallOp(args[0]) { |
| - return "", "", errGroupMaintenance |
| +// for status), then for withdraw and move a --peers= list when root was |
| +// given one (peers nil when not). |
| +func drainCallArgs(args []string) (op, txn string, peers []string, err error) { |
| + if (len(args) != 2 && len(args) != 3) || !drainCallOp(args[0]) { |
| + return "", "", nil, errGroupMaintenance |
| } |
| op, txn = args[0], args[1] |
| + if len(args) == 3 { |
| + var ok bool |
| + if op != "withdraw" && op != "move" { |
| + return "", "", nil, errGroupMaintenance |
| + } |
| + if peers, ok = parseDrainPeersFlag(args[2]); !ok { |
| + return "", "", nil, errGroupMaintenance |
| + } |
| + } |
| if op == "status" { |
| if txn != "-" { |
| - return "", "", errGroupMaintenance |
| + return "", "", nil, errGroupMaintenance |
| } |
| - return op, "", nil |
| + return op, "", nil, nil |
| } |
| if !groupTransactionID.MatchString(txn) || txn[0] == '-' { |
| - return "", "", errGroupMaintenance |
| + return "", "", nil, errGroupMaintenance |
| } |
| - return op, txn, nil |
| + return op, txn, peers, nil |
| } |
| // runDrainCallBody is the child after its privileges are dropped: one call |
| // over the socket at path, its answer printed as one JSON line. |
| func runDrainCallBody(ctx context.Context, args []string, path string, out io.Writer) error { |
| - op, txn, err := drainCallArgs(args) |
| + op, txn, peers, err := drainCallArgs(args) |
| if err != nil { |
| return err |
| } |
| ctx, cancel := context.WithTimeout(ctx, haDrainCallBound) |
| defer cancel() |
| - r, err := socketDrainCall(newDrainClient(path))(ctx, op, txn) |
| + r, err := socketDrainCall(newDrainClient(path))(ctx, op, txn, peers) |
| if err != nil { |
| return err |
| } |
| @@ -138,11 +203,15 @@ func runDrainCallBody(ctx context.Context, args []string, path string, out io.Wr |
| } |
| // drainCallChildArgs is the child's argument list after the command: the |
| -// transaction is "-" for status. |
| -func drainCallChildArgs(op, txn string) []string { |
| +// transaction is "-" for status; withdraw and move add --peers= when root |
| +// was given a list. |
| +func drainCallChildArgs(op, txn string, peers []string) []string { |
| if op == "status" { |
| txn = "-" |
| } |
| + if peers != nil && (op == "withdraw" || op == "move") { |
| + return []string{op, txn, drainPeersArg(peers)} |
| + } |
| return []string{op, txn} |
| } |
diff --git a/internal/host/hadrain_call_linux.go b/internal/host/hadrain_call_linux.go| index 1f7a06fc8..dc7ab832c 100644 |
| --- a/internal/host/hadrain_call_linux.go |
| +++ b/internal/host/hadrain_call_linux.go |
| @@ -14,11 +14,11 @@ import ( |
| // execDrainCall is the production drainCaller: one child, run as the |
| // agent's user, per call (hadrain_call.go). |
| -func execDrainCall(ctx context.Context, op, txn string) (drainCallResult, error) { |
| - if !drainCallOp(op) { |
| +func execDrainCall(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) { |
| + if !drainCallOp(op) || (peers != nil && !validDrainPeers(peers)) { |
| return drainCallResult{}, errGroupMaintenance |
| } |
| - cmd, err := drainCallExec(op, txn) |
| + cmd, err := drainCallExec(op, txn, peers) |
| if err != nil { |
| return drainCallResult{}, err |
| } |
| @@ -28,11 +28,11 @@ func execDrainCall(ctx context.Context, op, txn string) (drainCallResult, error) |
| // drainCallExec is the child's command: the pinned executable (fd 3, as |
| // the registry child), the private command, op and transaction, an empty |
| // environment, "/" as its directory, and no stdin. |
| -func drainCallExec(op, txn string) (*exec.Cmd, error) { |
| +func drainCallExec(op, txn string, peers []string) (*exec.Cmd, error) { |
| if registryExecutableError != nil { |
| return nil, registryExecutableError |
| } |
| - cmd := exec.Command("/proc/self/fd/3", append([]string{drainCallCommand}, drainCallChildArgs(op, txn)...)...) |
| + cmd := exec.Command("/proc/self/fd/3", append([]string{drainCallCommand}, drainCallChildArgs(op, txn, peers)...)...) |
| cmd.ExtraFiles = []*os.File{registryExecutable} |
| cmd.Env = []string{} |
| cmd.Dir = "/" |
diff --git a/internal/host/hadrain_call_linux_test.go b/internal/host/hadrain_call_linux_test.go| index 928984dd8..ffe615e4e 100644 |
| --- a/internal/host/hadrain_call_linux_test.go |
| +++ b/internal/host/hadrain_call_linux_test.go |
| @@ -43,20 +43,29 @@ func init() { |
| // transaction; an empty environment, "/" and no stdin. It runs through the |
| // registry child's start (no new privileges) and drops to carlos itself. |
| func TestDrainCallCommand(t *testing.T) { |
| - cmd, err := drainCallExec("move", "t1") |
| + cmd, err := drainCallExec("move", "t1", []string{"adi", "g-0123456789abcdef0123"}) |
| must(t, err) |
| - if cmd.Path != "/proc/self/fd/3" || strings.Join(cmd.Args, " ") != "/proc/self/fd/3 __drain-call move t1" { |
| + if cmd.Path != "/proc/self/fd/3" || strings.Join(cmd.Args, " ") != "/proc/self/fd/3 __drain-call move t1 --peers=adi,g-0123456789abcdef0123" { |
| t.Fatalf("command %q %q", cmd.Path, cmd.Args) |
| } |
| + if cmd, _ = drainCallExec("withdraw", "t1", nil); strings.Join(cmd.Args[1:], " ") != "__drain-call withdraw t1" { |
| + t.Fatalf("no list: %q", cmd.Args) |
| + } |
| + if cmd, _ = drainCallExec("withdraw", "t1", []string{}); strings.Join(cmd.Args[1:], " ") != "__drain-call withdraw t1 --peers=" { |
| + t.Fatalf("empty list: %q", cmd.Args) |
| + } |
| if cmd.Env == nil || len(cmd.Env) != 0 || cmd.Dir != "/" || cmd.Stdin != nil || len(cmd.ExtraFiles) != 1 || cmd.ExtraFiles[0] != registryExecutable { |
| t.Fatalf("env %q dir %q stdin %v extra %v", cmd.Env, cmd.Dir, cmd.Stdin, cmd.ExtraFiles) |
| } |
| - if cmd, _ = drainCallExec("status", ""); strings.Join(cmd.Args[1:], " ") != "__drain-call status -" { |
| + if cmd, _ = drainCallExec("status", "", nil); strings.Join(cmd.Args[1:], " ") != "__drain-call status -" { |
| t.Fatalf("status args %q", cmd.Args) |
| } |
| - if _, err := execDrainCall(context.Background(), "stop", "t1"); err == nil { |
| + if _, err := execDrainCall(context.Background(), "stop", "t1", nil); err == nil { |
| t.Fatal("an unknown op ran a child") |
| } |
| + if _, err := execDrainCall(context.Background(), "withdraw", "t1", []string{"a", "a"}); err == nil { |
| + t.Fatal("a duplicate peer ran a child") |
| + } |
| } |
| func TestDrainCallArgs(t *testing.T) { |
| @@ -65,6 +74,13 @@ func TestDrainCallArgs(t *testing.T) { |
| op, txn string |
| bad bool |
| }{ |
| + {[]string{"withdraw", "t1", "--peers=adi,g-0123456789abcdef0123"}, "withdraw", "t1", false}, |
| + {[]string{"move", "t1", "--peers="}, "move", "t1", false}, |
| + {[]string{"withdraw", "t1", "--peers=adi,adi"}, "", "", true}, |
| + {[]string{"withdraw", "t1", "--peers=a b"}, "", "", true}, |
| + {[]string{"withdraw", "t1", "--peers=,"}, "", "", true}, |
| + {[]string{"cancel", "t1", "--peers="}, "", "", true}, |
| + {[]string{"status", "-", "--peers="}, "", "", true}, |
| {[]string{"withdraw", "t1"}, "withdraw", "t1", false}, |
| {[]string{"move", "t1"}, "move", "t1", false}, |
| {[]string{"cancel", "t1"}, "cancel", "t1", false}, |
| @@ -76,7 +92,7 @@ func TestDrainCallArgs(t *testing.T) { |
| {[]string{"move"}, "", "", true}, |
| {[]string{"move", "t1", "x"}, "", "", true}, |
| } { |
| - op, txn, err := drainCallArgs(tc.args) |
| + op, txn, _, err := drainCallArgs(tc.args) |
| if (err != nil) != tc.bad || op != tc.op || txn != tc.txn { |
| t.Fatalf("%q: %q %q %v", tc.args, op, txn, err) |
| } |
| @@ -114,15 +130,15 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| cmd, l := verbDrain(t, d) |
| d.fence = l.read |
| path := socketPathOf(t, cmd) |
| - child := func(ctx context.Context, op, txn string) (drainCallResult, error) { |
| - c, err := drainCallExec(op, txn) |
| + child := func(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) { |
| + c, err := drainCallExec(op, txn, peers) |
| if err != nil { |
| return drainCallResult{}, err |
| } |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path} |
| return runDrainCallChild(ctx, c) |
| } |
| - r, err := child(context.Background(), "status", "") |
| + r, err := child(context.Background(), "status", "", nil) |
| if err != nil || r.err() != nil || r.Status == nil || r.Status.Incarnation != agentIncarnation { |
| t.Fatalf("status through the child: %+v %v", r, err) |
| } |
| @@ -135,7 +151,7 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| t.Fatal("the agent's own start gate is open after the withdrawal") |
| } |
| // A refusal comes back as the agent's answer, not a caller failure. |
| - if r, err = child(context.Background(), "cancel", "t2"); err != nil || !strings.Contains(r.Error, errDrainOtherTxn.Error()) || r.AgentDown { |
| + if r, err = child(context.Background(), "cancel", "t2", nil); err != nil || !strings.Contains(r.Error, errDrainOtherTxn.Error()) || r.AgentDown { |
| t.Fatalf("refused cancel: %+v %v", r, err) |
| } |
| if _, err = runDrainVerb(t, cmd, "drain-cancel", "t1"); err != nil || l.read().Present || marks.startsClosed() { |
| @@ -143,13 +159,13 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| } |
| // No agent: agent_down. |
| other := filepath.Join(filepath.Dir(path), "none.sock") |
| - c, _ := drainCallExec("status", "") |
| + c, _ := drainCallExec("status", "", nil) |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + other} |
| if r, err = runDrainCallChild(context.Background(), c); err != nil || !r.AgentDown { |
| t.Fatalf("no agent: %+v %v", r, err) |
| } |
| // A child that fails or is killed is a caller error, not an answer. |
| - c, _ = drainCallExec("status", "") |
| + c, _ = drainCallExec("status", "", nil) |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path} |
| c.Args = []string{c.Args[0], drainCallCommand, "status", "t1"} |
| if _, err = runDrainCallChild(context.Background(), c); err == nil { |
| @@ -157,7 +173,7 @@ func TestDrainCallChildEndToEnd(t *testing.T) { |
| } |
| ctx, cancel := context.WithCancel(context.Background()) |
| cancel() |
| - c, _ = drainCallExec("status", "") |
| + c, _ = drainCallExec("status", "", nil) |
| c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + path} |
| if _, err = runDrainCallChild(ctx, c); err == nil { |
| t.Fatal("a cancelled call answered") |
| @@ -170,7 +186,7 @@ func TestDrainCallChildRefusesWithoutDrop(t *testing.T) { |
| if os.Geteuid() == 0 { |
| t.Skip("as root the child would drop to carlos") |
| } |
| - c, err := drainCallExec("status", "") |
| + c, err := drainCallExec("status", "", nil) |
| must(t, err) |
| out := &cappedBuffer{max: 4096} |
| errOut := &cappedBuffer{max: 4096} |
diff --git a/internal/host/hadrain_call_other.go b/internal/host/hadrain_call_other.go| index 3845266f9..23ef928c0 100644 |
| --- a/internal/host/hadrain_call_other.go |
| +++ b/internal/host/hadrain_call_other.go |
| @@ -10,7 +10,7 @@ import ( |
| ) |
| // execDrainCall: the drain verbs are Linux group members' only. |
| -func execDrainCall(context.Context, string, string) (drainCallResult, error) { |
| +func execDrainCall(context.Context, string, string, []string) (drainCallResult, error) { |
| return drainCallResult{}, errSystemUnsupported |
| } |
diff --git a/internal/host/hadrain_socket.go b/internal/host/hadrain_socket.go| index a57803042..1b378d53f 100644 |
| --- a/internal/host/hadrain_socket.go |
| +++ b/internal/host/hadrain_socket.go |
| @@ -8,8 +8,12 @@ package host |
| // (hadrain_call.go). 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/withdraw {"transaction":T,"peers":[...]} step 1; answers the report |
| +// POST /v1/drain/move {"transaction":T,"peers":[...]} steps 2-5; answers the report |
| +// |
| +// peers is the verb's acknowledgement population (§25.4 step 1): the boxes |
| +// its floor counted, the member excluded. A step without it is refused |
| +// before anything runs. |
| // POST /v1/drain/cancel {"transaction":T} drain --cancel |
| // GET /v1/drain/status incarnation and drain state |
| // |
| @@ -31,14 +35,17 @@ import ( |
| const ( |
| haDrainSocketDir = "/run/carlos/.ha-drain" |
| haDrainSocketPath = haDrainSocketDir + "/drain.sock" |
| - haDrainBodyMax = 4096 |
| + // haDrainBodyMax bounds a request: a transaction and up to |
| + // maxDrainPeers references of at most 128 bytes each. |
| + haDrainBodyMax = 64 << 10 |
| // 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"` |
| + Transaction string `json:"transaction"` |
| + Peers *[]string `json:"peers,omitempty"` |
| } |
| type drainError struct { |
| @@ -78,7 +85,8 @@ func (d *drainDriver) handler() http.Handler { |
| 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) { |
| + if err != nil || len(b) > haDrainBodyMax || dec.Decode(&ask) != nil || !groupTransactionID.MatchString(ask.Transaction) || |
| + (ask.Peers != nil && (step == "cancel" || !validDrainPeers(*ask.Peers))) { |
| w.WriteHeader(http.StatusBadRequest) |
| _ = json.NewEncoder(w).Encode(drainError{Error: errGroupMaintenance.Error()}) |
| return |
| @@ -94,7 +102,11 @@ func (d *drainDriver) handler() http.Handler { |
| _ = json.NewEncoder(w).Encode(struct{}{}) |
| return |
| } |
| - done, err := d.start(ask.Transaction, step) |
| + var peers []string |
| + if ask.Peers != nil { |
| + peers = *ask.Peers |
| + } |
| + done, err := d.start(ask.Transaction, step, peers) |
| if err != nil { |
| w.WriteHeader(http.StatusConflict) |
| _ = json.NewEncoder(w).Encode(drainError{Error: err.Error()}) |
| @@ -167,9 +179,13 @@ func (c *drainClient) call(ctx context.Context, method, path string, body any, o |
| return nil |
| } |
| -func (c *drainClient) step(ctx context.Context, step, txn string) (*drainReport, error) { |
| +func (c *drainClient) step(ctx context.Context, step, txn string, peers []string) (*drainReport, error) { |
| var rep drainReport |
| - if err := c.call(ctx, http.MethodPost, "/v1/drain/"+step, drainAsk{Transaction: txn}, &rep); err != nil { |
| + ask := drainAsk{Transaction: txn} |
| + if peers != nil { |
| + ask.Peers = &peers |
| + } |
| + if err := c.call(ctx, http.MethodPost, "/v1/drain/"+step, ask, &rep); err != nil { |
| return nil, err |
| } |
| return &rep, nil |
diff --git a/internal/host/hadrain_test.go b/internal/host/hadrain_test.go| index 27655a8d4..2a624eb52 100644 |
| --- a/internal/host/hadrain_test.go |
| +++ b/internal/host/hadrain_test.go |
| @@ -264,7 +264,6 @@ type fakeDrainEdge struct { |
| mu sync.Mutex |
| peers []string |
| - peersErr func() error |
| asks map[string]int |
| nottake map[string]bool |
| draining map[string]bool |
| @@ -275,16 +274,10 @@ type fakeDrainEdge struct { |
| heldShut []string |
| } |
| -func (f *fakeDrainEdge) DrainAckPeers() ([]string, error) { |
| +func (f *fakeDrainEdge) DrainAckPeers() []string { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - if f.peersErr != nil { |
| - err := f.peersErr() |
| - if err != nil { |
| - return nil, err |
| - } |
| - } |
| - return append([]string(nil), f.peers...), nil |
| + return append([]string(nil), f.peers...) |
| } |
| func (f *fakeDrainEdge) AskDrainSeen(_ context.Context, peer, txn, phase string, id uint64) (bool, error) { |
| f.mu.Lock() |
| @@ -463,7 +456,7 @@ func shorten(v *time.Duration, d time.Duration) func() { |
| } |
| func (d *drainDriver) startWithdrawForTest(txn string) error { |
| - done, err := d.start(txn, "withdraw") |
| + done, err := d.start(txn, "withdraw", []string{}) |
| if err != nil { |
| return err |
| } |
| @@ -474,7 +467,13 @@ func (d *drainDriver) startWithdrawForTest(txn string) error { |
| // 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") |
| + return runDrainListed(t, d, txn, []string{}) |
| +} |
| + |
| +// runDrainListed is runDrain with the verb's population. |
| +func runDrainListed(t *testing.T, d *drainDriver, txn string, listed []string) *drainReport { |
| + t.Helper() |
| + done, err := d.start(txn, "withdraw", listed) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -482,7 +481,7 @@ func runDrain(t *testing.T, d *drainDriver, txn string) *drainReport { |
| if r := d.snapshot(); r.Result != "ok" { |
| return r |
| } |
| - done, err = d.start(txn, "move") |
| + done, err = d.start(txn, "move", listed) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -562,7 +561,7 @@ func TestDrainDriverWholeSequence(t *testing.T) { |
| t.Fatal("a successful drain cleared the drain state") |
| } |
| // The move step is answered again as it was. |
| - done, err := d.start("t1", "move") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -619,7 +618,7 @@ func TestDrainWaitsForQuiescence(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - done, err := d.start("t1", "move") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -732,7 +731,7 @@ func TestDrainReleaseLogCatchesEveryUncleanStop(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - done, err := d.start("t1", "move") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -893,7 +892,7 @@ func TestDrainMissingAcknowledgement(t *testing.T) { |
| if ed.askCount("c draining") < 3 || ed.askCount("b draining") != 1 { |
| t.Fatalf("asks: c %d (want re-asked), b %d (want once)", ed.askCount("c draining"), ed.askCount("b draining")) |
| } |
| - if _, err := d.start("t1", "move"); !errors.Is(err, errDrainStep) { |
| + if _, err := d.start("t1", "move", []string{}); !errors.Is(err, errDrainStep) { |
| t.Fatalf("move after a failed withdraw: %v", err) |
| } |
| // A drained acknowledgement missing fails the move step too, with |
| @@ -909,37 +908,6 @@ func TestDrainMissingAcknowledgement(t *testing.T) { |
| } |
| } |
| -// A fold not read in full is no peer list: it is retried on the ack |
| -// ticks, and the drain fails within the same bound if it never is (held |
| -// floor capability ruling: every filed box must answer, so an unread file |
| -// cannot be skipped). |
| -func TestDrainAckPeersUnreadFold(t *testing.T) { |
| - defer shorten(&drainAckBound, 120*time.Millisecond)() |
| - defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| - act, ed, marks := healthyDrain() |
| - ed.peersErr = func() error { return errors.New("ha-drain: the edges files have not all been read") } |
| - rep := runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| - if rep.Result != "failed" || rep.Step != "withdraw" || !strings.Contains(rep.Reasons[0], "have not all been read") { |
| - t.Fatalf("report %+v", rep) |
| - } |
| - if ed.askCount("b draining") != 0 { |
| - t.Fatal("asked with no peer list") |
| - } |
| - // Read on a later tick: the drain goes on. |
| - act, ed, marks = healthyDrain() |
| - var calls atomic.Int32 |
| - ed.peersErr = func() error { |
| - if calls.Add(1) < 3 { |
| - return errors.New("ha-drain: the edges files have not all been read") |
| - } |
| - return nil |
| - } |
| - rep = runDrain(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1") |
| - if rep.Result != "ok" { |
| - t.Fatalf("report %+v", rep) |
| - } |
| -} |
| - |
| // The drain fails before any move when a filed box cannot answer: a box |
| // rolled back to an older binary (its capable file left in place) and a |
| // dead box's leftover file are named; a quiet box that answers is not. |
| @@ -968,6 +936,81 @@ func TestDrainFailsNamingFiledBoxesThatCannotAnswer(t *testing.T) { |
| } |
| } |
| +// Astra r2 F2.1: the verb's list is the population, whatever the fold |
| +// says. olden is on the list and not in the fold (a failed LIST, every GET |
| +// failing, or no poll since it published, as the edge witnesses show), so |
| +// it is asked, cannot answer, and the drain fails naming it before any |
| +// move. The fold's own boxes are asked too: a box the list omits but the |
| +// fold has is not dropped. |
| +func TestDrainAsksTheVerbsListWhateverTheFoldSays(t *testing.T) { |
| + defer shorten(&drainAckBound, 120*time.Millisecond)() |
| + defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + ed.peers = []string{} // the stale fold holds no other box |
| + ed.ack = func(peer string) (bool, error) { |
| + if peer == "olden" { |
| + return false, errors.New("ha-drain: no edges file for olden (fold read: list failed)") |
| + } |
| + return true, nil |
| + } |
| + rep := runDrainListed(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1", []string{"olden"}) |
| + if rep.Result != "failed" || rep.Step != "withdraw" || !strings.Contains(strings.Join(rep.Reasons, ";"), "olden (") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if ed.askCount("olden draining") == 0 || len(rep.Moved) != 0 || act.endedMoves() != 0 { |
| + t.Fatalf("olden asked %d times, moved %+v", ed.askCount("olden draining"), rep.Moved) |
| + } |
| + // The list omits b and c, which the fold has: both are asked, and both |
| + // phases ask the listed box too. |
| + act, ed, marks = healthyDrain() |
| + rep = runDrainListed(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1", []string{"adi"}) |
| + if rep.Result != "ok" || !slices.Equal(rep.Acked, []string{"adi", "b", "c"}) { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + for _, k := range []string{"adi draining", "b draining", "c draining", "adi drained", "b drained", "c drained"} { |
| + if ed.askCount(k) == 0 { |
| + t.Fatalf("%s was not asked", k) |
| + } |
| + } |
| +} |
| + |
| +// Recovery within the bound: olden cannot be asked for two rounds (its file |
| +// not yet readable), then answers; the drain goes on. |
| +func TestDrainListedBoxRecoversWithinTheBound(t *testing.T) { |
| + defer shorten(&drainAckBound, 2*time.Second)() |
| + defer shorten(&drainAckEvery, 20*time.Millisecond)() |
| + act, ed, marks := healthyDrain() |
| + ed.peers = []string{} |
| + var n atomic.Int32 |
| + ed.ack = func(peer string) (bool, error) { |
| + if peer == "olden" && n.Add(1) <= 2 { |
| + return false, errors.New("ha-drain: no edges file for olden") |
| + } |
| + return true, nil |
| + } |
| + rep := runDrainListed(t, newDrainDriver(act, ed, marks, fenceOf("t1")), "t1", []string{"olden"}) |
| + if rep.Result != "ok" || !slices.Equal(rep.Acked, []string{"olden"}) { |
| + t.Fatalf("report %+v", rep) |
| + } |
| +} |
| + |
| +// No list from the verb (an older tool): nothing runs, no move, no state. |
| +func TestDrainWithoutTheVerbsListRefuses(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + d := newDrainDriver(act, ed, marks, fenceOf("t1")) |
| + for _, step := range []string{"withdraw", "move"} { |
| + if _, err := d.start("t1", step, nil); !errors.Is(err, errDrainNoPeers) { |
| + t.Fatalf("%s without a list: %v", step, err) |
| + } |
| + } |
| + if _, err := d.start("t1", "withdraw", []string{"a", "a"}); !errors.Is(err, errDrainNoPeers) { |
| + t.Fatalf("a duplicate: %v", err) |
| + } |
| + if begun, _, _ := marks.counts(); len(ed.rec.events()) != 0 || begun != 0 { |
| + t.Fatalf("a refused drain did something: %v", ed.rec.events()) |
| + } |
| +} |
| + |
| // Many peers answering at once (the acknowledgement map is the |
| // coordinator's alone): run under -race. |
| func TestDrainAcknowledgementsConcurrently(t *testing.T) { |
| @@ -1022,13 +1065,13 @@ func TestDrainMoveNeedsTheFence(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - if _, err := d.start("t1", "move"); !errors.Is(err, errDrainNoFence) { |
| + if _, err := d.start("t1", "move", []string{}); !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) { |
| + if _, err := d.start("t1", "move", []string{}); !errors.Is(err, errDrainNoFence) { |
| t.Fatalf("another fence: %v", err) |
| } |
| mu.Lock() |
| @@ -1036,7 +1079,7 @@ func TestDrainMoveNeedsTheFence(t *testing.T) { |
| 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") |
| + done, err := d.start("t1", "move", []string{}) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -1054,7 +1097,7 @@ func TestDrainOneTransaction(t *testing.T) { |
| if err := d.startWithdrawForTest("t1"); err != nil { |
| t.Fatal(err) |
| } |
| - if _, err := d.start("t2", "withdraw"); !errors.Is(err, errDrainOtherTxn) { |
| + if _, err := d.start("t2", "withdraw", []string{}); !errors.Is(err, errDrainOtherTxn) { |
| t.Fatalf("t2: %v", err) |
| } |
| if err := d.cancel(context.Background(), "t2"); !errors.Is(err, errDrainOtherTxn) { |
| @@ -1063,7 +1106,7 @@ func TestDrainOneTransaction(t *testing.T) { |
| d.mu.Lock() |
| d.cancelling = true |
| d.mu.Unlock() |
| - if _, err := d.start("t1", "withdraw"); !errors.Is(err, errDrainCancel) { |
| + if _, err := d.start("t1", "withdraw", []string{}); !errors.Is(err, errDrainCancel) { |
| t.Fatalf("start during a cancel: %v", err) |
| } |
| d.mu.Lock() |
| @@ -1122,7 +1165,7 @@ func TestDrainAgentRestartVoidsTheReport(t *testing.T) { |
| 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) { |
| + if _, err := restarted.start("t1", "move", []string{}); !errors.Is(err, errDrainStep) { |
| t.Fatalf("move on a restarted agent: %v", err) |
| } |
| } |
diff --git a/internal/host/hadrainfence_linux_test.go b/internal/host/hadrainfence_linux_test.go| index db71a364f..02f4e58f3 100644 |
| --- a/internal/host/hadrainfence_linux_test.go |
| +++ b/internal/host/hadrainfence_linux_test.go |
| @@ -269,6 +269,9 @@ func verbDrain(t *testing.T, d *drainDriver) (*groupMaintenanceCommand, fenceLoc |
| drainSocketPaths.Store(cmd, path) |
| t.Cleanup(func() { drainSocketPaths.Delete(cmd) }) |
| cmd.txn = "" |
| + // The verb always names its population; these fixtures' boxes come |
| + // from the fake fold. |
| + cmd.peers = []string{} |
| return cmd, l |
| } |
| @@ -405,6 +408,33 @@ func TestDrainVerbFailures(t *testing.T) { |
| } |
| } |
| +// A drain verb run with no --peers (an older operator tool) refuses before |
| +// anything moves: the agent answers errDrainNoPeers, and no fence is |
| +// installed. A malformed list never reaches the agent's driver. |
| +func TestDrainVerbWithoutPeersRefuses(t *testing.T) { |
| + act, ed, marks := healthyDrain() |
| + d := newDrainDriver(act, ed, marks, nil) |
| + cmd, l := verbDrain(t, d) |
| + d.fence = l.read |
| + cmd.peers = nil |
| + _, err := runDrainVerb(t, cmd, "drain", "t1") |
| + if err == nil || !strings.Contains(err.Error(), errDrainNoPeers.Error()) || l.read().Present { |
| + t.Fatalf("no list: %v fence %+v", err, l.read()) |
| + } |
| + if begun, _, _ := marks.counts(); begun != 0 || act.endedMoves() != 0 { |
| + t.Fatalf("a refused drain began: %d", begun) |
| + } |
| + // The socket refuses a malformed list outright. |
| + path := socketPathOf(t, cmd) |
| + bad := []string{"a", "a"} |
| + r, err := socketDrainCall(newDrainClient(path))(context.Background(), "withdraw", "t1", bad) |
| + if err != nil || r.err() == nil || begunOf(marks) != 0 { |
| + t.Fatalf("a duplicate list: %+v %v", r, err) |
| + } |
| +} |
| + |
| +func begunOf(m *fakeMarks) int { b, _, _ := m.counts(); return b } |
| + |
| func TestDrainVerbArguments(t *testing.T) { |
| for _, tc := range []struct { |
| args []string |
| @@ -412,6 +442,11 @@ func TestDrainVerbArguments(t *testing.T) { |
| shouldFail bool |
| }{ |
| {[]string{"drain", "t1"}, "drain", "t1", false}, |
| + {[]string{"drain", "--peers=adi,g-0123456789abcdef0123", "t1"}, "drain", "t1", false}, |
| + {[]string{"drain", "--peers=", "t1"}, "drain", "t1", false}, |
| + {[]string{"drain", "--peers=adi,adi", "t1"}, "", "", true}, |
| + {[]string{"drain", "--peers=a;b", "t1"}, "", "", true}, |
| + {[]string{"drain", "--peers=adi"}, "", "", true}, |
| {[]string{"drain", "--cancel", "t1"}, "drain-cancel", "t1", false}, |
| {[]string{"fence-clear", "t1"}, "fence-clear", "t1", false}, |
| {[]string{"drain"}, "", "", true}, |