| new file mode 100644 |
| index 000000000..87ed0187d |
| --- /dev/null |
| +++ b/internal/host/group_hairpin_retry_test.go |
| @@ -0,0 +1,394 @@ |
| +package host |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "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/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") |
| + } |
| + }) |
| + } |
| +} |