region HA P3b-2: guarded rolls keep the new edge's hairpin; never latched
Window B: every guarded roll or rollback of a group member closed admission on the new edge. Repeat maintenance guards after the restart tombstoned the successor. The guard now clears once, before mutation. Only a named Revoke writes Closed; a failed enable retries with backoff, stays closed, alerts at 15 min and opens on a passing check. Group boxes get a 3-minute apply gate (40 s bind under an S3 and SSM drop). The client keeps the status and code; the control service logs the step. Proven on a root runner (the old code reproduces the member's logs); table test and 500-seed simulation. Opus reviews; census approved (#280). Paul's ruling on B3-FINDINGS, via 8a3d302. Squashed from region-ha-p3b2-rolls into main.
22 files changed,
+2,499
−121
docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md+13 −13docs/superpowers/notes/census-proposal-region-ha-p3b2-rolls.md+27 −0internal/hairpin/lifecycle.go+24 −7internal/hairpin/lifecycle_test.go+65 −5internal/host/group_admission.go+35 −14internal/host/group_hairpin.go+15 −3internal/host/group_hairpin_retry.go+141 −0internal/host/group_hairpin_retry_test.go+506 −0internal/host/group_hairpin_rootrunner_linux_test.go+182 −4internal/host/group_maintenance.go+24 −9internal/host/group_maintenance_test.go+119 −0internal/host/systemapply.go+16 −6internal/host/systemapply_groupgate_test.go+160 −0internal/instancectl/hairpin.go+219 −54internal/instancectl/hairpin_invariant_test.go+540 −0internal/instancectl/hairpin_retry_linux_test.go+276 −0internal/instancectl/hairpin_test.go+102 −0internal/instancectl/hardening.go+11 −2internal/instancectl/server.go+1 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-region-ha-p3b2-rolls.tsv+18 −0scripts/region-group-roll.py+4 −4
CI passed — run details
diff --git a/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md b/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md| index 2dc583d07..ffbf0b6af 100644 |
| --- a/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md |
| +++ b/docs/superpowers/notes/2026-11-05-region-ha-p3b2-operator.md |
| @@ -138,19 +138,19 @@ access keys, profile selection and endpoint overrides from child commands. |
| ## Refusal and recovery |
| -If a transaction's member has been lost, use `close-lost --transaction '<id>'` |
| -with the script that created its journal: `region-group-roll.py` for a roll |
| -or `region-group-probe.py` for a probe. Under the group lock, it requires an |
| -active, unfinished journal and fresh reads proving that the member is absent |
| -from the exact group ARN and is terminated or not found in EC2. Any other |
| -state or read error refuses closure. |
| - |
| -`close-lost` records `lost-member-closed` and finishes with outcome |
| -`failed-member-lost`. This records failure rather than recovery. It clears |
| -`active.json` without changing the group, a box or `provider-observation.json`. |
| -Any `provider-divergence.json` stays in place and is reported in the output; |
| -it continues to block rolls until the controller resolves it. The saved journal |
| -remains available through `status`. A second `close-lost` refuses. |
| +If a transaction's member is lost, use `close-lost --transaction '<id>'` with |
| +the matching script to close it: `region-group-roll.py` for a roll or |
| +`region-group-probe.py` for a probe. The script requires the group lock, an |
| +active unfinished journal, and fresh reads |
| +confirming that the member is absent from the exact group ARN and is terminated |
| +or not found in EC2. It refuses closure for any other state or read error. |
| + |
| +The `close-lost` operation records `lost-member-closed` and finishes as a |
| +`failed-member-lost` transaction. This records failure, not recovery. It clears |
| +`active.json` without changing the group, a box, or `provider-observation.json`. |
| +A `provider-divergence.json` record stays in place and is reported in the |
| +output. It continues to block rolls until the controller resolves it. The saved |
| +journal remains available through `status`. A second `close-lost` refuses. |
| Before group writes, the tool requires min=desired=max=N with N at least two, |
| all members SSM-online, healthy InService peers in both target groups, exact |
diff --git a/docs/superpowers/notes/census-proposal-region-ha-p3b2-rolls.md b/docs/superpowers/notes/census-proposal-region-ha-p3b2-rolls.md| new file mode 100644 |
| index 000000000..f7290903a |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-region-ha-p3b2-rolls.md |
| @@ -0,0 +1,27 @@ |
| +# Census approval: region-ha-p3b2-rolls |
| + |
| +Ruling `census-ruling-region-ha-p3b2-rolls`. The independent reviewer approves or rejects every change below, 5 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/instancectl/server.go` `type Server` | body | unchanged (1) | adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read | |
| + |
| +Envelopes re-pinned: `internal/hairpin`, `internal/host`, `internal/instancectl`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/instancectl/server.go` `type Server`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority. |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/instancectl/hairpin.go:Client.GroupHairpin`: reads +file:ReadAll; written legacy, accepted-legacy, frozen |
| +- new `internal/instancectl/hairpin.go:newHairpinResetServer`: reads +file:CommandContext; written legacy, accepted-legacy, frozen |
| +- new `internal/instancectl/hairpin.go:var#1`: reads +file:Prepare; written legacy, accepted-legacy, frozen |
| +- quiet `internal/instancectl/hairpin.go:ClearGroupHairpin`: reads nothing now; retired while it reads nothing (or its row keeps no sites) |
| +- quiet `internal/instancectl/hairpin.go:InstallDormantGroupHairpin`: reads nothing now; retired while it reads nothing (or its row keeps no sites) |
| + |
| +Seal: `9bfd77d30d8e3deb5f3863cb6c272c2cb46ce32aa1370acbaa6e9181b71101b4` → `c55b4a022b3d42f40a05b727f93e57dc9f76b6dc2251f7d3b777c34d7ffdee09`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p3b2-rolls.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/hairpin/lifecycle.go b/internal/hairpin/lifecycle.go| index a617aaf20..c028b355a 100644 |
| --- a/internal/hairpin/lifecycle.go |
| +++ b/internal/hairpin/lifecycle.go |
| @@ -15,15 +15,13 @@ type Operations struct { |
| Verify func(context.Context) error |
| Addresses func(context.Context, bool) error |
| Exempt func(context.Context, bool) error |
| - Save func(bool) error |
| + Save func(active, closed bool) error |
| } |
| func (o Operations) Enable(ctx context.Context) (err error) { |
| defer func() { |
| if err != nil { |
| - cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) |
| - defer cancel() |
| - err = errors.Join(err, o.Disable(cleanup)) |
| + err = errors.Join(err, o.Rollback(ctx)) |
| } |
| }() |
| if err = o.Install(ctx); err != nil { |
| @@ -38,16 +36,35 @@ func (o Operations) Enable(ctx context.Context) (err error) { |
| if err = o.Exempt(ctx, true); err != nil { |
| return err |
| } |
| - return o.Save(true) |
| + return o.Save(true, false) |
| } |
| // The dormant fence stays installed. Removal of a fence is reserved for root |
| // reseeding under maintenance, after removal of all addresses and exemptions. |
| // Even a failed address removal attempts to restore the full #367 deny. |
| -func (o Operations) Disable(ctx context.Context) error { |
| - saved := o.Save(false) |
| +// Revocation invariant: a live process is tombstoned only by an act of |
| +// revocation: explicit disable, maintenance clear, exit cleanup, or a genuine |
| +// non-context readback failure of an active exemption. Only Revoke grants that |
| +// authority; all other deactivation uses Rollback and leaves retries open. |
| +func (o Operations) Revoke(ctx context.Context) error { |
| + return o.deactivate(ctx, true) |
| +} |
| + |
| +func (o Operations) Rollback(ctx context.Context) error { |
| + return o.deactivate(ctx, false) |
| +} |
| + |
| +func (o Operations) deactivate(ctx context.Context, closed bool) error { |
| + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) |
| + defer cancel() |
| + saved := o.Save(false, closed) |
| removed := o.Addresses(ctx, false) |
| denied := o.Exempt(ctx, false) |
| + if saved != nil { |
| + // A transient write failure must not leave the preceding active state |
| + // on disk for the next lease or a restarted control service to adopt. |
| + saved = errors.Join(saved, o.Save(false, closed)) |
| + } |
| return errors.Join(saved, removed, denied) |
| } |
diff --git a/internal/hairpin/lifecycle_test.go b/internal/hairpin/lifecycle_test.go| index 38af57d86..d90eed02b 100644 |
| --- a/internal/hairpin/lifecycle_test.go |
| +++ b/internal/hairpin/lifecycle_test.go |
| @@ -3,8 +3,10 @@ package hairpin |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "reflect" |
| "testing" |
| + "time" |
| ) |
| func TestHairpinAdmissionLifecycle(t *testing.T) { |
| @@ -19,6 +21,7 @@ func TestHairpinAdmissionLifecycle(t *testing.T) { |
| return nil |
| } |
| fence, addresses, exempt := false, false, false |
| + var savedActive, savedClosed bool |
| ops := Operations{ |
| Install: func(context.Context) error { |
| err := op("install") |
| @@ -61,7 +64,8 @@ func TestHairpinAdmissionLifecycle(t *testing.T) { |
| } |
| return err |
| }, |
| - Save: func(on bool) error { |
| + Save: func(on, closed bool) error { |
| + savedActive, savedClosed = on, closed |
| n := "save-off" |
| if on { |
| n = "save-on" |
| @@ -78,22 +82,78 @@ func TestHairpinAdmissionLifecycle(t *testing.T) { |
| t.Fatal(calls) |
| } |
| calls = nil |
| - if err := ops.Disable(context.Background()); err != nil { |
| + if err := ops.Revoke(context.Background()); err != nil { |
| t.Fatal(err) |
| } |
| + if savedActive || !savedClosed { |
| + t.Fatal("disable did not tombstone") |
| + } |
| if !reflect.DeepEqual(calls, []string{"save-off", "addresses-off", "exempt-off"}) { |
| t.Fatal(calls) |
| } |
| - } else if err == nil || addresses || exempt { |
| + } else if err == nil || addresses || exempt || savedActive || savedClosed { |
| t.Fatalf("rollback: %v %v addresses=%v exempt=%v", err, calls, addresses, exempt) |
| } |
| }) |
| } |
| t.Run("failed-removal-keeps-fence-and-restores-deny", func(t *testing.T) { |
| var calls []string |
| - ops := Operations{Save: func(bool) error { calls = append(calls, "save"); return nil }, Addresses: func(context.Context, bool) error { calls = append(calls, "remove"); return errors.New("ip") }, Exempt: func(context.Context, bool) error { calls = append(calls, "deny"); return nil }} |
| - if ops.Disable(context.Background()) == nil || !reflect.DeepEqual(calls, []string{"save", "remove", "deny"}) { |
| + ops := Operations{Save: func(bool, bool) error { calls = append(calls, "save"); return nil }, Addresses: func(context.Context, bool) error { calls = append(calls, "remove"); return errors.New("ip") }, Exempt: func(context.Context, bool) error { calls = append(calls, "deny"); return nil }} |
| + if ops.Revoke(context.Background()) == nil || !reflect.DeepEqual(calls, []string{"save", "remove", "deny"}) { |
| t.Fatal(calls) |
| } |
| }) |
| } |
| + |
| +func TestHairpinDeactivationDetached(t *testing.T) { |
| + for _, revoke := range []bool{false, true} { |
| + for _, expired := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("revoke=%v/expired=%v", revoke, expired), func(t *testing.T) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + if expired { |
| + cancel() |
| + ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) |
| + } |
| + cancel() |
| + var calls []string |
| + cleanup := func(ctx context.Context, name string) error { |
| + deadline, ok := ctx.Deadline() |
| + if ctx.Err() != nil || !ok || time.Until(deadline) > 15*time.Second { |
| + t.Fatalf("cleanup context: %v %v", ctx.Err(), deadline) |
| + } |
| + calls = append(calls, name) |
| + return nil |
| + } |
| + ops := Operations{ |
| + Save: func(active, closed bool) error { |
| + if active || closed != revoke { |
| + t.Fatal(active, closed) |
| + } |
| + return errors.New("save") |
| + }, |
| + Addresses: func(ctx context.Context, on bool) error { |
| + if on { |
| + t.Fatal("add") |
| + } |
| + return cleanup(ctx, "remove") |
| + }, |
| + Exempt: func(ctx context.Context, on bool) error { |
| + if on { |
| + t.Fatal("exempt") |
| + } |
| + return cleanup(ctx, "deny") |
| + }, |
| + } |
| + var err error |
| + if revoke { |
| + err = ops.Revoke(ctx) |
| + } else { |
| + err = ops.Rollback(ctx) |
| + } |
| + if err == nil || !reflect.DeepEqual(calls, []string{"remove", "deny"}) { |
| + t.Fatal(err, calls) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go| index 149c11192..ced0d9a05 100644 |
| --- a/internal/host/group_admission.go |
| +++ b/internal/host/group_admission.go |
| @@ -23,7 +23,9 @@ import ( |
| var armedFixedAdmission atomic.Pointer[fixedAdmission] |
| type fixedAdmission struct { |
| + hairpinRetryState |
| hairpin func(bool) error |
| + hairpinCancel context.CancelFunc |
| hairpinMu sync.Mutex |
| hairpinReady atomic.Bool |
| launchFailure string |
| @@ -145,7 +147,11 @@ func (a *fixedAdmission) tick(ctx context.Context) { |
| } |
| } |
| if a.state.Admitted() { |
| + retry := a.hairpin != nil && !a.hairpinReady.Load() |
| a.mu.Unlock() |
| + if retry { |
| + a.enableGroupHairpin() |
| + } |
| return |
| } |
| if !a.state.Ready() || !a.known || (a.group && (a.launch == nil || a.completer == nil || a.role != boxroles.Serve)) { |
| @@ -153,30 +159,25 @@ func (a *fixedAdmission) tick(ctx context.Context) { |
| a.mu.Unlock() |
| return |
| } |
| - a.health.SetHosting(true) |
| + if a.hairpin == nil { |
| + a.health.SetHosting(true) |
| + } |
| launch, complete := a.launch, a.completer |
| a.mu.Unlock() |
| // No orchestration lock spans the provider call. Close can win immediately. |
| if err := a.state.Admit(ctx, launch, complete, a.initialHealthy); err == nil { |
| - a.hairpinMu.Lock() |
| - a.mu.Lock() |
| - closed, change := a.closed, a.hairpin |
| - a.mu.Unlock() |
| - var hairpinErr error |
| - if !closed && change != nil { |
| - hairpinErr = change(true) |
| + if a.hairpin != nil { |
| + a.enableGroupHairpin() |
| + return |
| } |
| + a.hairpinMu.Lock() |
| a.mu.Lock() |
| - if !a.closed && hairpinErr == nil { |
| + if !a.closed { |
| a.hairpinReady.Store(true) |
| a.openOnce.Do(func() { close(a.opened); log.Print("tenant admission is open. accepting tenant work") }) |
| } |
| a.mu.Unlock() |
| a.hairpinMu.Unlock() |
| - if hairpinErr != nil { |
| - log.Printf("group hairpin activation failed: %v", hairpinErr) |
| - a.Close() |
| - } |
| } else { |
| a.mu.Lock() |
| if a.group && !errors.Is(err, groupadmission.ErrNotReady) { |
| @@ -191,7 +192,18 @@ func (a *fixedAdmission) tick(ctx context.Context) { |
| } |
| } |
| func (a *fixedAdmission) initialHealthy() bool { |
| - return a.allowed.Load() && a.groupReadersReady(time.Now()) && len(a.health.Failing(time.Now())) == 0 |
| + now := a.admissionNow() |
| + if !a.allowed.Load() || !a.groupReadersReady(now) { |
| + return false |
| + } |
| + for _, failure := range a.health.Failing(now) { |
| + // Hosting stays false until root enables hairpin. It is the result |
| + // of this check, not a prerequisite for the first enable or a retry. |
| + if failure != lbhealth.CondHosting || a.hairpin == nil { |
| + return false |
| + } |
| + } |
| + return true |
| } |
| func (a *fixedAdmission) Close() { |
| if a == nil { |
| @@ -212,6 +224,9 @@ func (a *fixedAdmission) Close() { |
| a.workCancel() |
| } |
| a.workMu.Unlock() |
| + if a.hairpinCancel != nil { |
| + a.hairpinCancel() |
| + } |
| a.hairpinMu.Lock() |
| if a.hairpin != nil { |
| if err := a.hairpin(false); err != nil { |
| @@ -337,8 +352,14 @@ func (a *fixedAdmission) logWaitingLocked(now time.Time) { |
| missing = append(missing, "GroupReadersReady") |
| } |
| for _, failure := range a.health.Failing(now) { |
| + if failure == lbhealth.CondHosting && a.hairpin != nil { |
| + continue |
| + } |
| missing = append(missing, string(failure)) |
| } |
| + if a.hairpin != nil && !a.hairpinReady.Load() { |
| + missing = append(missing, groupHairpinWaitText) |
| + } |
| log.Printf("tenant admission is still closed. waiting for: %s", strings.Join(missing, ", ")) |
| } |
diff --git a/internal/host/group_hairpin.go b/internal/host/group_hairpin.go| index ea3ad27dc..893d07b8e 100644 |
| --- a/internal/host/group_hairpin.go |
| +++ b/internal/host/group_hairpin.go |
| @@ -37,18 +37,30 @@ func configureGroupHairpin(a *fixedAdmission) error { |
| if err != nil { |
| return err |
| } |
| - client := instancectl.NewClient(controlsock.Path) |
| + configureGroupHairpinClient(a, instancectl.NewClient(controlsock.Path), p) |
| + return nil |
| +} |
| + |
| +func configureGroupHairpinClient(a *fixedAdmission, client *instancectl.Client, p hairpin.Process) { |
| + enableCtx, cancelEnable := context.WithCancel(context.Background()) |
| + a.hairpinCancel = cancelEnable |
| a.hairpin = func(enable bool) error { |
| - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + parent := context.Background() |
| + if enable { |
| + parent = enableCtx |
| + } |
| + ctx, cancel := context.WithTimeout(parent, 60*time.Second) |
| defer cancel() |
| return client.GroupHairpin(ctx, enable, p) |
| } |
| - return nil |
| } |
| // Task 4 calls this only after consuming its root maintenance permit, before |
| // any edge stop or replacement. Staging trees have no live host interfaces. |
| func (a *systemApplier) clearGroupHairpin() error { |
| + if g := a.groupMaintenance; g != nil && g.clearHairpin != nil { |
| + return g.clearHairpin() |
| + } |
| if a.etcDir != "/etc" { |
| return nil |
| } |
diff --git a/internal/host/group_hairpin_retry.go b/internal/host/group_hairpin_retry.go| new file mode 100644 |
| index 000000000..4bb87e40a |
| --- /dev/null |
| +++ b/internal/host/group_hairpin_retry.go |
| @@ -0,0 +1,141 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| + "github.com/carlosframework/platform/internal/boxroles" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| +) |
| + |
| +const ( |
| + groupHairpinRetryFirst = 10 * time.Second |
| + groupHairpinRetryCap = 5 * time.Minute |
| + groupHairpinAlertAfter = 15 * time.Minute |
| +) |
| + |
| +// Operator text stays together for the controller's copy pass. |
| +const ( |
| + groupHairpinWaitText = "hairpin" |
| + groupHairpinRetryFailureText = "group hairpin activation failed: code=%s; retry in %s" |
| + groupHairpinAlertSubjectText = "Group hairpin enable needs attention" |
| + groupHairpinAlertBodyText = "Box %s could not enable hairpin. Failure code: %s. Admission remains closed after 15 minutes. Local retries continue." |
| + groupHairpinClearSubjectText = "Group hairpin enable recovered" |
| + groupHairpinClearBodyText = "Box %s enabled hairpin and opened admission. Previous failure code: %s." |
| + groupHairpinPageFailureText = "group hairpin alert delivery failed: %v" |
| +) |
| + |
| +// Retry and alert fields are protected by fixedAdmission.mu. The clock is |
| +// installed before ticks start; production uses time.Now. |
| +type hairpinRetryState struct { |
| + clock func() time.Time |
| + hairpinNext time.Time |
| + hairpinDelay time.Duration |
| + hairpinFailedAt time.Time |
| + hairpinCode string |
| + hairpinAlerted bool |
| + hairpinAlertDone chan struct{} |
| +} |
| + |
| +func (a *fixedAdmission) admissionNow() time.Time { |
| + if a.clock != nil { |
| + return a.clock() |
| + } |
| + return time.Now() |
| +} |
| + |
| +func (a *fixedAdmission) enableGroupHairpin() { |
| + a.hairpinMu.Lock() |
| + defer a.hairpinMu.Unlock() |
| + a.mu.Lock() |
| + if a.closed || a.refusal != "" || !a.state.Admitted() || a.hairpinReady.Load() { |
| + a.mu.Unlock() |
| + return |
| + } |
| + a.health.SetHosting(false) |
| + now := a.admissionNow() |
| + if !a.hairpinFailedAt.IsZero() && !a.hairpinAlerted && now.Sub(a.hairpinFailedAt) >= groupHairpinAlertAfter { |
| + a.hairpinAlerted = true |
| + a.pageHairpinLocked(false) |
| + } |
| + if now.Before(a.hairpinNext) || !a.known || a.role != boxroles.Serve || !a.initialHealthy() { |
| + a.logWaitingLocked(now) |
| + a.mu.Unlock() |
| + return |
| + } |
| + change := a.hairpin |
| + a.mu.Unlock() |
| + err := change(true) |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + // Close publishes its refusal before waiting for hairpinMu, then calls |
| + // change(false). A completed enable must never reopen that gate. |
| + if a.closed { |
| + return |
| + } |
| + if err != nil { |
| + now = a.admissionNow() |
| + if a.hairpinFailedAt.IsZero() { |
| + a.hairpinFailedAt = now |
| + } |
| + a.hairpinCode = groupHairpinFailureCode(err) |
| + if a.hairpinDelay == 0 { |
| + a.hairpinDelay = groupHairpinRetryFirst |
| + } else { |
| + a.hairpinDelay = min(a.hairpinDelay*2, groupHairpinRetryCap) |
| + } |
| + a.hairpinNext = now.Add(a.hairpinDelay) |
| + log.Printf(groupHairpinRetryFailureText, a.hairpinCode, a.hairpinDelay) |
| + return |
| + } |
| + a.hairpinReady.Store(true) |
| + a.health.SetHosting(true) |
| + a.openOnce.Do(func() { close(a.opened); log.Print("tenant admission is open. accepting tenant work") }) |
| + if a.hairpinAlerted { |
| + a.pageHairpinLocked(true) |
| + } |
| + a.hairpinNext = time.Time{} |
| + a.hairpinDelay = 0 |
| + a.hairpinFailedAt = time.Time{} |
| + a.hairpinCode = "" |
| + a.hairpinAlerted = false |
| +} |
| + |
| +func groupHairpinFailureCode(err error) string { |
| + var refusal *instancectl.GroupHairpinError |
| + if errors.As(err, &refusal) { |
| + switch refusal.Code { |
| + case "group_hairpin_closed", "group_hairpin_peer", "group_hairpin_request", "group_hairpin_unavailable": |
| + return refusal.Code |
| + } |
| + } |
| + return "group_hairpin_unavailable" |
| +} |
| + |
| +// Like metrics alerts, send only a firing or clearing transition. PageOperator |
| +// has no resolve API, so recovery is a second page. Preserve their order even |
| +// when a sink is slow, without blocking admission or adding a polling loop. |
| +func (a *fixedAdmission) pageHairpinLocked(clear bool) { |
| + subject, body := groupHairpinAlertSubjectText, groupHairpinAlertBodyText |
| + if clear { |
| + subject, body = groupHairpinClearSubjectText, groupHairpinClearBodyText |
| + } |
| + body = fmt.Sprintf(body, a.readerSelf, a.hairpinCode) |
| + previous, done := a.hairpinAlertDone, make(chan struct{}) |
| + a.hairpinAlertDone = done |
| + go func() { |
| + defer close(done) |
| + if previous != nil { |
| + <-previous |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| + defer cancel() |
| + if err := PageOperator(ctx, alerting.LevelWarning, subject, body); err != nil { |
| + log.Printf(groupHairpinPageFailureText, err) |
| + } |
| + }() |
| +} |
diff --git a/internal/host/group_hairpin_retry_test.go b/internal/host/group_hairpin_retry_test.go| new file mode 100644 |
| index 000000000..b41fffc1f |
| --- /dev/null |
| +++ b/internal/host/group_hairpin_retry_test.go |
| @@ -0,0 +1,506 @@ |
| +package host |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "slices" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxroles" |
| + "github.com/carlosframework/platform/internal/edgesfile" |
| + "github.com/carlosframework/platform/internal/groupadmission" |
| + "github.com/carlosframework/platform/internal/hairpin" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lbhealth" |
| +) |
| + |
| +func TestGroupHairpinAdmissionFailureDoesNotClose(t *testing.T) { |
| + a := readyGroupAdmission(t) |
| + a.observe(groupadmission.Facts{TerminationStarted: true}) |
| + work, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + a.workCtx, a.workCancel = work, cancel |
| + var disables int |
| + a.hairpin = func(on bool) error { |
| + if !on { |
| + disables++ |
| + } |
| + return &instancectl.GroupHairpinError{StatusCode: 503, Code: "group_hairpin_unavailable"} |
| + } |
| + a.tick(t.Context()) |
| + if a.closed || !a.state.Admitted() { |
| + t.Fatal("hairpin failure latched shutdown instead of retaining launch completion for retry") |
| + } |
| + if a.TenantAdmitted() || a.startAllowed() || a.health.Hosting() { |
| + t.Fatal("hairpin failure opened admission or reported hosting") |
| + } |
| + if disables != 0 || work.Err() != nil { |
| + t.Fatal("hairpin failure disabled root hairpin or cancelled work") |
| + } |
| +} |
| + |
| +type hairpinRetryFixture struct { |
| + a *fixedAdmission |
| + base time.Time |
| + stamp atomic.Int64 |
| + readers atomic.Bool |
| +} |
| + |
| +func newHairpinRetryFixture(t *testing.T) *hairpinRetryFixture { |
| + t.Helper() |
| + f := &hairpinRetryFixture{a: readyGroupAdmission(t), base: time.Unix(1800000000, 0)} |
| + f.readers.Store(true) |
| + f.a.clock = func() time.Time { return time.Unix(0, f.stamp.Load()) } |
| + f.a.readers = func() edgesfile.ReaderSnapshot { |
| + return edgesfile.ReaderSnapshot{Complete: f.readers.Load(), CheckedAt: f.a.clock().Add(-time.Second), Self: "self", KnownReaders: []string{}} |
| + } |
| + f.a.observe(groupadmission.Facts{TerminationStarted: true}) |
| + f.at(0) |
| + t.Cleanup(func() { |
| + f.a.mu.Lock() |
| + done := f.a.hairpinAlertDone |
| + f.a.mu.Unlock() |
| + if done != nil { |
| + <-done |
| + } |
| + }) |
| + return f |
| +} |
| + |
| +func (f *hairpinRetryFixture) at(elapsed time.Duration) { |
| + now := f.base.Add(elapsed) |
| + f.stamp.Store(now.UnixNano()) |
| + f.a.health.EdgeBeat(now) |
| + f.a.health.RefreshAttempted(now) |
| + f.a.health.SetActivator(f.a.clock) |
| +} |
| + |
| +func assertHairpinWaiting(t *testing.T, a *fixedAdmission) { |
| + t.Helper() |
| + if a.TenantAdmitted() || a.startAllowed() || a.health.Hosting() || a.hairpinReady.Load() { |
| + t.Fatal("tenant admission, starts or health opened before hairpin") |
| + } |
| + if role, admitted, _ := a.EdgesRole(); role != boxroles.Booting || admitted { |
| + t.Fatal("waiting member advertised as serving") |
| + } |
| + select { |
| + case <-a.opened: |
| + t.Fatal("open notification sent before hairpin") |
| + default: |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionRetrySuccess(t *testing.T) { |
| + f := newHairpinRetryFixture(t) |
| + a := f.a |
| + var output bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&output) |
| + defer log.SetOutput(old) |
| + completions, attempts := 0, 0 |
| + a.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error { |
| + completions++ |
| + assertHairpinWaiting(t, a) |
| + return nil |
| + }) |
| + a.hairpin = func(on bool) error { |
| + if !on || completions != 1 { |
| + t.Fatal("hairpin called before launch completion, or disabled on failure") |
| + } |
| + assertHairpinWaiting(t, a) |
| + attempts++ |
| + if attempts == 1 { |
| + return fmt.Errorf("control: %w", &instancectl.GroupHairpinError{StatusCode: 403, Code: "group_hairpin_peer"}) |
| + } |
| + return nil |
| + } |
| + for _, step := range []struct { |
| + at time.Duration |
| + attempts int |
| + open bool |
| + }{{0, 1, false}, {9 * time.Second, 1, false}, {10 * time.Second, 2, true}, {time.Hour, 2, true}} { |
| + f.at(step.at) |
| + a.tick(t.Context()) |
| + if attempts != step.attempts || completions != 1 { |
| + t.Fatalf("at %s: attempts=%d completions=%d", step.at, attempts, completions) |
| + } |
| + if !step.open { |
| + assertHairpinWaiting(t, a) |
| + continue |
| + } |
| + if !a.TenantAdmitted() || !a.startAllowed() || len(a.health.Failing(a.clock())) != 0 { |
| + t.Fatal("successful retry did not restore admission and health") |
| + } |
| + select { |
| + case <-a.opened: |
| + default: |
| + t.Fatal("successful retry did not notify workers") |
| + } |
| + } |
| + if strings.Count(output.String(), "tenant admission is open.") != 1 || strings.Contains(output.String(), "closed for shutdown") || !strings.Contains(output.String(), "code=group_hairpin_peer") { |
| + t.Fatalf("wrong transition log: %s", output.String()) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionRetryBackoff(t *testing.T) { |
| + for _, failure := range []struct { |
| + name string |
| + err error |
| + }{ |
| + {"unavailable", &instancectl.GroupHairpinError{StatusCode: 503, Code: "group_hairpin_unavailable"}}, |
| + {"closed tombstone", &instancectl.GroupHairpinError{StatusCode: 409, Code: "group_hairpin_closed"}}, |
| + } { |
| + t.Run(failure.name, func(t *testing.T) { |
| + f := newHairpinRetryFixture(t) |
| + a := f.a |
| + attempts := 0 |
| + a.hairpin = func(on bool) error { |
| + if !on { |
| + t.Fatal("retry disabled hairpin") |
| + } |
| + assertHairpinWaiting(t, a) |
| + attempts++ |
| + return failure.err |
| + } |
| + a.tick(t.Context()) |
| + elapsed := time.Duration(0) |
| + for i, delay := range []time.Duration{10, 20, 40, 80, 160, 300, 300, 300, 300} { |
| + delay *= time.Second |
| + elapsed += delay |
| + f.at(elapsed - time.Nanosecond) |
| + a.tick(t.Context()) |
| + if attempts != i+1 { |
| + t.Fatalf("retry before %s: %d attempts", elapsed, attempts) |
| + } |
| + f.at(elapsed) |
| + a.tick(t.Context()) |
| + if attempts != i+2 || a.closed || !a.state.Admitted() { |
| + t.Fatalf("retry at %s: attempts=%d closed=%v", elapsed, attempts, a.closed) |
| + } |
| + assertHairpinWaiting(t, a) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionRetryPredicate(t *testing.T) { |
| + for _, missing := range []string{"allowed", "known", "role", "readers", "forwarding", "certificates", "edge", "activator", "refresh"} { |
| + t.Run(missing, func(t *testing.T) { |
| + f := newHairpinRetryFixture(t) |
| + a := f.a |
| + attempts := 0 |
| + a.hairpin = func(bool) error { |
| + attempts++ |
| + return errors.New("local failure") |
| + } |
| + a.tick(t.Context()) |
| + f.at(10 * time.Second) |
| + switch missing { |
| + case "allowed": |
| + a.allowed.Store(false) |
| + case "known": |
| + a.known = false |
| + case "role": |
| + a.role = boxroles.Drain |
| + case "readers": |
| + f.readers.Store(false) |
| + default: |
| + h := &lbhealth.State{} |
| + if missing != "forwarding" { |
| + h.MapLoaded() |
| + h.KeyLoaded() |
| + } |
| + if missing != "certificates" { |
| + h.CertsLoaded() |
| + } |
| + if missing != "edge" { |
| + h.EdgeBeat(a.clock()) |
| + } |
| + if missing != "activator" { |
| + h.SetActivator(a.clock) |
| + } |
| + if missing != "refresh" { |
| + h.RefreshAttempted(a.clock()) |
| + } |
| + a.health = h |
| + } |
| + a.tick(t.Context()) |
| + if attempts != 1 { |
| + t.Fatal("retry ignored opening predicate") |
| + } |
| + assertHairpinWaiting(t, a) |
| + // Recovery of the local predicate permits the pending attempt. |
| + a.health = admissionHealth() |
| + f.at(11 * time.Second) |
| + f.readers.Store(true) |
| + _ = a.applyRole(boxroles.Serve, true) |
| + a.tick(t.Context()) |
| + if attempts != 2 { |
| + t.Fatal("recovered predicate left retry stuck") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionAlertTransitions(t *testing.T) { |
| + for _, blocked := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("blocked sink %v", blocked), func(t *testing.T) { |
| + var pages []struct{ Kind, Level, Subject, Body string } |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + armPaging(newAlertSinks("http://example.test/hook", func(_ string, raw []byte) error { |
| + var p struct{ Kind, Level, Subject, Body string } |
| + if err := json.Unmarshal(raw, &p); err != nil { |
| + return err |
| + } |
| + pages = append(pages, p) |
| + if len(pages) == 1 { |
| + close(entered) |
| + <-release |
| + } |
| + return nil |
| + }, "", nil, nil)) |
| + t.Cleanup(func() { armPaging(nil) }) |
| + if !blocked { |
| + close(release) |
| + } |
| + f := newHairpinRetryFixture(t) |
| + a := f.a |
| + fail := true |
| + a.hairpin = func(bool) error { |
| + if fail { |
| + return &instancectl.GroupHairpinError{StatusCode: 409, Code: "group_hairpin_closed"} |
| + } |
| + return nil |
| + } |
| + for _, seconds := range []int{0, 10, 30, 70, 150, 310, 610, 899} { |
| + f.at(time.Duration(seconds) * time.Second) |
| + a.tick(t.Context()) |
| + if a.hairpinAlerted || a.hairpinAlertDone != nil { |
| + t.Fatal("alert before 15 minutes") |
| + } |
| + } |
| + f.at(15 * time.Minute) |
| + a.tick(t.Context()) |
| + <-entered |
| + fired := a.hairpinAlertDone |
| + for _, seconds := range []int{901, 910, 1210} { |
| + f.at(time.Duration(seconds) * time.Second) |
| + a.tick(t.Context()) |
| + if a.hairpinAlertDone != fired { |
| + t.Fatal("repeated firing page") |
| + } |
| + } |
| + fail = false |
| + f.at(1510 * time.Second) |
| + a.tick(t.Context()) |
| + if !a.TenantAdmitted() || a.hairpinAlerted || !a.hairpinFailedAt.IsZero() { |
| + t.Fatal("success did not clear failure state") |
| + } |
| + if blocked { |
| + close(release) |
| + } |
| + <-a.hairpinAlertDone |
| + if len(pages) != 2 || pages[0].Subject != groupHairpinAlertSubjectText || pages[1].Subject != groupHairpinClearSubjectText { |
| + t.Fatalf("unordered or missing transitions: %+v", pages) |
| + } |
| + for _, p := range pages { |
| + if p.Kind != "page" || p.Level != "warning" || !strings.Contains(p.Body, "self") || !strings.Contains(p.Body, "group_hairpin_closed") { |
| + t.Fatalf("missing box or failure code: %+v", p) |
| + } |
| + } |
| + f.at(time.Hour) |
| + a.tick(t.Context()) |
| + <-a.hairpinAlertDone |
| + if len(pages) != 2 { |
| + t.Fatal("duplicate recovery page") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionRetryClose(t *testing.T) { |
| + for _, phase := range []string{"backoff", "in flight"} { |
| + t.Run(phase, func(t *testing.T) { |
| + f := newHairpinRetryFixture(t) |
| + a := f.a |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + work, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + a.workCtx, a.workCancel = work, cancel |
| + var calls []bool |
| + a.hairpin = func(on bool) error { |
| + calls = append(calls, on) |
| + if len(calls) == 1 { |
| + return errors.New("local failure") |
| + } |
| + if on { |
| + close(entered) |
| + <-release |
| + } |
| + return nil |
| + } |
| + a.tick(t.Context()) |
| + want := []bool{true, false} |
| + if phase == "in flight" { |
| + want = []bool{true, true, false} |
| + f.at(10 * time.Second) |
| + ticked := make(chan struct{}) |
| + go func() { a.tick(t.Context()); close(ticked) }() |
| + <-entered |
| + closed := make(chan struct{}) |
| + go func() { a.Close(); close(closed) }() |
| + <-work.Done() |
| + assertHairpinWaiting(t, a) |
| + close(release) |
| + <-ticked |
| + <-closed |
| + } else { |
| + a.Close() |
| + } |
| + f.at(time.Hour) |
| + a.tick(t.Context()) |
| + assertHairpinWaiting(t, a) |
| + if !a.closed || a.state.Admitted() || !slices.Equal(calls, want) { |
| + t.Fatalf("close lost: closed=%v calls=%v", a.closed, calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionFixedUnchanged(t *testing.T) { |
| + for _, role := range []boxroles.Role{boxroles.Serve, boxroles.Drain, boxroles.Platform} { |
| + t.Run(string(role), func(t *testing.T) { |
| + a := newFixedAdmission(admissionEnv, admissionHealth()) |
| + _ = a.applyRole(role, true) |
| + a.observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true}) |
| + a.tick(t.Context()) |
| + a.tick(t.Context()) |
| + if !a.TenantAdmitted() || !a.health.Hosting() || a.startAllowed() != (role == boxroles.Serve) || a.hairpinAlertDone != nil { |
| + t.Fatal("fixed admission changed") |
| + } |
| + a.Close() |
| + a.tick(t.Context()) |
| + if a.TenantAdmitted() || a.health.Hosting() { |
| + t.Fatal("fixed box reopened after close") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionWaitingAfterAdmit(t *testing.T) { |
| + f := newHairpinRetryFixture(t) |
| + a := f.a |
| + a.hairpin = func(bool) error { t.Fatal("enable while readers unready"); return nil } |
| + if err := a.state.Admit(t.Context(), nil, nil, func() bool { return true }); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.readers.Store(false) |
| + var output bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&output) |
| + defer log.SetOutput(old) |
| + for _, step := range []struct { |
| + at time.Duration |
| + logs int |
| + }{{0, 1}, {59 * time.Second, 1}, {time.Minute, 2}} { |
| + f.at(step.at) |
| + a.tick(t.Context()) |
| + if got := strings.Count(output.String(), "tenant admission is still closed."); got != step.logs { |
| + t.Fatalf("at %s: logs=%d want %d: %s", step.at, got, step.logs, output.String()) |
| + } |
| + if !strings.Contains(output.String(), "GroupReadersReady") || !strings.Contains(output.String(), "hairpin") || strings.Contains(output.String(), "hosting") { |
| + t.Fatalf("wrong waits: %s", output.String()) |
| + } |
| + if !a.hairpinFailedAt.IsZero() { |
| + t.Fatal("predicate failure counted as enable failure") |
| + } |
| + assertHairpinWaiting(t, a) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionWaitingNamesRealGate(t *testing.T) { |
| + for _, group := range []bool{false, true} { |
| + t.Run(fmt.Sprint(group), func(t *testing.T) { |
| + a := newFixedAdmission(admissionEnv, admissionHealth()) |
| + if group { |
| + a.hairpin = func(bool) error { return nil } |
| + a.group = true |
| + } |
| + var output bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&output) |
| + defer log.SetOutput(old) |
| + a.tick(t.Context()) |
| + if strings.Contains(output.String(), "hosting") == group || strings.Contains(output.String(), "hairpin") != group { |
| + t.Fatalf("wrong gate: %s", output.String()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinAdmissionCloseCancelsEnableBeforeDisable(t *testing.T) { |
| + f := newHairpinRetryFixture(t) |
| + a := f.a |
| + entered, disabled := make(chan struct{}), make(chan struct{}) |
| + client := &instancectl.Client{Dial: func(context.Context, string) (net.Conn, error) { |
| + local, remote := net.Pipe() |
| + done := make(chan struct{}) |
| + t.Cleanup(func() { local.Close(); remote.Close(); <-done }) |
| + go func() { |
| + defer close(done) |
| + defer remote.Close() |
| + r, err := http.ReadRequest(bufio.NewReader(remote)) |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + var req struct{ Enable bool } |
| + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + r.Body.Close() |
| + if req.Enable { |
| + close(entered) |
| + io.Copy(io.Discard, remote) |
| + return |
| + } |
| + close(disabled) |
| + fmt.Fprint(remote, "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n") |
| + }() |
| + return local, nil |
| + }} |
| + configureGroupHairpinClient(a, client, hairpin.Process{PID: 1, Start: "1", Boot: "fixture"}) |
| + defer a.hairpinCancel() |
| + ticked := make(chan struct{}) |
| + go func() { a.tick(t.Context()); close(ticked) }() |
| + <-entered |
| + closed := make(chan struct{}) |
| + go func() { a.Close(); close(closed) }() |
| + select { |
| + case <-closed: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("Close waited for the enable deadline instead of cancelling it") |
| + } |
| + <-ticked |
| + select { |
| + case <-disabled: |
| + default: |
| + t.Fatal("Close did not attempt disable with a fresh context") |
| + } |
| + assertHairpinWaiting(t, a) |
| + if !a.closed { |
| + t.Fatal("Close reopened admission") |
| + } |
| +} |
diff --git a/internal/host/group_hairpin_rootrunner_linux_test.go b/internal/host/group_hairpin_rootrunner_linux_test.go| index f30e4d5ac..932b1147a 100644 |
| --- a/internal/host/group_hairpin_rootrunner_linux_test.go |
| +++ b/internal/host/group_hairpin_rootrunner_linux_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "context" |
| "crypto/rand" |
| "crypto/rsa" |
| + "crypto/sha256" |
| "crypto/tls" |
| "crypto/x509" |
| "crypto/x509/pkix" |
| @@ -21,6 +22,7 @@ import ( |
| "net" |
| "net/http" |
| "net/netip" |
| + "net/url" |
| "os" |
| "os/exec" |
| "path/filepath" |
| @@ -40,7 +42,9 @@ import ( |
| "golang.org/x/sys/unix" |
| ) |
| -func TestHairpinKernelAgentTenantSidecar(t *testing.T) { hairpinKernelWitness(t) } |
| +func TestHairpinKernelAgentTenantSidecar(t *testing.T) { hairpinKernelWitness(t, false) } |
| + |
| +func TestGroupHairpinMaintenanceRestart(t *testing.T) { hairpinKernelWitness(t, true) } |
| // This witness permits IMDSv2 reads and traffic only to its own fixture. The |
| // public-shaped EIPs have blackhole fallback routes, so closed-state probes |
| @@ -48,7 +52,7 @@ func TestHairpinKernelAgentTenantSidecar(t *testing.T) { hairpinKernelWitness(t) |
| // than skips when root, systemd, nft or cgroup v2 is missing. The agent process |
| // uses production edge, admission and authenticated root operations; lifecycle |
| // completion and the app backend are local fixtures, with no ASG/S3/SSM calls. |
| -func hairpinKernelWitness(t *testing.T) { |
| +func hairpinKernelWitness(t *testing.T, maintenance bool) { |
| egressRootPrereqs(t) |
| for _, tool := range []string{"nft", "ip", "ss", "systemctl"} { |
| if _, err := exec.LookPath(tool); err != nil { |
| @@ -248,7 +252,12 @@ func hairpinKernelWitness(t *testing.T) { |
| hairpinRunnerUnit(t, agentUnit, unit) |
| hairpinCmd(t, "systemctl", "start", agentUnit) |
| control := hairpinAgentClient() |
| + t.Cleanup(control.CloseIdleConnections) |
| hairpinAgentWait(t, control) |
| + if maintenance { |
| + hairpinMaintenanceRestart(t, control, scratch) |
| + return |
| + } |
| pid, err := strconv.Atoi(egressShow(t, agentUnit, "MainPID")) |
| if err != nil { |
| t.Fatal(err) |
| @@ -367,6 +376,155 @@ func hairpinKernelWitness(t *testing.T) { |
| t.Log("PASS: agent, root, tenant, sidecar and rootfs; both EIPs; HTTP/TLS/POST/upgrade; actual listeners fenced; metadata/private/UDP denied for sandbox callers; closure and replacement") |
| } |
| +func hairpinMaintenanceRestart(t *testing.T, control *http.Client, scratch string) { |
| + t.Helper() |
| + if err := os.Mkdir(groupMaintenanceDir, 0700); err != nil { |
| + t.Fatal("fixture maintenance directory must not exist", err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(groupMaintenanceDir) }) |
| + artifact := []byte("maintenance fixture artifact") |
| + if err := os.WriteFile(systemBinaryPath(scratch), artifact, 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + a := &systemApplier{etcDir: "/etc", optDir: scratch, ops: productionSysOps()} |
| + c, err := a.maintenanceConfig() |
| + if err != nil || c == nil { |
| + t.Fatal("real maintenance marker", err) |
| + } |
| + digest := fmt.Sprintf("%x", sha256.Sum256(artifact)) |
| + p := groupMaintenancePermit{V: 1, Account: c.Account, Region: c.AWSRegion, Group: c.Group, Instance: c.InstanceID, BootID: c.BootID, ConfigDigest: c.ConfigDigest, Transaction: "hairpin-restart", Phase: "mutation", Action: "apply", OldSHA256: digest, NewSHA256: digest, Expires: time.Now().Add(time.Hour).Unix(), AllowRollback: true} |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(groupMaintenanceDir, "permit.json"), raw, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + identity := func() hairpin.Process { |
| + t.Helper() |
| + p, err := hairpin.MainProcess(t.Context()) |
| + if err != nil || p.PID == 0 { |
| + t.Fatal("agent MainPID", p, err) |
| + } |
| + return p |
| + } |
| + assertState := func(p hairpin.Process, active bool) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) |
| + defer cancel() |
| + l, err := hairpin.Acquire(ctx) |
| + if err != nil || l == nil { |
| + t.Fatal("state readback", err) |
| + } |
| + defer l.Close() |
| + if l.State.Process != p || l.State.Active != active || l.State.Closed == active { |
| + t.Fatalf("state=%+v want process=%+v active=%v closed=%v", l.State, p, active, !active) |
| + } |
| + if err := l.CheckAddresses(ctx, active); err != nil { |
| + t.Fatal("EIP readback", err) |
| + } |
| + } |
| + refused := func(p hairpin.Process, status int, code string) { |
| + t.Helper() |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := control.Get("http://fixture/hairpin-enable?process=" + url.QueryEscape(string(raw))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + body, err := io.ReadAll(resp.Body) |
| + if err != nil || resp.StatusCode != status || strings.TrimSpace(string(body)) != code { |
| + t.Fatalf("enable refusal: status=%d body=%s err=%v; want %d %s", resp.StatusCode, body, err, status, code) |
| + } |
| + } |
| + |
| + p1 := identity() |
| + arpPath := "/proc/sys/net/ipv4/conf/all/arp_ignore" |
| + if err := os.WriteFile(arpPath, []byte("0"), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.WriteFile(arpPath, []byte("1"), 0644) }) |
| + refused(p1, http.StatusServiceUnavailable, "group_hairpin_unavailable") |
| + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) |
| + defer cancel() |
| + l, err := hairpin.Acquire(ctx) |
| + if err != nil || l == nil { |
| + t.Fatal("failed enable state", err) |
| + } |
| + failedState := l.State |
| + addressErr := l.CheckAddresses(ctx, false) |
| + l.Close() |
| + if failedState != (hairpin.State{Process: p1}) || addressErr != nil { |
| + t.Fatal("failed enable did not roll back to retryable state", failedState, addressErr) |
| + } |
| + if err := os.WriteFile(arpPath, []byte("1"), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + refused(p1, http.StatusOK, "") |
| + assertState(p1, true) |
| + hairpinAgentCall(t, control, "/admit") |
| + assertState(p1, true) |
| + if err := a.requireGroupMaintenance("apply"); err != nil { |
| + t.Fatal("first consumption", err) |
| + } |
| + assertState(p1, false) |
| + if err := a.restartEdge(); err != nil { |
| + t.Fatal("guarded restart", err) |
| + } |
| + hairpinAgentWait(t, control) |
| + p2 := identity() |
| + if p2 == p1 { |
| + t.Fatal("restart did not replace agent", p1) |
| + } |
| + // restartRelay, activationGuard and arm all use this exact guard call. |
| + for range 3 { |
| + if err := a.requireGroupMaintenance("apply", "rollback"); err != nil { |
| + t.Fatal("successor guard", err) |
| + } |
| + } |
| + hairpinAgentCall(t, control, "/admit") |
| + assertState(p2, true) |
| + refused(p1, http.StatusForbidden, "group_hairpin_peer") |
| + assertState(p2, true) |
| + |
| + // A failed forward gate consumes rollback before stopping P2. This first |
| + // consumption must still close P2, including its future enable requests. |
| + if err := a.requireGroupMaintenance("rollback"); err != nil { |
| + t.Fatal("first rollback consumption", err) |
| + } |
| + assertState(p2, false) |
| + refused(p2, http.StatusConflict, "group_hairpin_closed") |
| + for deadline := time.Now().Add(5 * time.Second); ; { |
| + journal := egressJournal("carlos-instance-control.service") |
| + if strings.Contains(journal, fmt.Sprintf("step=closed code=group_hairpin_closed status=409: pid=%d:", p2.PID)) { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("closed refusal did not log the process", journal) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + if err := a.restartEdge(); err != nil { |
| + t.Fatal("rollback restart", err) |
| + } |
| + hairpinAgentWait(t, control) |
| + p3 := identity() |
| + if p3 == p2 || p3 == p1 { |
| + t.Fatal("rollback did not replace agent", p3) |
| + } |
| + for range 3 { |
| + if err := a.requireGroupMaintenance("apply", "rollback"); err != nil { |
| + t.Fatal("rollback successor guard", err) |
| + } |
| + } |
| + hairpinAgentCall(t, control, "/admit") |
| + assertState(p3, true) |
| + t.Logf("guarded apply and rollback admitted successors: P1=%+v P2=%+v P3=%+v", p1, p2, p3) |
| +} |
| + |
| func hairpinCmd(t *testing.T, args ...string) string { |
| t.Helper() |
| ctx, cancel := context.WithTimeout(t.Context(), 70*time.Second) |
| @@ -622,6 +780,26 @@ func TestHairpinAgentPayload(t *testing.T) { |
| h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| switch r.URL.Path { |
| case "/ping": |
| + case "/hairpin-enable": |
| + var p hairpin.Process |
| + if err := json.Unmarshal([]byte(r.URL.Query().Get("process")), &p); err != nil { |
| + http.Error(w, "invalid fixture identity", 400) |
| + return |
| + } |
| + err := instancectl.NewClient(controlsock.Path).GroupHairpin(r.Context(), true, p) |
| + if err != nil { |
| + var failure *instancectl.GroupHairpinError |
| + if errors.As(err, &failure) { |
| + if failure.Code == "group_hairpin_closed" && !errors.Is(err, instancectl.ErrGroupHairpinClosed) { |
| + http.Error(w, "closed sentinel missing", 500) |
| + return |
| + } |
| + http.Error(w, failure.Code, failure.StatusCode) |
| + } else { |
| + http.Error(w, err.Error(), 500) |
| + } |
| + return |
| + } |
| case "/admit": |
| admission.tick(context.Background()) |
| if !admission.startAllowed() { |
| @@ -1011,11 +1189,11 @@ func TestHairpinRollbackPayload(t *testing.T) { |
| return err |
| } |
| injected := errors.New("injected post-assignment save failure") |
| - ops := hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses, Exempt: plainDeny, Save: func(on bool) error { |
| + ops := hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses, Exempt: plainDeny, Save: func(on, closed bool) error { |
| if on { |
| return injected |
| } |
| - return l.Save(hairpin.State{Process: l.State.Process, Closed: true}) |
| + return l.Save(hairpin.State{Process: l.State.Process, Closed: closed}) |
| }} |
| rollbackErr := ops.Enable(ctx) |
| l.Close() |
diff --git a/internal/host/group_maintenance.go b/internal/host/group_maintenance.go| index 081506c8b..15b5cfe21 100644 |
| --- a/internal/host/group_maintenance.go |
| +++ b/internal/host/group_maintenance.go |
| @@ -48,7 +48,10 @@ type groupMaintenance struct { |
| read func(string, int, os.FileMode) ([]byte, error) |
| permit *groupMaintenancePermit |
| used map[string]bool |
| + cleared map[string]bool |
| initial bool |
| + // Tests can count clears without changing the host's network state. |
| + clearHairpin func() error |
| } |
| func (a *systemApplier) maintenance() *groupMaintenance { |
| @@ -116,18 +119,29 @@ func (a *systemApplier) requireGroupMaintenance(action string, alternatives ...s |
| if action == "check" { |
| return a.maintenanceUnconsumed(p) |
| } |
| - if g.used[action] { |
| - return a.clearGroupHairpin() |
| + if g.used[action] && g.cleared[action] { |
| + return nil |
| } |
| - if err := consumeGroupAction(g.dir, "used-"+p.Transaction+"-"+action, g.owner); err != nil { |
| - return errors.Join(errGroupMaintenance, err) |
| + if !g.used[action] { |
| + if err := consumeGroupAction(g.dir, "used-"+p.Transaction+"-"+action, g.owner); err != nil { |
| + return errors.Join(errGroupMaintenance, err) |
| + } |
| + if g.used == nil { |
| + g.used = map[string]bool{} |
| + } |
| + g.used[action] = true |
| + g.permit = &p |
| } |
| - if g.used == nil { |
| - g.used = map[string]bool{} |
| + // Tombstone the process maintenance is about to stop, never its successor. |
| + // Retry a failed clear before mutation; after success, only revalidate. |
| + if err := a.clearGroupHairpin(); err != nil { |
| + return err |
| + } |
| + if g.cleared == nil { |
| + g.cleared = map[string]bool{} |
| } |
| - g.used[action] = true |
| - g.permit = &p |
| - return a.clearGroupHairpin() |
| + g.cleared[action] = true |
| + return nil |
| } |
| // The operator writer and the mutation guard use the same field checks. |
| @@ -361,6 +375,7 @@ func (a *systemApplier) resetGroupMaintenance() { |
| if g := a.groupMaintenance; g != nil { |
| g.permit = nil |
| g.used = nil |
| + g.cleared = nil |
| g.initial = false |
| } |
| } |
diff --git a/internal/host/group_maintenance_test.go b/internal/host/group_maintenance_test.go| index 18504fa91..42e092e16 100644 |
| --- a/internal/host/group_maintenance_test.go |
| +++ b/internal/host/group_maintenance_test.go |
| @@ -113,6 +113,125 @@ func writeMaintenancePermit(t *testing.T, f *applyFixture, p groupMaintenancePer |
| t.Fatal(err) |
| } |
| } |
| + |
| +func TestGroupMaintenanceClearsHairpinOnce(t *testing.T) { |
| + for _, action := range []string{"apply", "rollback"} { |
| + t.Run(action, func(t *testing.T) { |
| + f, p := maintenanceFixture(t) |
| + p.Action = action |
| + p.AllowRollback = true |
| + writeMaintenancePermit(t, f, p) |
| + clears := 0 |
| + f.a.maintenance().clearHairpin = func() error { clears++; return nil } |
| + if err := f.a.requireGroupMaintenance("check"); err != nil || clears != 0 { |
| + t.Fatalf("check: clears=%d err=%v", clears, err) |
| + } |
| + if err := f.a.requireGroupMaintenance(action); err != nil || clears != 1 { |
| + t.Fatalf("first consumption: clears=%d err=%v", clears, err) |
| + } |
| + // These are the real restart entry and the guard used by the relay, |
| + // activation finish and arm after it. None may tombstone the successor. |
| + if err := f.a.restartEdge(); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.a.restartRelay() |
| + for range 3 { |
| + if err := f.a.requireGroupMaintenance("apply", "rollback"); err != nil || clears != 1 { |
| + t.Fatalf("post-restart guard: clears=%d err=%v", clears, err) |
| + } |
| + } |
| + if action == "apply" { |
| + // A failed forward gate consumes rollback while the failed process |
| + // still runs. Helpers continue selecting the permit's apply action. |
| + if err := f.a.requireGroupMaintenance("rollback"); err != nil || clears != 2 { |
| + t.Fatalf("rollback consumption: clears=%d err=%v", clears, err) |
| + } |
| + if err := f.a.restartEdge(); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.a.restartRelay() |
| + for _, guard := range [][]string{{"rollback"}, {"apply", "rollback"}, {"apply", "rollback"}} { |
| + if err := f.a.requireGroupMaintenance(guard[0], guard[1:]...); err != nil || clears != 2 { |
| + t.Fatalf("rollback successor guard: clears=%d err=%v", clears, err) |
| + } |
| + } |
| + } |
| + before := clears |
| + p.Expires = f.now.Unix() |
| + writeMaintenancePermit(t, f, p) |
| + if err := f.a.requireGroupMaintenance("apply", "rollback"); !errors.Is(err, errGroupMaintenance) || clears != before { |
| + t.Fatalf("expired consumed permit: clears=%d err=%v", clears, err) |
| + } |
| + }) |
| + } |
| +} |
| +func TestGroupMaintenanceRetriesFailedHairpinClear(t *testing.T) { |
| + for _, action := range []string{"apply", "rollback"} { |
| + t.Run(action, func(t *testing.T) { |
| + f, p := maintenanceFixture(t) |
| + p.Action = action |
| + writeMaintenancePermit(t, f, p) |
| + clearErr := errors.New("hairpin clear failed") |
| + clears := 0 |
| + f.a.maintenance().clearHairpin = func() error { |
| + clears++ |
| + if clears == 1 { |
| + return clearErr |
| + } |
| + return nil |
| + } |
| + if err := f.a.requireGroupMaintenance(action); !errors.Is(err, clearErr) || clears != 1 { |
| + t.Fatalf("first guard: clears=%d err=%v", clears, err) |
| + } |
| + if err := f.a.requireGroupMaintenance(action); err != nil || clears != 2 { |
| + t.Fatalf("retry: clears=%d err=%v", clears, err) |
| + } |
| + if err := f.a.restartEdge(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for range 3 { |
| + if err := f.a.requireGroupMaintenance(action); err != nil || clears != 2 { |
| + t.Fatalf("after success: clears=%d err=%v", clears, err) |
| + } |
| + } |
| + f.a.resetGroupMaintenance() |
| + p.Transaction = "tx-2" |
| + writeMaintenancePermit(t, f, p) |
| + if err := f.a.requireGroupMaintenance(action); err != nil || clears != 3 { |
| + t.Fatalf("new run: clears=%d err=%v", clears, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupMaintenanceFailedHairpinClearBlocksRestart(t *testing.T) { |
| + f, _ := maintenanceFixture(t) |
| + clearErr := errors.New("hairpin clear failed") |
| + clears := 0 |
| + f.a.maintenance().clearHairpin = func() error { |
| + clears++ |
| + return clearErr |
| + } |
| + if err := f.a.notePendingRearm([]string{"carlos-adopt.timer"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.a.rearmPending() |
| + if clears != 1 || len(f.calls) != 0 { |
| + t.Fatalf("pending rearm: clears=%d calls=%v", clears, f.calls) |
| + } |
| + for want := 2; want <= 3; want++ { |
| + if err := f.a.restartEdge(); !errors.Is(err, clearErr) || clears != want { |
| + t.Fatalf("restart: clears=%d want=%d err=%v", clears, want, err) |
| + } |
| + if len(f.calls) != 0 { |
| + t.Fatalf("failed clear allowed systemctl: %v", f.calls) |
| + } |
| + } |
| + if _, err := os.Stat(f.a.file(rearmPendingFile)); err != nil { |
| + t.Fatalf("failed clear lost pending rearm: %v", err) |
| + } |
| +} |
| + |
| func TestGroupMaintenancePermit(t *testing.T) { |
| for _, bad := range []string{"valid", "missing", "account", "region", "group", "iid", "boot", "transaction", "old", "new", "digest", "expiry", "verify", "return", "revoked", "mode", "symlink", "hardlink", "directory", "oversize", "unknown", "trailing", "parent-mode", "marker-mode", "marker-corrupt", "agent-receipt"} { |
| t.Run(bad, func(t *testing.T) { |
diff --git a/internal/host/systemapply.go b/internal/host/systemapply.go| index 1bd5ad522..9ccb2d87e 100644 |
| --- a/internal/host/systemapply.go |
| +++ b/internal/host/systemapply.go |
| @@ -65,11 +65,16 @@ const ( |
| // deployment and grows with the deployment's app count. A fixed 20 s |
| // rolled every update back, and its rollback too. The longer window |
| // comes with fail-fast (gateFailFast), so a build that crashes still |
| - // rolls back in seconds. Claims-off boxes keep systemGateWait exactly. |
| + // rolls back in seconds. Fixed claims-off boxes keep systemGateWait. |
| systemClaimsGateWait = 120 * time.Second |
| - systemGateSoak = 15 * time.Second |
| - systemVersionWait = 30 * time.Second |
| - systemBootstrapWait = 120 * time.Second |
| + // systemGroupGateWait covers group maintenance startup: the listener |
| + // bound at 40 s with S3 and SSM dropped. A member in Standby carries |
| + // no traffic, so waiting costs no traffic and a shared-store outage |
| + // must not read as a bad build. Failure still rolls back at the deadline. |
| + systemGroupGateWait = 3 * time.Minute |
| + systemGateSoak = 15 * time.Second |
| + systemVersionWait = 30 * time.Second |
| + systemBootstrapWait = 120 * time.Second |
| // How long --recover waits for the apply lock, and how often it asks. |
| // See waitForLock. |
| @@ -279,7 +284,7 @@ type systemApplier struct { |
| // unit's environment (carlos-system-update.service and |
| // carlos-system-recover.service both load host.env). It changes only the |
| // gate: the claims window and fail-fast (systemGateWaitFor, |
| - // gateFailFast). Off, the gate is exactly the 20 s one. |
| + // gateFailFast). Group maintenance selects its own window from the marker. |
| claims bool |
| // store is the deploy store verifyPointer opened, kept for armFloor. |
| // Nil on --recover, which reads no store. |
| @@ -1659,6 +1664,9 @@ func (a *systemApplier) gate(ctx context.Context, target string) error { |
| wait, soak := a.gateWait, a.soak |
| if wait <= 0 { |
| wait = systemGateWaitFor(a.claims) |
| + if groupMarkerPresent(a.etcDir) { |
| + wait = systemGroupGateWait |
| + } |
| } |
| if soak <= 0 { |
| soak = systemGateSoak |
| @@ -1715,7 +1723,9 @@ func systemApplyGate(getenv func(string) string) (bool, time.Duration) { |
| // the way production does. CARLOS_REGION_HA is not read here (region HA |
| // P1a): it no longer changes how an update begins. |
| func (a *systemApplier) readEnvironment(getenv func(string) string) { |
| - a.claims, a.gateWait = systemApplyGate(getenv) |
| + // Resolve the default window in gate, where the group marker is known. |
| + // Leave an explicit gateWait intact for callers testing a shorter window. |
| + a.claims, _ = systemApplyGate(getenv) |
| } |
| // systemGateWaitFor is the gate's window: systemClaimsGateWait with |
diff --git a/internal/host/systemapply_groupgate_test.go b/internal/host/systemapply_groupgate_test.go| new file mode 100644 |
| index 000000000..5c615fa83 |
| --- /dev/null |
| +++ b/internal/host/systemapply_groupgate_test.go |
| @@ -0,0 +1,160 @@ |
| +package host |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestSystemApplyGroupGateWindow(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + group bool |
| + claims bool |
| + override time.Duration |
| + want time.Duration |
| + }{ |
| + {name: "fixed", want: 20 * time.Second}, |
| + {name: "claims", claims: true, want: 120 * time.Second}, |
| + {name: "group", group: true, want: 3 * time.Minute}, |
| + {name: "group-with-claims", group: true, claims: true, want: 3 * time.Minute}, |
| + {name: "group-override", group: true, override: 7 * time.Second, want: 7 * time.Second}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + f := newApplyFixture(t, "stable", "v1") |
| + if tc.group { |
| + dir := filepath.Join(f.a.etcDir, "carlos") |
| + if err := os.MkdirAll(dir, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "group.json"), []byte(`{}`), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + f.a.gateWait = tc.override |
| + f.a.readEnvironment(func(k string) string { |
| + if k == "CARLOS_HOST_CLAIM" && tc.claims { |
| + return "1" |
| + } |
| + if k == "CARLOS_GROUP_ADMISSION" || k == "CARLOS_REGION_HA" { |
| + return "1" |
| + } |
| + return "" |
| + }) |
| + f.probeErr = errors.New("connection refused") |
| + start := f.now |
| + if err := f.a.gate(t.Context(), "v1"); err == nil { |
| + t.Fatal("gate accepted a listener that never answers") |
| + } |
| + if got := f.now.Sub(start); got != tc.want { |
| + t.Fatalf("gate window = %s, want %s", got, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func groupGateFixture(t *testing.T) (*applyFixture, systemRequest) { |
| + t.Helper() |
| + m, p := maintenanceFixture(t) |
| + f, req := applyHappy(t) |
| + f.a.etcDir = m.a.etcDir |
| + f.a.groupMaintenance = m.a.groupMaintenance |
| + for path, target := range map[string]*string{ |
| + systemBinaryPath(f.a.optDir): &p.OldSHA256, |
| + systemCachePath(f.a.dataDir, req.Version): &p.NewSHA256, |
| + } { |
| + body, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + sum := sha256.Sum256(body) |
| + *target = hex.EncodeToString(sum[:]) |
| + } |
| + p.AllowRollback = true |
| + writeMaintenancePermit(t, f, p) |
| + f.a.readEnvironment(func(string) string { return "" }) |
| + return f, req |
| +} |
| + |
| +func TestSystemApplyGroupGatePassesListenerAt40s(t *testing.T) { |
| + f, req := groupGateFixture(t) |
| + restarts := slowListener(f, 40*time.Second) |
| + if err := f.a.Run(t.Context(), false); err != nil { |
| + t.Fatalf("group gate failed the listener at 40 s: %v", err) |
| + } |
| + if r := f.result(); r == nil || r.Outcome != systemOutcomeApplied || !r.matches("stable", "v2", req.PromotedAt) { |
| + t.Fatalf("result = %+v, want applied", r) |
| + } |
| + if len(*restarts) != 1 { |
| + t.Fatalf("edge restarted %d times, want 1 with no rollback", len(*restarts)) |
| + } |
| + if elapsed := f.now.Sub((*restarts)[0]); elapsed != 40*time.Second+systemGateSoak { |
| + t.Fatalf("gate took %s, want 40 s plus the soak", elapsed) |
| + } |
| +} |
| + |
| +func TestSystemApplyGroupGateNeverAnswersRollsBack(t *testing.T) { |
| + for _, restoredAnswers := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "both-fail", true: "restored-answers-at-40s"}[restoredAnswers], func(t *testing.T) { |
| + f, req := groupGateFixture(t) |
| + restarts := slowListener(f, 40*time.Second) |
| + probe := f.a.ops.probeEdge |
| + f.a.ops.probeEdge = func() error { |
| + if !restoredAnswers || len(*restarts) < 2 { |
| + return errors.New("connection refused") |
| + } |
| + return probe() |
| + } |
| + if err := f.a.Run(t.Context(), false); err == nil { |
| + t.Fatal("gate accepted a candidate that never answers") |
| + } |
| + want := systemOutcomeRollbackFailed |
| + if restoredAnswers { |
| + want = systemOutcomeRolledBack |
| + } |
| + if r := f.result(); r == nil || r.Outcome != want || !r.matches("stable", "v2", req.PromotedAt) { |
| + t.Fatalf("result = %+v, want %s", r, want) |
| + } |
| + if len(*restarts) != 2 { |
| + t.Fatalf("edge restarted %d times, want apply and rollback", len(*restarts)) |
| + } |
| + if waited := (*restarts)[1].Sub((*restarts)[0]); waited != 3*time.Minute { |
| + t.Fatalf("rollback began after %s, want 3 min", waited) |
| + } |
| + wantWait := 3 * time.Minute |
| + if restoredAnswers { |
| + wantWait = 40*time.Second + systemGateSoak |
| + } |
| + if waited := f.now.Sub((*restarts)[1]); waited != wantWait { |
| + t.Fatalf("rollback gate took %s, want %s", waited, wantWait) |
| + } |
| + body, err := os.ReadFile(systemBinaryPath(f.a.optDir)) |
| + if err != nil || !strings.Contains(string(body), "carlos v1") { |
| + t.Fatalf("previous binary was not restored: %q %v", body, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSystemApplyGroupGateKeepsFailFastClaimsOnly(t *testing.T) { |
| + f, _ := maintenanceFixture(t) |
| + f.edgeUp = false |
| + f.nrestarts = "3" |
| + start := f.now |
| + if err := f.a.gate(t.Context(), "v1.0.0"); err == nil { |
| + t.Fatal("gate accepted a failed edge") |
| + } |
| + if waited := f.now.Sub(start); waited != 3*time.Minute { |
| + t.Fatalf("group gate failed after %s, want 3 min", waited) |
| + } |
| + for _, call := range f.calls { |
| + if strings.HasPrefix(call, "systemctl show") { |
| + t.Fatalf("group gate invoked claims fail-fast: %s", call) |
| + } |
| + } |
| +} |
diff --git a/internal/instancectl/hairpin.go b/internal/instancectl/hairpin.go| index f22fe2c08..fe37e1737 100644 |
| --- a/internal/instancectl/hairpin.go |
| +++ b/internal/instancectl/hairpin.go |
| @@ -12,17 +12,60 @@ import ( |
| "os" |
| "os/exec" |
| "slices" |
| + "strings" |
| "time" |
| "github.com/carlosframework/platform/internal/hairpin" |
| ) |
| +var ( |
| + hairpinAuthenticate = hairpin.Authenticate |
| + hairpinWatchExit = hairpin.WatchExit |
| + hairpinSave = (*hairpin.Lease).Save |
| + hairpinAddresses = (*hairpin.Lease).Addresses |
| + hairpinEUID = os.Geteuid |
| + hairpinInstall = (*hairpin.Lease).Install |
| + hairpinVerify = (*hairpin.Lease).Verify |
| + hairpinCheck = (*hairpin.Lease).CheckAddresses |
| + hairpinMainProcess = hairpin.MainProcess |
| + hairpinPrepare = (*hairpin.Lease).Prepare |
| + hairpinResetServer = newHairpinResetServer |
| +) |
| + |
| type hairpinLeaseKey struct{} |
| +type hairpinEnablingKey struct{} |
| type hairpinRequest struct { |
| Enable *bool `json:"enable"` |
| Process hairpin.Process `json:"process"` |
| } |
| +// Operator diagnostics are kept together for the later copy pass. |
| +const ( |
| + groupHairpinErrorText = "%s (HTTP %d)" |
| + groupHairpinFailureText = "group hairpin: step=%s code=%s status=%d: %v" |
| + groupHairpinClosedText = "pid=%d: %w" |
| + groupHairpinMissingPeerText = "missing peer connection" |
| + groupHairpinMissingLeaseText = "missing group lease" |
| + groupHairpinTrailingValueText = "trailing request value" |
| + groupHairpinMissingEnableText = "missing enable field" |
| +) |
| + |
| +var ErrGroupHairpinClosed = errors.New("group_hairpin_closed") |
| + |
| +// GroupHairpinError preserves the control service's refusal for callers and logs. |
| +type GroupHairpinError struct { |
| + StatusCode int |
| + Code string |
| +} |
| + |
| +func (e *GroupHairpinError) Error() string { |
| + return fmt.Sprintf(groupHairpinErrorText, e.Code, e.StatusCode) |
| +} |
| + |
| +func (e *GroupHairpinError) Is(target error) bool { |
| + return target == ErrGroupHairpinClosed && e.StatusCode == http.StatusConflict && e.Code == ErrGroupHairpinClosed.Error() |
| +} |
| + |
| // All group operations, the ordinary deny refresh and the entire binary/rootfs |
| // probe share this root lock. No second per-box polling loop is introduced. |
| func hairpinLocked(ctx context.Context) (context.Context, func(), error) { |
| @@ -46,18 +89,21 @@ func (s *Server) hairpinDeny(ctx context.Context, local []netip.Prefix) ([]netip |
| if !ok || !l.State.Active { |
| return local, nil |
| } |
| - if err := errors.Join(l.Verify(ctx), l.CheckAddresses(ctx, true)); err != nil { |
| - // A failed readback revokes both pieces of authority immediately. Even if |
| - // address removal fails, the caller still applies the complete local deny. |
| - l.State.Active = false |
| - l.State.Closed = true |
| - saved := l.Save(l.State) |
| - removed := l.Addresses(ctx, false) |
| - current, readErr := s.localPrefixes() |
| - if readErr == nil && len(current) > 0 { |
| - local = current |
| + if err := errors.Join(hairpinVerify(l, ctx), hairpinCheck(l, ctx, true)); err != nil { |
| + op := s.hairpinOperations(ctx, l, l.State.Process) |
| + // denyLocalAddrs already holds denyMu. Restore the full deny directly, |
| + // using the deactivation context, without entering the refresher again. |
| + op.Exempt = func(cleanup context.Context, _ bool) error { |
| + current, readErr := s.localPrefixes() |
| + if readErr == nil && len(current) > 0 { |
| + local = current |
| + } |
| + return errors.Join(readErr, s.applyLocalDeny(cleanup, local, true)) |
| + } |
| + if enabling, _ := ctx.Value(hairpinEnablingKey{}).(bool); enabling || hairpinContextError(ctx, err) { |
| + return local, errors.Join(err, op.Rollback(ctx)) |
| } |
| - return local, errors.Join(err, saved, removed, readErr) |
| + return local, errors.Join(err, op.Revoke(ctx)) |
| } |
| out := make([]netip.Prefix, 0, len(local)) |
| for _, p := range local { |
| @@ -69,82 +115,168 @@ func (s *Server) hairpinDeny(ctx context.Context, local []netip.Prefix) ([]netip |
| return out, nil |
| } |
| func (s *Server) hairpinOperations(ctx context.Context, l *hairpin.Lease, p hairpin.Process) hairpin.Operations { |
| - return hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses, |
| - Exempt: func(ctx context.Context, on bool) error { l.State.Active = on; return s.denyLocalAddrs(ctx) }, |
| - Save: func(on bool) error { return l.Save(hairpin.State{Process: p, Active: on, Closed: !on}) }, |
| + return hairpin.Operations{Install: func(ctx context.Context) error { return hairpinInstall(l, ctx) }, |
| + Verify: func(ctx context.Context) error { return hairpinVerify(l, ctx) }, |
| + Addresses: func(ctx context.Context, on bool) error { return hairpinAddresses(l, ctx, on) }, |
| + Exempt: func(ctx context.Context, on bool) error { |
| + if on { |
| + l.State = hairpin.State{Process: p, Active: true} |
| + ctx = context.WithValue(ctx, hairpinEnablingKey{}, true) |
| + } else { |
| + l.State.Active = false |
| + } |
| + return s.denyLocalAddrs(ctx) |
| + }, |
| + Save: func(on, closed bool) error { |
| + // Rollback cannot undo an existing revocation for this process. |
| + closed = closed || (l.State.Process == p && l.State.Closed) |
| + state := hairpin.State{Process: p, Active: on && !closed, Closed: closed} |
| + l.State = state |
| + if !state.Active && s.hairpinWatch.process == p { |
| + s.stopHairpinWatch() |
| + } |
| + return hairpinSave(l, state) |
| + }, |
| + } |
| +} |
| + |
| +func hairpinContextError(ctx context.Context, err error) bool { |
| + return ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) |
| +} |
| + |
| +type groupHairpinWatch struct { |
| + process hairpin.Process |
| + stop func() |
| +} |
| + |
| +// The root hairpin lock protects the watch along with the lease state. |
| +func (s *Server) stopHairpinWatch() { |
| + if s.hairpinWatch.stop != nil { |
| + s.hairpinWatch.stop() |
| } |
| + s.hairpinWatch = groupHairpinWatch{} |
| } |
| + |
| +func (s *Server) watchGroupHairpin(p hairpin.Process) error { |
| + if s.hairpinWatch.stop != nil && s.hairpinWatch.process == p { |
| + return nil |
| + } |
| + s.stopHairpinWatch() |
| + stop, err := hairpinWatchExit(p, func() { s.hairpinExited(p) }) |
| + if err == nil { |
| + s.hairpinWatch = groupHairpinWatch{process: p, stop: stop} |
| + } |
| + return err |
| +} |
| + |
| func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) { |
| ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) |
| defer cancel() |
| + refuse := func(step, code string, status int, err error) { |
| + s.logf(groupHairpinFailureText, step, code, status, err) |
| + http.Error(w, code, status) |
| + } |
| conn := RequestConn(r.Context()) |
| - if conn == nil || conn.SetReadDeadline(time.Now().Add(5*time.Second)) != nil || conn.SetWriteDeadline(time.Now().Add(75*time.Second)) != nil { |
| - http.Error(w, "group_hairpin_peer", 403) |
| + if conn == nil { |
| + refuse("peer", "group_hairpin_peer", 403, errors.New(groupHairpinMissingPeerText)) |
| + return |
| + } |
| + if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { |
| + refuse("peer", "group_hairpin_peer", 403, err) |
| + return |
| + } |
| + if err := conn.SetWriteDeadline(time.Now().Add(75 * time.Second)); err != nil { |
| + refuse("peer", "group_hairpin_peer", 403, err) |
| return |
| } |
| var req hairpinRequest |
| d := json.NewDecoder(io.LimitReader(r.Body, 1025)) |
| d.DisallowUnknownFields() |
| - if d.Decode(&req) != nil || d.Decode(new(any)) != io.EOF || req.Enable == nil { |
| - http.Error(w, "group_hairpin_request", 400) |
| + if err := d.Decode(&req); err != nil { |
| + refuse("request", "group_hairpin_request", 400, err) |
| + return |
| + } |
| + if err := d.Decode(new(any)); err != io.EOF { |
| + if err == nil { |
| + err = errors.New(groupHairpinTrailingValueText) |
| + } |
| + refuse("request", "group_hairpin_request", 400, err) |
| + return |
| + } |
| + if req.Enable == nil { |
| + refuse("request", "group_hairpin_request", 400, errors.New(groupHairpinMissingEnableText)) |
| return |
| } |
| // Revalidate the exact kernel peer and live MainPID after taking the lock; |
| // a delayed connection from an earlier process cannot alter its successor. |
| ctx, unlock, err := hairpinLocked(ctx) |
| if err != nil { |
| - http.Error(w, "group_hairpin_unavailable", 503) |
| + refuse("lock", "group_hairpin_unavailable", 503, err) |
| return |
| } |
| defer unlock() |
| l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease) |
| - if !ok || hairpin.Authenticate(ctx, conn, req.Process) != nil { |
| - http.Error(w, "group_hairpin_peer", 403) |
| + if !ok { |
| + refuse("peer", "group_hairpin_peer", 403, errors.New(groupHairpinMissingLeaseText)) |
| + return |
| + } |
| + if err := hairpinAuthenticate(ctx, conn, req.Process); err != nil { |
| + refuse("peer", "group_hairpin_peer", 403, err) |
| return |
| } |
| op := s.hairpinOperations(ctx, l, req.Process) |
| if *req.Enable { |
| if l.State.Process == req.Process && l.State.Closed { |
| - http.Error(w, "group_hairpin_closed", 409) |
| + if cleanupErr := op.Rollback(ctx); cleanupErr != nil { |
| + s.logf(groupHairpinFailureText, "disable", "group_hairpin_unavailable", 503, cleanupErr) |
| + } |
| + refuse("closed", "group_hairpin_closed", 409, fmt.Errorf(groupHairpinClosedText, req.Process.PID, ErrGroupHairpinClosed)) |
| return |
| } |
| if l.State.Active && l.State.Process == req.Process { |
| - if err := errors.Join(l.Verify(ctx), l.CheckAddresses(ctx, true)); err != nil { |
| - _ = op.Disable(ctx) |
| - http.Error(w, "group_hairpin_unavailable", 503) |
| + if err := errors.Join(hairpinVerify(l, ctx), hairpinCheck(l, ctx, true)); err != nil { |
| + if disableErr := op.Rollback(ctx); disableErr != nil { |
| + s.logf(groupHairpinFailureText, "disable", "group_hairpin_unavailable", 503, disableErr) |
| + } |
| + refuse("verify", "group_hairpin_unavailable", 503, err) |
| return |
| } |
| w.WriteHeader(http.StatusNoContent) |
| return |
| } |
| - if l.State.Active { |
| - if err := op.Disable(ctx); err != nil { |
| - http.Error(w, "group_hairpin_unavailable", 503) |
| - return |
| - } |
| + if err := op.Rollback(ctx); err != nil { |
| + refuse("disable", "group_hairpin_unavailable", 503, err) |
| + return |
| } |
| // Open the descriptor before making the first EIP local. The callback also |
| // checks the saved identity, so an old exit cannot close a new process. |
| - stop, watchErr := hairpin.WatchExit(req.Process, func() { s.hairpinExited(req.Process) }) |
| - if watchErr != nil { |
| - http.Error(w, "group_hairpin_peer", 403) |
| + if watchErr := s.watchGroupHairpin(req.Process); watchErr != nil { |
| + refuse("watch", "group_hairpin_peer", 403, watchErr) |
| return |
| } |
| err = op.Enable(ctx) |
| if err != nil { |
| - stop() |
| + s.stopHairpinWatch() |
| } |
| } else { |
| - err = op.Disable(ctx) |
| + err = op.Revoke(ctx) |
| } |
| if err != nil { |
| - http.Error(w, "group_hairpin_unavailable", 503) |
| + step := "disable" |
| + if *req.Enable { |
| + step = "enable" |
| + } |
| + refuse(step, "group_hairpin_unavailable", 503, err) |
| return |
| } |
| w.WriteHeader(http.StatusNoContent) |
| } |
| func (s *Server) hairpinExited(p hairpin.Process) { |
| - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + s.cleanupHairpinExit(context.Background(), p) |
| +} |
| + |
| +func (s *Server) cleanupHairpinExit(ctx context.Context, p hairpin.Process) { |
| + ctx, cancel := context.WithTimeout(ctx, 60*time.Second) |
| defer cancel() |
| ctx, unlock, err := hairpinLocked(ctx) |
| if err != nil { |
| @@ -156,7 +288,7 @@ func (s *Server) hairpinExited(p hairpin.Process) { |
| if !ok || l.State.Process != p { |
| return |
| } |
| - if err = s.hairpinOperations(ctx, l, p).Disable(ctx); err != nil { |
| + if err = s.hairpinOperations(ctx, l, p).Revoke(ctx); err != nil { |
| s.logf("group hairpin exit cleanup failed: %v", err) |
| } |
| } |
| @@ -165,13 +297,10 @@ func (s *Server) hairpinExited(p hairpin.Process) { |
| // state remains closed for the old process. Only a different current MainPID |
| // may subsequently enable. The group-only reset unit also runs after a crash. |
| func ClearGroupHairpin(ctx context.Context) error { |
| - if os.Geteuid() != 0 { |
| + if hairpinEUID() != 0 { |
| return fmt.Errorf("%w: hairpin reset requires root", hairpin.ErrConfig) |
| } |
| - s := &Server{LocalAddrs: LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| - return string(out), err |
| - }} |
| + s := hairpinResetServer() |
| ctx, unlock, err := hairpinLocked(ctx) |
| if err != nil { |
| return err |
| @@ -183,15 +312,22 @@ func ClearGroupHairpin(ctx context.Context) error { |
| } |
| // Tombstone the current process even if it has never enabled hairpin. |
| // A booting agent must not race a maintenance stop by enabling afterward. |
| - process, lookupErr := hairpin.MainProcess(ctx) |
| + process, lookupErr := hairpinMainProcess(ctx) |
| if process.PID == 0 { |
| process = l.State.Process |
| } |
| - if err := errors.Join(s.hairpinOperations(ctx, l, process).Disable(ctx), lookupErr); err != nil { |
| + if err := errors.Join(s.hairpinOperations(ctx, l, process).Revoke(ctx), lookupErr); err != nil { |
| return err |
| } |
| - return l.Prepare(ctx) |
| + return hairpinPrepare(l, ctx) |
| +} |
| +func newHairpinResetServer() *Server { |
| + return &Server{LocalAddrs: LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + }} |
| } |
| + |
| func groupHairpinMarker() bool { return hairpin.GroupPresent() } |
| func (c *Client) GroupHairpin(ctx context.Context, enable bool, p hairpin.Process) error { |
| @@ -209,7 +345,14 @@ func (c *Client) GroupHairpin(ctx context.Context, enable bool, p hairpin.Proces |
| } |
| defer resp.Body.Close() |
| if resp.StatusCode != http.StatusNoContent { |
| - return errors.New("group_hairpin_unavailable") |
| + body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1025)) |
| + code := strings.TrimSpace(string(body)) |
| + switch code { |
| + case "group_hairpin_closed", "group_hairpin_peer", "group_hairpin_request", "group_hairpin_unavailable": |
| + default: |
| + code = "group_hairpin_unavailable" |
| + } |
| + return errors.Join(&GroupHairpinError{StatusCode: resp.StatusCode, Code: code}, readErr) |
| } |
| return nil |
| } |
| @@ -228,11 +371,27 @@ func (s *Server) resumeGroupHairpin(ctx context.Context) error { |
| return nil |
| } |
| p := l.State.Process |
| - if !l.State.Active || hairpin.Current(ctx, p) != nil || l.Verify(ctx) != nil || l.CheckAddresses(ctx, true) != nil { |
| - return s.hairpinOperations(ctx, l, p).Disable(ctx) |
| + op := s.hairpinOperations(ctx, l, p) |
| + current, lookupErr := hairpinMainProcess(ctx) |
| + if lookupErr != nil { |
| + return op.Rollback(ctx) |
| } |
| - _, err = hairpin.WatchExit(p, func() { s.hairpinExited(p) }) |
| - return err |
| + if p.PID <= 0 || current != p { |
| + return op.Revoke(ctx) |
| + } |
| + if !l.State.Active { |
| + return op.Rollback(ctx) |
| + } |
| + if err := errors.Join(hairpinVerify(l, ctx), hairpinCheck(l, ctx, true)); err != nil { |
| + if hairpinContextError(ctx, err) { |
| + return op.Rollback(ctx) |
| + } |
| + return op.Revoke(ctx) |
| + } |
| + if err := s.watchGroupHairpin(p); err != nil { |
| + return errors.Join(err, op.Rollback(ctx)) |
| + } |
| + return nil |
| } |
| // InstallDormantGroupHairpin is the initial root boot stage, before bootstrap |
| @@ -254,14 +413,20 @@ func InstallDormantGroupHairpin(ctx context.Context) error { |
| if l.State != (hairpin.State{}) { |
| return fmt.Errorf("%w: dormant install found saved state", hairpin.ErrConfig) |
| } |
| - if current, err := hairpin.MainProcess(ctx); err != nil || current.PID != 0 { |
| + if current, err := hairpinMainProcess(ctx); err != nil || current.PID != 0 { |
| return fmt.Errorf("%w: dormant install agent lookup failed or agent exists", hairpin.ErrConfig) |
| } |
| - if err := l.Prepare(ctx); err != nil { |
| + if err := hairpinPrepare(l, ctx); err != nil { |
| return err |
| } |
| if err := l.CheckAddresses(ctx, false); err != nil { |
| return err |
| } |
| - return l.Save(hairpin.State{Closed: true}) |
| + op := hairpin.Operations{ |
| + Save: func(_, closed bool) error { return hairpinSave(l, hairpin.State{Closed: closed}) }, |
| + Addresses: func(ctx context.Context, on bool) error { return hairpinAddresses(l, ctx, on) }, |
| + // Initial install has never granted an exemption. |
| + Exempt: func(context.Context, bool) error { return nil }, |
| + } |
| + return op.Revoke(ctx) |
| } |
diff --git a/internal/instancectl/hairpin_invariant_test.go b/internal/instancectl/hairpin_invariant_test.go| new file mode 100644 |
| index 000000000..1df667cc2 |
| --- /dev/null |
| +++ b/internal/instancectl/hairpin_invariant_test.go |
| @@ -0,0 +1,540 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "math/rand" |
| + "net" |
| + "net/http/httptest" |
| + "net/netip" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hairpin" |
| +) |
| + |
| +// These seams replace only kernel identity, kernel commands and persistence. |
| +// The handler, Operations, deny application and restart decisions are real. |
| +type hairpinMachine struct { |
| + persisted hairpin.State |
| + failure error |
| + readbackCanceled bool |
| + t *testing.T |
| + s *Server |
| + l *hairpin.Lease |
| + p hairpin.Process |
| + live bool |
| + addresses, denied bool |
| + watches, maxWatches int |
| + fail, cancelAt string |
| + nth, seen int |
| + cancel context.CancelFunc |
| + trace []string |
| + removed, deactivated bool |
| + readbackFailure bool |
| + lookupFailed bool |
| +} |
| + |
| +func newHairpinMachine(t *testing.T) *hairpinMachine { |
| + t.Helper() |
| + m := &hairpinMachine{t: t, p: hairpin.Process{PID: 101, Start: "1", Boot: "boot"}, live: true, denied: true} |
| + m.l = &hairpin.Lease{Config: hairpin.Config{PublicIPs: []string{"8.8.8.8", "9.9.9.9"}}} |
| + resetServer := hairpinResetServer |
| + auth, watch, save, addresses, euid := hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID |
| + install, verify, check, main, prepare := hairpinInstall, hairpinVerify, hairpinCheck, hairpinMainProcess, hairpinPrepare |
| + t.Cleanup(func() { |
| + m.s.stopHairpinWatch() |
| + hairpinResetServer = resetServer |
| + hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID = auth, watch, save, addresses, euid |
| + hairpinInstall, hairpinVerify, hairpinCheck, hairpinMainProcess, hairpinPrepare = install, verify, check, main, prepare |
| + }) |
| + hairpinResetServer = func() *Server { return m.s } |
| + hairpinAuthenticate = func(ctx context.Context, _ net.Conn, p hairpin.Process) error { |
| + if !m.live || p != m.p { |
| + return errors.New("stale") |
| + } |
| + return ctx.Err() |
| + } |
| + hairpinMainProcess = func(ctx context.Context) (hairpin.Process, error) { |
| + if err := m.step(ctx, "current"); err != nil { |
| + m.lookupFailed = true |
| + return hairpin.Process{}, err |
| + } |
| + if !m.live { |
| + return hairpin.Process{}, nil |
| + } |
| + return m.p, nil |
| + } |
| + hairpinPrepare = func(*hairpin.Lease, context.Context) error { return nil } |
| + hairpinEUID = func() int { return 0 } |
| + hairpinWatchExit = func(p hairpin.Process, _ func()) (func(), error) { |
| + if err := m.step(context.Background(), "watch"); err != nil { |
| + return nil, err |
| + } |
| + if !m.live || p != m.p { |
| + return nil, errors.New("dead") |
| + } |
| + m.watches++ |
| + m.maxWatches = max(m.maxWatches, m.watches) |
| + stopped := false |
| + return func() { |
| + if !stopped { |
| + m.watches-- |
| + stopped = true |
| + } |
| + }, nil |
| + } |
| + hairpinInstall = func(_ *hairpin.Lease, ctx context.Context) error { return m.step(ctx, "install") } |
| + hairpinVerify = func(_ *hairpin.Lease, ctx context.Context) error { |
| + err := m.step(ctx, "verify") |
| + if err != nil && !hairpinContextError(ctx, err) { |
| + m.readbackFailure = true |
| + } |
| + return err |
| + } |
| + hairpinCheck = func(_ *hairpin.Lease, ctx context.Context, on bool) error { |
| + if err := m.step(ctx, "check"); err != nil { |
| + if !hairpinContextError(ctx, err) { |
| + m.readbackFailure = true |
| + } |
| + return err |
| + } |
| + if m.addresses != on { |
| + return errors.New("address readback") |
| + } |
| + return nil |
| + } |
| + hairpinAddresses = func(_ *hairpin.Lease, ctx context.Context, on bool) error { |
| + name := "remove" |
| + if on { |
| + name = "addresses" |
| + } |
| + if !on { |
| + m.removed = false |
| + m.cleanupContext(ctx) |
| + } |
| + if err := m.step(ctx, name); err != nil { |
| + return err |
| + } |
| + m.addresses = on |
| + if on { |
| + return hairpinCheck(m.l, ctx, true) |
| + } |
| + if !on { |
| + m.removed = true |
| + } |
| + return nil |
| + } |
| + hairpinSave = func(l *hairpin.Lease, state hairpin.State) error { |
| + name := "save-off" |
| + if state.Active { |
| + name = "save" |
| + } else { |
| + m.deactivated = true |
| + } |
| + err := m.step(context.Background(), name) |
| + if err == nil { |
| + m.persisted = state |
| + } |
| + l.State = state |
| + return err |
| + } |
| + m.resetServer() |
| + return m |
| +} |
| + |
| +func (m *hairpinMachine) resetServer() { |
| + m.s = &Server{Logf: func(string, ...any) {}, LocalAddrs: func() ([]netip.Prefix, error) { |
| + return parsePrefixes("172.31.7.19/32", "8.8.8.8/32", "9.9.9.9/32"), nil |
| + }, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + deny := strings.Contains(args[len(args)-1], "8.8.8.8/32") |
| + name := "exempt" |
| + if deny { |
| + name = "deny" |
| + m.cleanupContext(ctx) |
| + } |
| + if err := m.step(ctx, name); err != nil { |
| + return "", err |
| + } |
| + m.denied = deny |
| + return "", nil |
| + }} |
| +} |
| +func (m *hairpinMachine) cleanupContext(ctx context.Context) { |
| + m.t.Helper() |
| + // Ordinary refreshes also apply a deny. Only deactivation is detached. |
| + if !m.deactivated { |
| + return |
| + } |
| + deadline, ok := ctx.Deadline() |
| + if ctx.Err() != nil || !ok || time.Until(deadline) > 15*time.Second { |
| + m.t.Fatalf("cleanup context: err=%v deadline=%v", ctx.Err(), deadline) |
| + } |
| +} |
| +func (m *hairpinMachine) step(ctx context.Context, name string) error { |
| + m.trace = append(m.trace, name) |
| + if name == m.cancelAt { |
| + m.cancel() |
| + m.cancelAt = "" |
| + } |
| + if err := ctx.Err(); err != nil { |
| + if name == "verify" || name == "check" { |
| + m.readbackCanceled = true |
| + } |
| + return err |
| + } |
| + if name == m.fail { |
| + m.seen++ |
| + if m.seen == max(1, m.nth) { |
| + if m.failure != nil { |
| + return m.failure |
| + } |
| + return errors.New("injected " + name) |
| + } |
| + } |
| + return nil |
| +} |
| +func (m *hairpinMachine) context() (context.Context, context.CancelFunc) { |
| + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), hairpinLeaseKey{}, m.l)) |
| + m.cancel = cancel |
| + m.trace = nil |
| + m.seen = 0 |
| + m.removed = false |
| + m.deactivated = false |
| + m.readbackFailure = false |
| + m.lookupFailed = false |
| + m.readbackCanceled = false |
| + return ctx, cancel |
| +} |
| +func (m *hairpinMachine) request(ctx context.Context, on bool, p hairpin.Process) int { |
| + raw, _ := json.Marshal(hairpinRequest{Enable: &on, Process: p}) |
| + local, remote := net.Pipe() |
| + defer local.Close() |
| + defer remote.Close() |
| + req := httptest.NewRequest("POST", "/group-hairpin", strings.NewReader(string(raw))) |
| + req = req.WithContext(requestConnContext(ctx, local)) |
| + w := httptest.NewRecorder() |
| + m.s.handleHairpin(w, req) |
| + return w.Code |
| +} |
| +func (m *hairpinMachine) initial(active, closed bool) { |
| + m.l.State = hairpin.State{Process: m.p, Active: active, Closed: closed} |
| + m.persisted = m.l.State |
| + m.addresses = active |
| + m.denied = !active |
| +} |
| +func (m *hairpinMachine) act(ctx context.Context, path string) int { |
| + switch path { |
| + case "enable": |
| + return m.request(ctx, true, m.p) |
| + case "disable": |
| + return m.request(ctx, false, m.p) |
| + case "clear": |
| + if ClearGroupHairpin(ctx) != nil { |
| + return 503 |
| + } |
| + case "resume": |
| + m.s.stopHairpinWatch() |
| + m.l.State = m.persisted |
| + m.resetServer() |
| + if m.s.resumeGroupHairpin(ctx) != nil { |
| + return 503 |
| + } |
| + case "deny": |
| + if m.s.denyLocalAddrs(ctx) != nil { |
| + return 503 |
| + } |
| + case "exit": |
| + m.live = false |
| + m.s.cleanupHairpinExit(ctx, m.p) |
| + default: |
| + m.t.Fatal(path) |
| + } |
| + return 204 |
| +} |
| + |
| +func TestGroupHairpinRevocationGuard(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, path string |
| + active, closed, successor bool |
| + fail, cancel string |
| + wantActive, wantClosed bool |
| + next, nth int |
| + }{ |
| + {name: "N1/predecessor-removal", path: "enable", active: true, successor: true, fail: "remove", next: 204}, |
| + {name: "N1/predecessor-watch", path: "enable", active: true, successor: true, fail: "watch", next: 204}, |
| + {name: "N2/restart-retry", path: "resume", next: 204}, |
| + {name: "N2/restart-closed", path: "resume", closed: true, wantClosed: true, next: 409}, |
| + {name: "N2/restart-active", path: "resume", active: true, wantActive: true, next: 204}, |
| + {name: "N2/restart-dead", path: "resume", active: true, successor: true, wantClosed: true, next: 204}, |
| + {name: "N3/deny-cancel-verify", path: "deny", active: true, cancel: "verify", next: 204}, |
| + {name: "N3/deny-cancel-check", path: "deny", active: true, cancel: "check", next: 204}, |
| + {name: "N3/resume-cancel-current", path: "resume", active: true, cancel: "current", next: 204}, |
| + {name: "N3/resume-cancel-verify", path: "resume", active: true, cancel: "verify", next: 204}, |
| + {name: "N3/deny-real-failure", path: "deny", active: true, fail: "verify", wantClosed: true, next: 409}, |
| + {name: "N3/resume-real-failure", path: "resume", active: true, fail: "verify", wantClosed: true, next: 409}, |
| + {name: "N4/idempotent-cancel", path: "enable", active: true, cancel: "verify", next: 204}, |
| + {name: "idempotent-verify", path: "enable", active: true, fail: "verify", next: 204}, |
| + {name: "disable", path: "disable", active: true, wantClosed: true, next: 409}, |
| + {name: "disable-cancel", path: "disable", active: true, cancel: "remove", wantClosed: true, next: 409}, |
| + {name: "clear", path: "clear", wantClosed: true, next: 409}, |
| + {name: "exit", path: "exit", active: true, wantClosed: true, next: 403}, |
| + {name: "install", path: "enable", fail: "install", next: 204}, |
| + {name: "verify", path: "enable", fail: "verify", next: 204}, |
| + {name: "enable-readback-verify", path: "enable", fail: "verify", nth: 2, next: 204}, |
| + {name: "enable-readback-check", path: "enable", fail: "check", nth: 2, next: 204}, |
| + {name: "resume-current", path: "resume", active: true, fail: "current", next: 204}, |
| + {name: "addresses", path: "enable", fail: "addresses", next: 204}, |
| + {name: "exempt", path: "enable", fail: "exempt", next: 204}, |
| + {name: "save", path: "enable", fail: "save", next: 204}, |
| + {name: "save-off", path: "enable", fail: "save-off", next: 204}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(tc.active, tc.closed) |
| + old := m.p |
| + if tc.successor { |
| + m.p.Start = "2" |
| + } |
| + m.fail, m.cancelAt, m.nth = tc.fail, tc.cancel, tc.nth |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, tc.path) |
| + wantProcess := m.p |
| + if tc.name == "N2/restart-dead" { |
| + wantProcess = old |
| + } |
| + want := hairpin.State{Process: wantProcess, Active: tc.wantActive, Closed: tc.wantClosed} |
| + if m.l.State != want { |
| + t.Fatalf("state=%+v want=%+v trace=%v", m.l.State, want, m.trace) |
| + } |
| + if !tc.wantActive && tc.fail != "remove" && (m.addresses || !m.denied) { |
| + t.Fatalf("deactivation addresses=%v denied=%v trace=%v", m.addresses, m.denied, m.trace) |
| + } |
| + m.fail, m.cancelAt = "", "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + if got := m.request(ctx, true, m.p); got != tc.next { |
| + t.Fatalf("next=%d want=%d state=%+v trace=%v", got, tc.next, m.l.State, m.trace) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinSingleExitWatch(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + for range 8 { |
| + ctx, cancel := m.context() |
| + if m.request(ctx, true, m.p) != 204 { |
| + t.Fatal("enable") |
| + } |
| + for range 3 { |
| + if m.request(ctx, true, m.p) != 204 { |
| + t.Fatal("idempotent") |
| + } |
| + } |
| + m.fail = "verify" |
| + m.seen = 0 |
| + if m.request(ctx, true, m.p) != 503 { |
| + t.Fatal("verify") |
| + } |
| + m.fail = "" |
| + cancel() |
| + } |
| + if m.maxWatches != 1 || m.watches != 0 { |
| + t.Fatalf("watchers max=%d left=%d", m.maxWatches, m.watches) |
| + } |
| +} |
| + |
| +func TestGroupHairpinSeededInvariants(t *testing.T) { |
| + paths := []string{"enable", "enable", "disable", "clear", "resume", "exit", "successor", "deny", "stale"} |
| + failures := []string{"", "current", "install", "verify", "check", "addresses", "remove", "exempt", "deny", "save", "save-off", "watch"} |
| + cancellations := []string{"", "current", "watch", "install", "verify", "check", "addresses", "remove", "exempt", "deny", "save", "save-off"} |
| + for seed := int64(0); seed < 500; seed++ { |
| + t.Run(fmt.Sprintf("seed=%d", seed), func(t *testing.T) { |
| + r := rand.New(rand.NewSource(seed)) |
| + m := newHairpinMachine(t) |
| + revoked := map[hairpin.Process]bool{} |
| + for n := 0; n < 80; n++ { |
| + path := paths[r.Intn(len(paths))] |
| + m.fail = failures[r.Intn(len(failures))] |
| + m.cancelAt = cancellations[r.Intn(len(cancellations))] |
| + m.nth = 1 + r.Intn(2) |
| + m.l.State = m.persisted |
| + ctx, cancel := m.context() |
| + prior := m.l.State |
| + switch path { |
| + case "successor": |
| + old := m.p |
| + m.p.Start = fmt.Sprint(n + 2) |
| + m.live = true |
| + if got := m.request(ctx, true, old); got != 403 || m.l.State != prior { |
| + t.Fatalf("S4 step=%d successor accepted stale request=%d state=%+v", n, got, m.l.State) |
| + } |
| + case "stale": |
| + stale := m.p |
| + stale.Start = "exited" |
| + if got := m.request(ctx, true, stale); got != 403 { |
| + t.Fatalf("S4 step=%d stale=%d", n, got) |
| + } |
| + default: |
| + m.act(ctx, path) |
| + if path == "clear" { |
| + if m.lookupFailed || !m.live { |
| + revoked[prior.Process] = true |
| + } else { |
| + revoked[m.p] = true |
| + } |
| + } |
| + if path == "disable" && m.live || path == "exit" && prior.Process == m.p { |
| + revoked[m.p] = true |
| + } |
| + if path == "resume" && prior.Process != m.p || path == "resume" && !m.live { |
| + revoked[prior.Process] = true |
| + } |
| + // A genuine readback in refresh/resume revokes an active exemption. |
| + // Idempotent verification and pre-exemption Verify are retryable. |
| + if (path == "deny" || path == "resume") && prior.Active && m.readbackFailure && !m.readbackCanceled { |
| + revoked[prior.Process] = true |
| + } |
| + } |
| + cancel() |
| + if m.l.State.Active && revoked[m.l.State.Process] { |
| + t.Fatalf("S2 step=%d path=%s state=%+v trace=%v", n, path, m.l.State, m.trace) |
| + } |
| + if m.deactivated && !m.l.State.Active && m.removed && m.addresses { |
| + t.Fatalf("S3 step=%d path=%s removed address remains", n, path) |
| + } |
| + if m.deactivated && !m.l.State.Active && m.removed && m.fail != "deny" && !m.denied { |
| + t.Fatalf("S3 step=%d path=%s deny missing trace=%v", n, path, m.trace) |
| + } |
| + // Stop failures after each transition. A restart retries incomplete |
| + // deactivation before the next enable; no elapsed-time escape is used. |
| + m.fail, m.cancelAt = "", "" |
| + m.nth = 1 |
| + ctx, finish := m.context() |
| + if !m.l.State.Active { |
| + if err := m.s.resumeGroupHairpin(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.addresses || !m.denied { |
| + t.Fatalf("S3 step=%d path=%s cleanup addresses=%v deny=%v", n, path, m.addresses, m.denied) |
| + } |
| + } |
| + got := m.request(ctx, true, m.p) |
| + switch { |
| + case !m.live: |
| + if got != 403 { |
| + t.Fatalf("S4 step=%d dead enable=%d", n, got) |
| + } |
| + case revoked[m.p]: |
| + if got != 409 || m.l.State.Active { |
| + t.Fatalf("S2 step=%d path=%s revoked retry=%d state=%+v", n, path, got, m.l.State) |
| + } |
| + default: |
| + if got != 204 || !m.l.State.Active { |
| + t.Fatalf("S1 step=%d path=%s retry=%d state=%+v", n, path, got, m.l.State) |
| + } |
| + } |
| + finish() |
| + if m.maxWatches > 1 { |
| + t.Fatalf("watch leak step=%d max=%d", n, m.maxWatches) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinReadbackDeadlineIsRetryable(t *testing.T) { |
| + for _, path := range []string{"enable", "deny", "resume"} { |
| + for _, step := range []string{"verify", "check"} { |
| + t.Run(path+"/"+step, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(true, false) |
| + m.fail = step |
| + m.failure = fmt.Errorf("readback: %w", context.DeadlineExceeded) |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, path) |
| + if m.l.State.Active || m.l.State.Closed || m.addresses || !m.denied { |
| + t.Fatalf("deadline state=%+v addresses=%v deny=%v", m.l.State, m.addresses, m.denied) |
| + } |
| + m.fail = "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + if got := m.request(ctx, true, m.p); got != 204 { |
| + t.Fatalf("deadline retry=%d", got) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestGroupHairpinFailedRemovalRetries(t *testing.T) { |
| + for _, path := range []string{"enable", "disable", "clear", "resume", "deny"} { |
| + t.Run(path, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(true, false) |
| + m.fail = "remove" |
| + if path == "enable" || path == "resume" || path == "deny" { |
| + m.cancelAt = "verify" |
| + } |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, path) |
| + if m.l.State.Active || !m.addresses || !m.denied { |
| + t.Fatalf("failed removal state=%+v addresses=%v deny=%v", m.l.State, m.addresses, m.denied) |
| + } |
| + closed := path == "disable" || path == "clear" |
| + if m.l.State.Closed != closed { |
| + t.Fatalf("closed=%v want=%v", m.l.State.Closed, closed) |
| + } |
| + m.fail, m.cancelAt = "", "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + if err := m.s.resumeGroupHairpin(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.addresses || !m.denied { |
| + t.Fatal("restart did not retry removal") |
| + } |
| + want := 204 |
| + if closed { |
| + want = 409 |
| + } |
| + if got := m.request(ctx, true, m.p); got != want { |
| + t.Fatalf("retry=%d want=%d", got, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinTransientRevocationSaveSurvivesRestart(t *testing.T) { |
| + for _, path := range []string{"disable", "clear", "exit"} { |
| + t.Run(path, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(true, false) |
| + m.fail = "save-off" |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, path) |
| + if m.persisted.Active || !m.persisted.Closed { |
| + t.Fatalf("revocation lost on disk: %+v trace=%v", m.persisted, m.trace) |
| + } |
| + m.fail = "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + m.act(ctx, "resume") |
| + want := 409 |
| + if path == "exit" { |
| + want = 403 |
| + } |
| + if got := m.request(ctx, true, m.p); got != want { |
| + t.Fatalf("restart enable=%d want=%d", got, want) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/instancectl/hairpin_retry_linux_test.go b/internal/instancectl/hairpin_retry_linux_test.go| new file mode 100644 |
| index 000000000..5454d5d2c |
| --- /dev/null |
| +++ b/internal/instancectl/hairpin_retry_linux_test.go |
| @@ -0,0 +1,276 @@ |
| +//go:build linux |
| + |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "net/http/httptest" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/hairpin" |
| +) |
| + |
| +type hairpinHandlerFixture struct { |
| + s *Server |
| + l *hairpin.Lease |
| + p hairpin.Process |
| + dir string |
| + ctx context.Context |
| + addresses bool |
| + failAdd, failRemove bool |
| + watches int |
| + saved hairpin.State |
| +} |
| + |
| +func newHairpinHandlerFixture(t *testing.T) *hairpinHandlerFixture { |
| + t.Helper() |
| + f := &hairpinHandlerFixture{dir: t.TempDir()} |
| + var err error |
| + f.p, err = hairpin.Identity(os.Getpid()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.l = &hairpin.Lease{Config: hairpin.Config{V: 1, Region: "ie", PublicIPs: []string{"8.8.8.8", "9.9.9.9"}, PublicIPv4: "1.1.1.1", PrimaryIPv4: "172.31.7.19", PrivateCIDR: "172.31.0.0/16", BootID: f.p.Boot, Account: "123456789012", InstanceID: "i-0123456789abcdef0"}} |
| + f.ctx = context.WithValue(t.Context(), hairpinLeaseKey{}, f.l) |
| + auth, watch, save, addresses, euid := hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID |
| + t.Cleanup(func() { |
| + hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID = auth, watch, save, addresses, euid |
| + }) |
| + hairpinAuthenticate = func(_ context.Context, _ net.Conn, p hairpin.Process) error { |
| + if p != f.p { |
| + return errors.New("stale process") |
| + } |
| + return nil |
| + } |
| + hairpinWatchExit = func(hairpin.Process, func()) (func(), error) { f.watches++; return func() {}, nil } |
| + hairpinSave = func(l *hairpin.Lease, state hairpin.State) error { l.State = state; f.saved = state; return nil } |
| + hairpinAddresses = func(_ *hairpin.Lease, _ context.Context, on bool) error { |
| + if on && f.failAdd { |
| + f.failAdd = false |
| + return errors.New("address add failed") |
| + } |
| + if !on && f.failRemove { |
| + return errors.New("address removal failed") |
| + } |
| + f.addresses = on |
| + body := `[]` |
| + if on { |
| + body = `[{"addr_info":[{"local":"8.8.8.8","prefixlen":32},{"local":"9.9.9.9","prefixlen":32}]}]` |
| + } |
| + return os.WriteFile(filepath.Join(f.dir, "addresses"), []byte(body), 0600) |
| + } |
| + hairpinEUID = func() int { return 0 } |
| + t.Setenv("PATH", f.dir) |
| + rules, err := f.l.Config.Rules() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.write(t, "rules", rules) |
| + f.write(t, "addresses", "[]") |
| + f.write(t, "nft", "#!/bin/sh\ncase \"$*\" in\n '-f -') /bin/cat >/dev/null; echo installed >> '"+f.dir+"/installs';;\n *) /bin/cat '"+f.dir+"/rules';;\nesac\n") |
| + f.write(t, "ip", "#!/bin/sh\ncase \"$*\" in\n '-j -4 addr show dev carlos-hairpin') /bin/cat '"+f.dir+"/addresses';;\n '-j -d link show') echo '[{\"ifname\":\"carlos-hairpin\",\"linkinfo\":{\"info_kind\":\"dummy\"}}]';;\n 'link set dev carlos-hairpin up') ;;\n *) exit 2;;\nesac\n") |
| + f.write(t, "systemctl", fmt.Sprintf("#!/bin/sh\necho MainPID=%d\necho LoadState=loaded\n", f.p.PID)) |
| + f.s = &Server{Logf: t.Logf, LocalAddrs: func() ([]netip.Prefix, error) { |
| + return parsePrefixes("172.31.7.19/32", "8.8.8.8/32", "9.9.9.9/32"), nil |
| + }, Systemctl: func(context.Context, ...string) (string, error) { return "", nil }} |
| + return f |
| +} |
| + |
| +func (f *hairpinHandlerFixture) write(t *testing.T, name, body string) { |
| + t.Helper() |
| + if err := os.WriteFile(filepath.Join(f.dir, name), []byte(body), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func (f *hairpinHandlerFixture) request(t *testing.T, on bool, p hairpin.Process) int { |
| + t.Helper() |
| + raw, err := json.Marshal(hairpinRequest{Enable: &on, Process: p}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + local, remote := net.Pipe() |
| + defer local.Close() |
| + defer remote.Close() |
| + r := httptest.NewRequest("POST", "/group-hairpin", strings.NewReader(string(raw))) |
| + r = r.WithContext(requestConnContext(f.ctx, local)) |
| + w := httptest.NewRecorder() |
| + f.s.handleHairpin(w, r) |
| + return w.Code |
| +} |
| +func (f *hairpinHandlerFixture) state(t *testing.T, active, closed bool) { |
| + t.Helper() |
| + want := hairpin.State{Process: f.p, Active: active, Closed: closed} |
| + if f.l.State != want || f.saved != want { |
| + t.Fatalf("state=%+v saved=%+v want=%+v", f.l.State, f.saved, want) |
| + } |
| +} |
| +func (f *hairpinHandlerFixture) fullDeny(t *testing.T) { |
| + t.Helper() |
| + for _, ip := range f.l.Config.PublicIPs { |
| + if !strings.Contains(fmt.Sprint(f.s.lastDeny), ip+"/32") { |
| + t.Fatalf("missing deny for %s: %v", ip, f.s.lastDeny) |
| + } |
| + } |
| +} |
| + |
| +func TestGroupHairpinHandlerFailedEnableRetry(t *testing.T) { |
| + f := newHairpinHandlerFixture(t) |
| + f.failAdd = true |
| + if got := f.request(t, true, f.p); got != 503 { |
| + t.Fatalf("failed enable=%d", got) |
| + } |
| + f.state(t, false, false) |
| + stale := f.p |
| + stale.Start += "0" |
| + if got := f.request(t, true, stale); got != 403 { |
| + t.Fatalf("stale retry=%d", got) |
| + } |
| + f.state(t, false, false) |
| + f.fullDeny(t) |
| + if f.addresses { |
| + t.Fatal("rollback retained addresses") |
| + } |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatalf("retry=%d, want 204; state=%+v", got, f.l.State) |
| + } |
| + f.state(t, true, false) |
| +} |
| + |
| +func TestGroupHairpinHandlerVerifyFailureRetry(t *testing.T) { |
| + f := newHairpinHandlerFixture(t) |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatal(got) |
| + } |
| + f.write(t, "rules", "invalid") |
| + if got := f.request(t, true, f.p); got != 503 { |
| + t.Fatal(got) |
| + } |
| + f.state(t, false, false) |
| + f.fullDeny(t) |
| + if f.addresses { |
| + t.Fatal("verify rollback retained addresses") |
| + } |
| + rules, _ := f.l.Config.Rules() |
| + f.write(t, "rules", rules) |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatalf("retry=%d", got) |
| + } |
| + f.state(t, true, false) |
| +} |
| + |
| +func TestGroupHairpinHandlerTombstones(t *testing.T) { |
| + for _, mode := range []string{"disable", "clear", "deny", "resume"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newHairpinHandlerFixture(t) |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatal(got) |
| + } |
| + switch mode { |
| + case "disable": |
| + if got := f.request(t, false, f.p); got != 204 { |
| + t.Fatal(got) |
| + } |
| + case "clear": |
| + if err := ClearGroupHairpin(f.ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "deny": |
| + f.write(t, "rules", "invalid") |
| + if err := f.s.denyLocalAddrs(f.ctx); err == nil { |
| + t.Fatal("revocation accepted") |
| + } |
| + case "resume": |
| + f.write(t, "rules", "invalid") |
| + if err := f.s.resumeGroupHairpin(f.ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + f.state(t, false, true) |
| + before, _ := os.ReadFile(filepath.Join(f.dir, "installs")) |
| + watches := f.watches |
| + if got := f.request(t, true, f.p); got != 409 { |
| + t.Fatalf("retry=%d", got) |
| + } |
| + after, _ := os.ReadFile(filepath.Join(f.dir, "installs")) |
| + if string(after) != string(before) || f.watches != watches { |
| + t.Fatal("tombstone checked after enable") |
| + } |
| + stale := f.p |
| + stale.Start += "0" |
| + if got := f.request(t, true, stale); got != 403 { |
| + t.Fatalf("stale identity=%d", got) |
| + } |
| + f.state(t, false, true) |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinHandlerRollbackFailedRemovalRestoresDeny(t *testing.T) { |
| + f := newHairpinHandlerFixture(t) |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatal(got) |
| + } |
| + f.write(t, "rules", "invalid") |
| + f.failRemove = true |
| + if got := f.request(t, true, f.p); got != 503 { |
| + t.Fatal(got) |
| + } |
| + f.state(t, false, false) |
| + if !f.addresses { |
| + t.Fatal("fixture did not retain addresses on failed removal") |
| + } |
| + f.fullDeny(t) |
| + f.failRemove = false |
| + rules, _ := f.l.Config.Rules() |
| + f.write(t, "rules", rules) |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatalf("retry=%d", got) |
| + } |
| + f.state(t, true, false) |
| +} |
| + |
| +func TestGroupHairpinHandlerEnableReadbackFailureRetries(t *testing.T) { |
| + f := newHairpinHandlerFixture(t) |
| + // Exemption refresh verifies again before the first exemption is applied. |
| + local := f.s.LocalAddrs |
| + f.s.LocalAddrs = func() ([]netip.Prefix, error) { |
| + if f.addresses { |
| + f.write(t, "rules", "invalid") |
| + } |
| + return local() |
| + } |
| + if got := f.request(t, true, f.p); got != 503 { |
| + t.Fatal(got) |
| + } |
| + f.state(t, false, false) |
| + f.fullDeny(t) |
| + f.s.LocalAddrs = local |
| + rules, _ := f.l.Config.Rules() |
| + f.write(t, "rules", rules) |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatalf("readback retry=%d", got) |
| + } |
| + f.state(t, true, false) |
| +} |
| + |
| +func TestGroupHairpinHandlerSuccessorFailedEnableRetry(t *testing.T) { |
| + f := newHairpinHandlerFixture(t) |
| + f.l.State = hairpin.State{Process: hairpin.Process{PID: 123, Start: "old", Boot: f.p.Boot}, Active: true} |
| + f.failAdd = true |
| + if got := f.request(t, true, f.p); got != 503 { |
| + t.Fatal(got) |
| + } |
| + f.state(t, false, false) |
| + if got := f.request(t, true, f.p); got != 204 { |
| + t.Fatalf("successor retry=%d", got) |
| + } |
| + f.state(t, true, false) |
| +} |
diff --git a/internal/instancectl/hairpin_test.go b/internal/instancectl/hairpin_test.go| new file mode 100644 |
| index 000000000..327ad26a4 |
| --- /dev/null |
| +++ b/internal/instancectl/hairpin_test.go |
| @@ -0,0 +1,102 @@ |
| +package instancectl |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/hairpin" |
| +) |
| + |
| +func TestGroupHairpinClientRefusal(t *testing.T) { |
| + for _, tc := range []struct { |
| + status int |
| + body string |
| + code string |
| + closed bool |
| + }{ |
| + {204, "", "", false}, |
| + {409, "group_hairpin_closed\n", "group_hairpin_closed", true}, |
| + {403, "group_hairpin_peer\n", "group_hairpin_peer", false}, |
| + {400, "group_hairpin_request\n", "group_hairpin_request", false}, |
| + {503, "group_hairpin_unavailable\n", "group_hairpin_unavailable", false}, |
| + {503, "group_hairpin_closed\n", "group_hairpin_closed", false}, |
| + {502, "unexpected response with private detail", "group_hairpin_unavailable", false}, |
| + } { |
| + t.Run(fmt.Sprintf("%d/%s", tc.status, tc.code), func(t *testing.T) { |
| + client := &Client{Dial: func(context.Context, string) (net.Conn, error) { |
| + local, remote := net.Pipe() |
| + t.Cleanup(func() { local.Close(); remote.Close() }) |
| + go func() { |
| + defer remote.Close() |
| + req, err := http.ReadRequest(bufio.NewReader(remote)) |
| + if err != nil { |
| + return |
| + } |
| + io.Copy(io.Discard, req.Body) |
| + req.Body.Close() |
| + fmt.Fprintf(remote, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", tc.status, http.StatusText(tc.status), len(tc.body), tc.body) |
| + }() |
| + return local, nil |
| + }} |
| + err := client.GroupHairpin(t.Context(), true, hairpin.Process{}) |
| + if tc.status == 204 { |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return |
| + } |
| + var failure *GroupHairpinError |
| + if !errors.As(err, &failure) || failure.StatusCode != tc.status || failure.Code != tc.code { |
| + t.Fatalf("refusal=%#v err=%v", failure, err) |
| + } |
| + wrapped := fmt.Errorf("activation: %w", err) |
| + if errors.Is(wrapped, ErrGroupHairpinClosed) != tc.closed { |
| + t.Fatalf("closed=%v error=%v", tc.closed, wrapped) |
| + } |
| + if !strings.Contains(err.Error(), tc.code) || !strings.Contains(err.Error(), fmt.Sprint(tc.status)) || strings.Contains(err.Error(), "private detail") { |
| + t.Fatalf("log message=%s", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinRefusalLogs(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, body, step, code string |
| + peer bool |
| + status int |
| + }{ |
| + {"missing-peer", `{}`, "peer", "group_hairpin_peer", false, 403}, |
| + {"malformed", `{`, "request", "group_hairpin_request", true, 400}, |
| + {"missing-enable", `{}`, "request", "group_hairpin_request", true, 400}, |
| + {"trailing", `{"enable":true} {}`, "request", "group_hairpin_request", true, 400}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + var logs []string |
| + s := &Server{Logf: func(format string, args ...any) { logs = append(logs, fmt.Sprintf(format, args...)) }} |
| + r := httptest.NewRequest("POST", "/group-hairpin", strings.NewReader(tc.body)) |
| + if tc.peer { |
| + local, remote := net.Pipe() |
| + defer local.Close() |
| + defer remote.Close() |
| + r = r.WithContext(requestConnContext(r.Context(), local)) |
| + } |
| + w := httptest.NewRecorder() |
| + s.handleHairpin(w, r) |
| + if w.Code != tc.status || strings.TrimSpace(w.Body.String()) != tc.code { |
| + t.Fatalf("response=%d %s", w.Code, w.Body.String()) |
| + } |
| + if len(logs) != 1 || !strings.Contains(logs[0], "step="+tc.step) || !strings.Contains(logs[0], "code="+tc.code) || strings.Contains(logs[0], "<nil>") { |
| + t.Fatalf("logs=%q", logs) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/instancectl/hardening.go b/internal/instancectl/hardening.go| index dab1a5430..2e4eb43dd 100644 |
| --- a/internal/instancectl/hardening.go |
| +++ b/internal/instancectl/hardening.go |
| @@ -303,6 +303,15 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| return fmt.Errorf("this box's addresses: %v; the last deny stands", err) |
| } |
| local, hairpinErr := s.hairpinDeny(ctx, local) |
| + if hairpinErr != nil { |
| + return hairpinErr |
| + } |
| + return s.applyLocalDeny(ctx, local, false) |
| +} |
| + |
| +// The caller holds denyMu. A failed hairpin readback forces a full deny even |
| +// when the last successful application already contained these addresses. |
| +func (s *Server) applyLocalDeny(ctx context.Context, local []netip.Prefix, force bool) error { |
| deny := denySet(local) |
| if len(deny) == 0 { |
| return errors.New("this box's addresses: none read; the last deny stands") |
| @@ -310,7 +319,7 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| l, group := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease) |
| s.mu.Lock() |
| unchanged := slices.Equal(deny, s.lastDeny) |
| - if group && unchanged && hairpinErr == nil { |
| + if group && unchanged && !force { |
| s.hairpinActive = l.State.Active |
| s.mu.Unlock() |
| return nil |
| @@ -328,7 +337,7 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| s.lastDeny = deny |
| s.hairpinActive = group && l.State.Active |
| s.mu.Unlock() |
| - return hairpinErr |
| + return nil |
| } |
| // denySet is local sorted by its string form, each prefix once: the deny |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index 90da0756c..a7a9ab490 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -208,6 +208,7 @@ type Server struct { |
| // and deduplicated (denySet); denyLoop compares a fresh read with it. |
| lastDeny []netip.Prefix |
| hairpinActive bool |
| + hairpinWatch groupHairpinWatch |
| // denyMu runs one denyLocalAddrs at a time (RunProbe's and denyLoop's), |
| // so an older read of the addresses is never applied over a newer one. |
| denyMu sync.Mutex |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index e153552e8..578b1aef3 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -102,3 +102,4 @@ plan14-root-reads-region-ha-p3b2-ops.tsv f9a2c93d8237229de3623f097004da568ab0cb7 |
| plan14-root-reads-agent-start-demo-analytics-fix.tsv 89841c50d08090185e24cb03c6bb4878ab8a4ccb84b7d2f0113f88b617df8026 |
| plan14-root-reads-agent-start-demo-log-skip.tsv ed24b69243622fc702159e0b22c732f4f8297438b87f10c499887cd1a13f6fce |
| plan14-root-reads-demo-api-site-route.tsv 9bfd77d30d8e3deb5f3863cb6c272c2cb46ce32aa1370acbaa6e9181b71101b4 |
| +plan14-root-reads-region-ha-p3b2-rolls.tsv c55b4a022b3d42f40a05b727f93e57dc9f76b6dc2251f7d3b777c34d7ffdee09 |
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p3b2-rolls.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p3b2-rolls.tsv| new file mode 100644 |
| index 000000000..dc75ff1b5 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-region-ha-p3b2-rolls.tsv |
| @@ -0,0 +1,18 @@ |
| +# Census overlay region-ha-p3b2-rolls, written by census-propose (#369). census-ruling-region-ha-p3b2-rolls, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p3b2-rolls.md. |
| +# 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 5 new dispositions: 0 reads re-frozen at their disposition with the claim, 3 new units frozen accepted-legacy, 2 quiet units retired while they read nothing, 0 other. |
| +@legacy fcad08aabea9d2125239440e08d34abfb71480be9344b1d05513a6833d900700 internal/instancectl/server.go type Server legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read file:Statfs@3927 13245799752194b3a1a96846dff49b479652181cc5db458c40dc26e7377f58e8 |
| +@legacy 7fd920e5ead8b623e3606c32f9b49832a0e55ac007f3f9aeea103adc85a913cd internal/instancectl/hairpin.go Client.GroupHairpin legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new read: a bounded read of the control response in the agent, code allow-listed, to return a typed status and code; root reads nothing new from an agent-writable path file:ReadAll@497 b5513261c3c987776e8ac7077dd3c62c7c0c2bc2479849284dffed9ee4030074 |
| +@legacy 17c8575ff8276279e3d65b4b04edb70a8d521115756f4987556ae77ce8ee1b99 internal/instancectl/hairpin.go newHairpinResetServer legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new function, same Systemctl runner as the one previously built inline in ClearGroupHairpin file:CommandContext@168 3fa56eab60ebe5c311d4a3ec344a4bbfafb1b5bc15a2129a9e829bee1be93055 |
| +@legacy ba3b0002d0eb263028c23c0d17f6e334f864836ca6c27615ccb8e32906fae00a internal/instancectl/hairpin.go var#1 legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new var block of test seams, including Prepare from ClearGroupHairpin and InstallDormantGroupHairpin; no production reassignment file:Prepare@436 53d945d34fa63652e07e6683a2321395b818d1cb5618537f86337c07e1c2c4af |
| +internal/instancectl/server.go type Server legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. Census ruling 292 reclassified this declaration accepted-legacy (J2,J4) for root's per-host ordering of legacy run starts against stops; this ruling kept the row as main classed it. Its own addition is the cmd start's poll and wait bounds and its per-host lock map: field declarations only;rev3=census-ruling-rootfs-apps-2;basis=new fields: HostRuntime, ProbeImage, ProbeImageFile, RootfsProbeOut, DenyEvery, the deny's lastDeny and denyMu, the rootfs probe's report and lock, the jit reload counters and imageDigests; genStarting counts binary generation starts per unit; rootfsLocksMu and rootfsLocks, one lock entry per rootfs unit name being started or removed right now, held by a start from its layout through systemctl start and its own cleanup and by a removal from its proof through the raw removal, a removal refusing while it is taken, a waiting start giving up when its request ends, an entry dropped with its last holder or waiter (fixes E6, L2, L3); rootfsProvenHook, a test hook run between the proof and the raw removal; field declarations only; no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 and #329 plan 3 Task 5: the declaration gains sliceLocks (one mutex per host slice, taken by /size and /parent) and Egress (the asserter every start path calls), and its comment names the egress allow (plan 3's ControlDropInDir field was deleted in ef38e13b, the P1 EROFS fix); the same one site, the Statfs field, offset moved; no read added.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 6: comments only: the one-shot pacing fields cover /cmd and /tty, and cmdLocks is now keyed by (role, host) (oneShotKey, PF-7) so a session's start never waits behind a command's; field declarations unchanged; the same one site, no read added;rev3=census-ruling-agent-start-demo-1;basis=Adds fixed demo configuration, registry views, derived runtime root, synchronization and purge guard.;rev3=census-ruling-region-ha-p3b;basis=Add hairpinActive boolean alongside lastDeny under existing deny synchronization. Field declaration only; existing Statfs selector unchanged, no new read or externally supplied authority.;rev3=census-ruling-region-ha-p3b2-rolls;basis=adds one field holding the current hairpin exit watcher, guarded by the root hairpin flock; no new read file:Statfs@3927 13245799752194b3a1a96846dff49b479652181cc5db458c40dc26e7377f58e8 |
| +internal/instancectl/hairpin.go Client.GroupHairpin legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new read: a bounded read of the control response in the agent, code allow-listed, to return a typed status and code; root reads nothing new from an agent-writable path file:ReadAll@497 b5513261c3c987776e8ac7077dd3c62c7c0c2bc2479849284dffed9ee4030074 |
| +internal/instancectl/hairpin.go newHairpinResetServer legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new function, same Systemctl runner as the one previously built inline in ClearGroupHairpin file:CommandContext@168 3fa56eab60ebe5c311d4a3ec344a4bbfafb1b5bc15a2129a9e829bee1be93055 |
| +internal/instancectl/hairpin.go var#1 legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3b2-rolls;basis=new var block of test seams, including Prepare from ClearGroupHairpin and InstallDormantGroupHairpin; no production reassignment file:Prepare@436 53d945d34fa63652e07e6683a2321395b818d1cb5618537f86337c07e1c2c4af |
| +@remove internal/instancectl/hairpin.go ClearGroupHairpin |
| +@removed internal/instancectl/hairpin.go ClearGroupHairpin H3 census-ruling-region-ha-p3b2-rolls;basis=quiet: the runner moved to newHairpinResetServer and Prepare to var#1 |
| +@remove internal/instancectl/hairpin.go InstallDormantGroupHairpin |
| +@removed internal/instancectl/hairpin.go InstallDormantGroupHairpin H3 census-ruling-region-ha-p3b2-rolls;basis=quiet: Prepare moved to var#1 |
| +@coverage internal/hairpin 576ee0fbd69d999ca43fa845f4c508712464e998984fafc57039f83cac8f635b |
| +@coverage internal/host 6b2a4097d40caa77f28ee9276a25b20408842961cdb968b4c05de5902787f3b5 |
| +@coverage internal/instancectl cb1573e0d1b6fd0fd685bba0e5d657d3a81350c8e544e5c48c159d7e7ebe7cc6 |
diff --git a/scripts/region-group-roll.py b/scripts/region-group-roll.py| index 0a9b11525..92f27b06a 100755 |
| --- a/scripts/region-group-roll.py |
| +++ b/scripts/region-group-roll.py |
| @@ -26,8 +26,8 @@ rollback restores the recorded old artifact in Standby, using a new rollback |
| permit in the same transaction. return performs only the return and cleanup |
| steps. status prints the saved transaction without contacting AWS. abandon |
| closes a transaction only before any group write intent was recorded. |
| -close-lost closes an active transaction after fresh group and EC2 reads prove |
| -the member is gone. It records failure and preserves any divergence flag. |
| +close-lost closes an active transaction after fresh group and EC2 reads confirm |
| +that the member is gone. It records failure and preserves any divergence flag. |
| An uncertain consumed box action stays in Standby for operator investigation. |
| The command never replays it, restarts a unit by hand, terminates a member, |
| @@ -93,8 +93,8 @@ TEXT = { |
| "return": "Return an already restarted and admitted member.", |
| "status": "Read the saved journal without contacting AWS.", |
| "abandon": "Close a transaction that has no group write intent.", |
| - "close-lost": "Close an active transaction whose member is confirmed gone, recording failure.", |
| - "close_lost_refused": "The member must be absent from the exact group and terminated or absent in EC2", |
| + "close-lost": "Close an active transaction after confirming that its member is gone. Record failure.", |
| + "close_lost_refused": "The member must be absent from the exact group and either terminated or absent from EC2.", |
| "lost_closed": "Transaction closed with outcome failed-member-lost. This does not record recovery.", |
| "divergence_retained": "Provider divergence flag retained: {path}", |
| "abandoned": "Transaction abandoned before any group write intent.", |