| index 04200e3b7..adb71a6d6 100644 |
| --- a/internal/host/ingressdrain_rootrunner_linux_test.go |
| +++ b/internal/host/ingressdrain_rootrunner_linux_test.go |
| @@ -34,8 +34,10 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "io" |
| "log" |
| "net/http" |
| + "net/http/httptrace" |
| "os" |
| "os/exec" |
| "os/signal" |
| @@ -45,10 +47,12 @@ import ( |
| "strconv" |
| "strings" |
| "sync" |
| + "sync/atomic" |
| "syscall" |
| "testing" |
| "time" |
| |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| "github.com/carlosframework/platform/internal/ingresshealth" |
| ) |
| |
| @@ -59,10 +63,6 @@ const ( |
| ingressRootEdgeUnit = "carlos-edge.service" |
| // The fake turns the box unhealthy this long after the drain starts. |
| ingressRootUnhealthyAfter = 10 * time.Second |
| - // A request started this close to step 3 may still be on a connection |
| - // whose headers have not all arrived when Shutdown runs: spec §3 |
| - // refuses that case up front, so the loop does not count it. |
| - ingressRootStep3Guard = 50 * time.Millisecond |
| ) |
| |
| // systemd's catalogue message ids for unit job messages. |
| @@ -112,8 +112,30 @@ func (f *ingressRootFake) Retention(context.Context) ([]ingresshealth.Retention, |
| return out, nil |
| } |
| |
| -// ingressRootArmFake runs in the agent process (terminateRootAgent). |
| +// ingressRootQueue is an empty termination queue: no box in the fixture |
| +// is ever terminated. Receive waits like a short long poll, so the |
| +// consumer does not spin. |
| +type ingressRootQueue struct{} |
| + |
| +func (ingressRootQueue) Receive(ctx context.Context, _ time.Duration) ([]hadeparture.Message, error) { |
| + select { |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + case <-time.After(time.Second): |
| + return nil, nil |
| + } |
| +} |
| + |
| +func (ingressRootQueue) Delete(context.Context, string) error { return nil } |
| + |
| +// ingressRootArmFake runs in the agent process (terminateRootAgent). Fixed |
| +// admission waits for the termination consumer's first receive |
| +// (TerminationStarted); production reads SQS through |
| +// CARLOS_TERMINATION_QUEUE_URL, which the runner cannot have, so the |
| +// rootrunner-tagged seam supplies an empty queue. The consumer's journal and |
| +// proof-store checks still run against the fixture's stores. |
| func ingressRootArmFake() { |
| + rootrunnerDepartureQueue = func(context.Context) (hadeparture.Queue, error) { return ingressRootQueue{}, nil } |
| newIngressReader = func(_ context.Context, region string, groups []string) (ingresshealth.Reader, error) { |
| log.Printf("ingress root fixture: fake target health for %d group(s) in %s: healthy until %s from now, then unhealthy", len(groups), region, ingressRootUnhealthyAfter) |
| return &ingressRootFake{start: time.Now(), groups: groups}, nil |
| @@ -189,15 +211,16 @@ func newIngressRootFixture(t *testing.T) *ingressRootFixture { |
| lifecycleCheck(t, "request template", err) |
| coldRootAuthorize(t, req) |
| x := &ingressRootFixture{t: t, f: f, request: req} |
| - x.awaitServing("first wake") |
| + x.awaitServing("first wake", time.Time{}) |
| return x |
| } |
| |
| // awaitServing waits for the tenant to answer through the edge (admission |
| // open, tenant awake), and for the drain unit to be active. |
| -func (x *ingressRootFixture) awaitServing(why string) { |
| +func (x *ingressRootFixture) awaitServing(why string, since time.Time) { |
| t := x.t |
| t.Helper() |
| + ingressRootAwaitAdmission(t, why, since) |
| client := coldRootClient(t, "127.0.0.1:443") |
| defer client.CloseIdleConnections() |
| deadline := time.Now().Add(3 * time.Minute) |
| @@ -228,6 +251,39 @@ func (x *ingressRootFixture) awaitServing(why string) { |
| t.Logf("%s: tenant serving, drain unit active", why) |
| } |
| |
| +// ingressRootAwaitAdmission fails fast when fixed admission does not open |
| +// within 90 s of the agent's start (since; zero for this boot's first |
| +// start), naming the admission's last waiting line. |
| +func ingressRootAwaitAdmission(t *testing.T, why string, since time.Time) { |
| + t.Helper() |
| + deadline := time.Now().Add(90 * time.Second) |
| + for { |
| + args := []string{"-b", "--no-pager", "-o", "cat", "-u", ingressRootEdgeUnit} |
| + if !since.IsZero() { |
| + args = append(args, "--since", since.UTC().Format("2006-01-02 15:04:05")+" UTC") |
| + } |
| + out, _ := exec.Command("journalctl", args...).Output() |
| + open, waiting := false, "" |
| + for _, l := range strings.Split(string(out), "\n") { |
| + switch { |
| + case strings.Contains(l, "tenant admission is open"): |
| + open = true |
| + case strings.Contains(l, "tenant admission is closed for shutdown"): |
| + open = false |
| + case strings.Contains(l, "tenant admission is still closed") || strings.Contains(l, "tenant admission is closed."): |
| + waiting = l |
| + } |
| + } |
| + if open { |
| + return |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("%s: fixed admission did not open within 90 s; last: %q\n%s", why, waiting, ingressRootAdmissionLog()) |
| + } |
| + time.Sleep(time.Second) |
| + } |
| +} |
| + |
| func ingressRootAdmissionLog() string { |
| out, _ := exec.Command("journalctl", "-b", "--no-pager", "-u", ingressRootEdgeUnit, "-n", "400").CombinedOutput() |
| var keep []string |
| @@ -244,13 +300,7 @@ func ingressRootGet(client *http.Client, tmpl *http.Request) (bool, string) { |
| if err != nil { |
| return false, err.Error() |
| } |
| - defer resp.Body.Close() |
| - body := make([]byte, 64) |
| - n, _ := resp.Body.Read(body) |
| - if resp.StatusCode != 200 || string(body[:n]) != "lifecycle tenant" { |
| - return false, fmt.Sprintf("%d %q", resp.StatusCode, body[:n]) |
| - } |
| - return true, "" |
| + return ingressRootRead(resp) |
| } |
| |
| // tenantUnits is every unit bound to the edge other than the drain unit: |
| @@ -298,102 +348,195 @@ func ingressRootKeys(m map[string]bool) []string { |
| return out |
| } |
| |
| -// IngressRootSample is one request of the loop. |
| +// IngressRootSample is one request of the loop. Wrote is when the client |
| +// finished writing the request (httptrace WroteRequest): the dispatch |
| +// evidence for a request that spans step 3. Unfinished marks a request |
| +// still outstanding when the loop's bounded wait ran out. |
| type IngressRootSample struct { |
| - Start time.Time `json:"start"` |
| - End time.Time `json:"end"` |
| - OK bool `json:"ok"` |
| - Close bool `json:"close"` |
| - Detail string `json:"detail,omitempty"` |
| + Start time.Time `json:"start"` |
| + Wrote time.Time `json:"wrote,omitzero"` |
| + End time.Time `json:"end,omitzero"` |
| + OK bool `json:"ok"` |
| + Close bool `json:"close"` |
| + Unfinished bool `json:"unfinished,omitempty"` |
| + Detail string `json:"detail,omitempty"` |
| +} |
| + |
| +// ingressRootBody is the most of a response body the loop reads; the |
| +// tenant answers 16 bytes. |
| +const ingressRootBody = 4096 |
| + |
| +// ingressRootRead reads a response to EOF (bounded) and says whether it is |
| +// the tenant's answer, and if not why. |
| +func ingressRootRead(resp *http.Response) (bool, string) { |
| + defer resp.Body.Close() |
| + body, err := io.ReadAll(io.LimitReader(resp.Body, ingressRootBody+1)) |
| + switch { |
| + case err != nil: |
| + return false, fmt.Sprintf("%d: reading the body: %v", resp.StatusCode, err) |
| + case len(body) > ingressRootBody: |
| + return false, fmt.Sprintf("%d: body over %d bytes", resp.StatusCode, ingressRootBody) |
| + case resp.StatusCode != 200 || string(body) != "lifecycle tenant": |
| + return false, fmt.Sprintf("%d %q", resp.StatusCode, body) |
| + } |
| + return true, "" |
| } |
| |
| // ingressRootLoop is the request loop through the edge: two workers, each |
| -// one request at a time. |
| +// one request at a time. Stopping it stops new requests only: every |
| +// request already sent is waited for (bounded), so none drops out of the |
| +// record. |
| type ingressRootLoop struct { |
| - mu sync.Mutex |
| - samples []IngressRootSample |
| - cancel context.CancelFunc |
| - wg sync.WaitGroup |
| + mu sync.Mutex |
| + samples []IngressRootSample |
| + inflight map[int]*ingressRootFlight |
| + stopping chan struct{} |
| + once sync.Once |
| + wg sync.WaitGroup |
| +} |
| + |
| +// ingressRootFlight is a request in flight. wrote (Unix ns, 0 until the |
| +// client has written the request) is set from the transport's goroutine. |
| +type ingressRootFlight struct { |
| + start time.Time |
| + wrote atomic.Int64 |
| +} |
| + |
| +func (f *ingressRootFlight) wroteAt() time.Time { |
| + if ns := f.wrote.Load(); ns != 0 { |
| + return time.Unix(0, ns) |
| + } |
| + return time.Time{} |
| } |
| |
| +// ingressRootLoopWait bounds the wait for outstanding requests: past the |
| +// clients' own 40 s timeout. |
| +const ingressRootLoopWait = 45 * time.Second |
| + |
| func (x *ingressRootFixture) startLoop() *ingressRootLoop { |
| - ctx, cancel := context.WithCancel(context.Background()) |
| - l := &ingressRootLoop{cancel: cancel} |
| - for range 2 { |
| + l := &ingressRootLoop{inflight: map[int]*ingressRootFlight{}, stopping: make(chan struct{})} |
| + for w := range 2 { |
| client := coldRootClient(x.t, "127.0.0.1:443") |
| client.Timeout = 40 * time.Second |
| l.wg.Add(1) |
| go func() { |
| defer l.wg.Done() |
| defer client.CloseIdleConnections() |
| - for ctx.Err() == nil { |
| - s := IngressRootSample{Start: time.Now()} |
| - resp, err := client.Do(x.request.Clone(ctx)) |
| + for { |
| + select { |
| + case <-l.stopping: |
| + return |
| + default: |
| + } |
| + f := &ingressRootFlight{start: time.Now()} |
| + l.mu.Lock() |
| + l.inflight[w] = f |
| + l.mu.Unlock() |
| + trace := &httptrace.ClientTrace{WroteRequest: func(httptrace.WroteRequestInfo) { f.wrote.Store(time.Now().UnixNano()) }} |
| + // Not the stop's context: a request already sent runs to |
| + // its answer or the client's timeout. |
| + req := x.request.Clone(httptrace.WithClientTrace(context.Background(), trace)) |
| + resp, err := client.Do(req) |
| + done := IngressRootSample{Start: f.start} |
| if err != nil { |
| - s.Detail = err.Error() |
| + done.Detail = err.Error() |
| } else { |
| - body := make([]byte, 64) |
| - n, _ := resp.Body.Read(body) |
| - resp.Body.Close() |
| - s.Close = resp.Close |
| - s.OK = resp.StatusCode == 200 && string(body[:n]) == "lifecycle tenant" |
| - if !s.OK { |
| - s.Detail = fmt.Sprintf("%d %q", resp.StatusCode, body[:n]) |
| - } |
| - } |
| - s.End = time.Now() |
| - if ctx.Err() != nil && !s.OK { |
| - return |
| + done.Close = resp.Close |
| + done.OK, done.Detail = ingressRootRead(resp) |
| } |
| + done.Wrote, done.End = f.wroteAt(), time.Now() |
| l.mu.Lock() |
| - l.samples = append(l.samples, s) |
| + delete(l.inflight, w) |
| + l.samples = append(l.samples, done) |
| l.mu.Unlock() |
| - time.Sleep(50 * time.Millisecond) |
| + select { |
| + case <-l.stopping: |
| + return |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| } |
| }() |
| } |
| - x.t.Cleanup(l.stop) |
| + x.t.Cleanup(func() { l.finish() }) |
| return l |
| } |
| |
| -func (l *ingressRootLoop) stop() { |
| - l.cancel() |
| - l.wg.Wait() |
| -} |
| - |
| -func (l *ingressRootLoop) snapshot() []IngressRootSample { |
| +// finish stops new requests, waits up to ingressRootLoopWait for the |
| +// outstanding ones, and returns every sample. A request still outstanding |
| +// at the bound is recorded unfinished, which is a failure. |
| +func (l *ingressRootLoop) finish() []IngressRootSample { |
| + l.once.Do(func() { close(l.stopping) }) |
| + waited := make(chan struct{}) |
| + go func() { l.wg.Wait(); close(waited) }() |
| + select { |
| + case <-waited: |
| + case <-time.After(ingressRootLoopWait): |
| + } |
| l.mu.Lock() |
| defer l.mu.Unlock() |
| - return append([]IngressRootSample(nil), l.samples...) |
| + out := append([]IngressRootSample(nil), l.samples...) |
| + for _, f := range l.inflight { |
| + out = append(out, IngressRootSample{Start: f.start, Wrote: f.wroteAt(), Unfinished: true, Detail: fmt.Sprintf("still outstanding after %s", ingressRootLoopWait)}) |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].Start.Before(out[j].Start) }) |
| + return out |
| } |
| |
| // checkIngressRootLoop is spec §9's "request loop at 0 failures until step |
| -// 3": every request started before the listeners began to close succeeded, |
| -// requests went on being served during the drain, and they carried |
| +// 3" (step 3 begins at the report's wait_ended_at): |
| +// - a request that ended before step 3 must have succeeded, whatever it |
| +// met (a 503, a reset); |
| +// - a request that started before step 3 and ended after it, or never |
| +// ended, must have succeeded if the client had finished writing it |
| +// before step 3: it was the box's to answer (§3). One not fully |
| +// written by then is the incomplete-header case §3 leaves out, and is |
| +// only logged; |
| +// - a request that started at or after step 3 is not counted. |
| +// |
| +// Requests must also have been served during the drain, with |
| // Connection: close (step 1). |
| -func checkIngressRootLoop(t *testing.T, samples []IngressRootSample, rep *ingressReport) { |
| - t.Helper() |
| - step1, step3 := *rep.HealthFailedAt, *rep.WaitEndedAt |
| - var failed []IngressRootSample |
| - before, during, closing := 0, 0, 0 |
| +type ingressRootLoopCounts struct { |
| + failed, excluded []IngressRootSample |
| + before, during, closing int |
| +} |
| + |
| +func classifyIngressRootLoop(samples []IngressRootSample, step1, step3 time.Time) ingressRootLoopCounts { |
| + var c ingressRootLoopCounts |
| for _, s := range samples { |
| - if !s.Start.Before(step3.Add(-ingressRootStep3Guard)) { |
| + if !s.Start.Before(step3) { |
| continue |
| } |
| if !s.OK { |
| - failed = append(failed, s) |
| + ended := !s.Unfinished && s.End.Before(step3) |
| + dispatched := !s.Wrote.IsZero() && s.Wrote.Before(step3) |
| + if ended || dispatched { |
| + c.failed = append(c.failed, s) |
| + } else { |
| + c.excluded = append(c.excluded, s) |
| + } |
| continue |
| } |
| if s.Start.Before(step1) { |
| - before++ |
| + c.before++ |
| } else { |
| - during++ |
| + c.during++ |
| if s.Close { |
| - closing++ |
| + c.closing++ |
| } |
| } |
| } |
| - t.Logf("request loop: %d sample(s); before step 3: %d served before the drain, %d during it (%d with Connection: close), %d failed", len(samples), before, during, closing, len(failed)) |
| + return c |
| +} |
| + |
| +func checkIngressRootLoop(t *testing.T, samples []IngressRootSample, rep *ingressReport) { |
| + t.Helper() |
| + step3 := *rep.WaitEndedAt |
| + c := classifyIngressRootLoop(samples, *rep.HealthFailedAt, step3) |
| + for _, s := range c.excluded { |
| + t.Logf("not counted (not fully sent before step 3, spec §3): %+v", s) |
| + } |
| + failed, before, during, closing := c.failed, c.before, c.during, c.closing |
| + t.Logf("request loop: %d sample(s); started before step 3: %d served before the drain, %d during it (%d with Connection: close), %d failed, %d not counted", len(samples), before, during, closing, len(failed), len(c.excluded)) |
| if len(failed) > 0 { |
| if len(failed) > 5 { |
| failed = failed[:5] |
| @@ -568,9 +711,9 @@ func ts(t time.Time) string { |
| |
| // afterRestart is spec §9's "drain unit active again after the restart", |
| // with the tenant serving through the new agent. |
| -func (x *ingressRootFixture) afterRestart(why string) { |
| +func (x *ingressRootFixture) afterRestart(why string, since time.Time) { |
| x.f.waitLeo() |
| - x.awaitServing(why) |
| + x.awaitServing(why, since) |
| } |
| |
| // TestRootIngressDrainOrderRestart: `systemctl restart carlos-edge` on a |
| @@ -584,9 +727,8 @@ func TestRootIngressDrainOrderRestart(t *testing.T) { |
| out, err := exec.Command("systemctl", "restart", ingressRootEdgeUnit).CombinedOutput() |
| lifecycleCheck(t, "restart "+string(out), err) |
| stop := ingressRootOrder(t, ingressRootJournal(t, since), tenants, false) |
| - loop.stop() |
| - checkIngressRootLoop(t, loop.snapshot(), stop.Report) |
| - x.afterRestart("after restart") |
| + checkIngressRootLoop(t, loop.finish(), stop.Report) |
| + x.afterRestart("after restart", since) |
| } |
| |
| // TestRootIngressDrainOrderAutoRestart: the agent is killed (SIGKILL to the |
| @@ -627,7 +769,7 @@ func TestRootIngressDrainOrderAutoRestart(t *testing.T) { |
| } |
| time.Sleep(200 * time.Millisecond) |
| } |
| - x.afterRestart("after automatic restart") |
| + x.afterRestart("after automatic restart", since) |
| ingressRootOrder(t, ingressRootJournal(t, since), tenants, true) |
| } |
| |
| @@ -658,8 +800,7 @@ func TestRootIngressDrainOrderVerbAsk(t *testing.T) { |
| if rep == nil || rep.Result != "done" || rep.Verdict != ingressWithdrawn || rep.WaitEndedAt == nil || rep.HealthFailedAt == nil || rep.StartedAt == nil { |
| t.Fatalf("the verbs' drain: want done and withdrawn: %+v", r) |
| } |
| - loop.stop() |
| - checkIngressRootLoop(t, loop.snapshot(), rep) |
| + checkIngressRootLoop(t, loop.finish(), rep) |
| out, err := exec.Command("systemctl", "restart", ingressRootEdgeUnit).CombinedOutput() |
| lifecycleCheck(t, "restart "+string(out), err) |
| stop := ingressRootOrder(t, ingressRootJournal(t, since), tenants, false) |
| @@ -672,7 +813,7 @@ func TestRootIngressDrainOrderVerbAsk(t *testing.T) { |
| if took := stop.DrainEnd.Sub(stop.DrainStopping); took > 2*time.Second { |
| t.Fatalf("joining a finished drain took %s", took) |
| } |
| - x.afterRestart("after the verb's drain and restart") |
| + x.afterRestart("after the verb's drain and restart", since) |
| } |
| |
| // The reboot pair. Phase 1 runs the fixture in a transient unit that |
| @@ -740,8 +881,9 @@ func ingressRootRebootPayload(t *testing.T) { |
| <-stopped |
| // The edge has stopped (this unit is ordered after it at shutdown): |
| // keep what the loop saw for phase 2. |
| - loop.cancel() |
| - samples, err := json.Marshal(loop.snapshot()) |
| + // finish waits (bounded) for every request already sent; with the |
| + // edge gone they end at once. TimeoutStopSec=90s covers the bound. |
| + samples, err := json.Marshal(loop.finish()) |
| lifecycleCheck(t, "loop samples", err) |
| ingressRootWriteDurable(t, "samples.json", samples) |
| // Shutdown owns the machine now; no fixture cleanups. |
| @@ -788,3 +930,32 @@ func TestRootRebootIngressDrainOrderPhase2(t *testing.T) { |
| // The runner is terminated after this phase; the fixture it left on |
| // disk goes with it. |
| } |
| + |
| +// The loop's step 3 classification, without root. |
| +func TestIngressRootLoopClassify(t *testing.T) { |
| + step1 := time.Date(2026, 11, 10, 12, 0, 0, 0, time.UTC) |
| + step3 := step1.Add(20 * time.Second) |
| + at := func(d time.Duration) time.Time { return step3.Add(d) } |
| + samples := []IngressRootSample{ |
| + {Start: step1.Add(-time.Second), Wrote: step1.Add(-time.Second), End: step1, OK: true}, |
| + {Start: at(-5 * time.Second), Wrote: at(-5 * time.Second), End: at(-4 * time.Second), OK: true, Close: true}, |
| + // Failed and ended before step 3: counted, however close to it. |
| + {Start: at(-10 * time.Millisecond), Wrote: at(-9 * time.Millisecond), End: at(-time.Millisecond), Detail: "503"}, |
| + // Spans step 3, fully sent before it: counted. |
| + {Start: at(-time.Second), Wrote: at(-time.Second), End: at(time.Second), Detail: "reset"}, |
| + // Outstanding at the bound, sent before step 3: counted. |
| + {Start: at(-2 * time.Second), Wrote: at(-2 * time.Second), Unfinished: true}, |
| + // Spans step 3, not fully sent before it: §3's exclusion. |
| + {Start: at(-time.Millisecond), Wrote: at(time.Millisecond), End: at(2 * time.Millisecond), Detail: "EOF"}, |
| + {Start: at(-time.Millisecond), End: at(2 * time.Millisecond), Detail: "EOF before write"}, |
| + // Started after step 3: not counted. |
| + {Start: at(time.Second), End: at(2 * time.Second), Detail: "refused"}, |
| + } |
| + c := classifyIngressRootLoop(samples, step1, step3) |
| + if len(c.failed) != 3 || c.failed[0].Detail != "503" || c.failed[1].Detail != "reset" || !c.failed[2].Unfinished { |
| + t.Fatalf("failed: %+v", c.failed) |
| + } |
| + if len(c.excluded) != 2 || c.before != 1 || c.during != 1 || c.closing != 1 { |
| + t.Fatalf("counts: %+v", c) |
| + } |
| +} |