console stop: serialise the second signal, join nested loops
Astra round 1 on audit-console-shutdown (no P1; P2-1..4, P3), fixed: P2-1: only the stop's own goroutine reads the signal channel once a stop begins, inside its waits and at the release decision, so a second signal already queued can no longer lose to the release and a clean exit. Forced, the release decision and the exit status are one sequence. A signal during the release returns at once with status 1; a release request already sent cannot be called back, and the log and comments say so. P2-2: every loop is joined or named. StartRelay waits for its writer-lease loop before returning. StartVerifyReader returns a channel closed when its tick ends, and serve registers it with workers.Spawn (setup still synchronous, before listening). The GeoIP follower and the override's expiry watcher take a context and run as workers; work is created before them. P2-3: the stop closes worker admission before cancelling and joining; Go and Spawn refuse afterwards and report false. The startup steps after the stop is armed (managed config, demo recovery, moves paging, claim runtime) run on work's context, and a failure there during a stop waits for the stop's exit instead of exiting 1 under it. P2-4: the stuck-worker and observer tests run on a rig with no other worker and an observer already joined. P3: the rig's cleanup cancels and joins its goroutines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+555
−142
cmd/console/main.go+42 −24cmd/console/region_test.go+3 −3cmd/console/stop.go+172 −84cmd/console/stop_test.go+217 −20internal/console/geoipfollower.go+12 −5internal/console/relayops.go+11 −2internal/console/verifyreader.go+11 −4internal/console/workerjoin_test.go+87 −0
CI cancelled — superseded by a newer push — run details
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 41631e3ec..1237af9b7 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -489,7 +489,11 @@ func serve() { |
| } |
| // Before the server exists: every door that seals reads this switch. |
| appconfig.SetBoundSealing(secretsEnvelopeV2()) |
| - geoReader := consoleGeoReader(strings.TrimSpace(os.Getenv("CONSOLE_GEOIP_DB"))) |
| + // Every background loop the console runs, from the GeoIP reader's on, |
| + // runs on work's context, so a stop cancels them together and waits for |
| + // them (stop.go). |
| + work := newWorkers(context.Background(), time.Now) |
| + geoReader := consoleGeoReader(strings.TrimSpace(os.Getenv("CONSOLE_GEOIP_DB")), work) |
| regionalIngress, err := regionIngress(os.Getenv) |
| if err != nil { |
| log.Fatal(err) |
| @@ -692,9 +696,6 @@ func serve() { |
| defer cancel() |
| srv.LoadHostsMode(ctx) |
| }() |
| - // Every background loop started below runs on work's context, so a stop |
| - // cancels them together and waits for them (stop.go). |
| - work := newWorkers(context.Background(), time.Now) |
| capacityCtx, stopCapacity := context.WithCancel(work.ctx) |
| defer stopCapacity() |
| capacityDone := startHACapacity(capacityCtx, srv, cfg) |
| @@ -719,6 +720,15 @@ func serve() { |
| now: time.Now, |
| } |
| handOff := stop.untilServing(sigs, os.Exit) |
| + // The startup steps below run on work's context, which an early stop |
| + // cancels. A step that then fails is the stop's doing, not a fault: it |
| + // waits for the stop to exit instead of exiting 1 under it. |
| + fatalUnlessStopping := func(format string, a ...any) { |
| + if work.ctx.Err() != nil { |
| + handOff() // a stop has begun: blocks until it exits |
| + } |
| + log.Fatalf(format, a...) |
| + } |
| // The console mailer's identity ensure (consoleMailer above) — makes or |
| // re-reads the sending domain's SES/DKIM identity. Started here, not in |
| // NewServer, same reasoning as the alert watcher below: constructing a |
| @@ -764,14 +774,14 @@ func serve() { |
| demoView = v |
| edgesWatch = w |
| } |
| - if err := srv.SetManagedConfigWatch(context.Background(), edgesWatch); err != nil { |
| + if err := srv.SetManagedConfigWatch(work.ctx, edgesWatch); err != nil { |
| log.Printf("console: managed configuration: %v", err) |
| } |
| - recoveryCtx, recoveryCancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + recoveryCtx, recoveryCancel := context.WithTimeout(work.ctx, 10*time.Second) |
| recoveryErr := srv.ReconcileDemoJobs(recoveryCtx, true) |
| recoveryCancel() |
| if recoveryErr != nil { |
| - log.Fatalf("console: demo job recovery: %v", recoveryErr) |
| + fatalUnlessStopping("console: demo job recovery: %v", recoveryErr) |
| } |
| if demoView != nil || cfg.Demo.Enabled || cfg.Demo.BoxMode() { |
| work.Go("recordViewBackstopLoop", func(ctx context.Context) { recordViewBackstopLoop(ctx, demoView, srv) }) |
| @@ -784,14 +794,16 @@ func serve() { |
| // The restore-test reader (member backups slice 2b): every box's |
| // control/verify/<ref>.json, read at start, then per moved scope while |
| // the change index vouches, with a relist at most every 6 hours. Stored |
| - // synchronously, before the server listens; it runs its own goroutine, |
| - // which ends when work's context does (it is not joined). |
| - srv.StartVerifyReader(work.ctx, edgesWatch) |
| + // synchronously, before the server listens; its tick runs in its own |
| + // goroutine, which the stop waits for like any worker. |
| + work.Spawn("StartVerifyReader", func(ctx context.Context) <-chan struct{} { |
| + return srv.StartVerifyReader(ctx, edgesWatch) |
| + }) |
| // The move pass's pages (moves Plan 5 Task 7): the console's alert sinks, |
| // armed before the claim runtime binds the pass, so no pass runs unarmed. |
| - armMovesPaging(context.Background(), cfg, os.Getenv) |
| - if err := srv.ConfigureClaimRuntime(context.Background()); err != nil { |
| - log.Fatalf("console: claim recovery: %v", err) |
| + armMovesPaging(work.ctx, cfg, os.Getenv) |
| + if err := srv.ConfigureClaimRuntime(work.ctx); err != nil { |
| + fatalUnlessStopping("console: claim recovery: %v", err) |
| } |
| // The fleet owner record backfill (rootfs apps Plan 4 D7): once per |
| // start, every fleet's accounts/<acct>/fleets/<fleet>.json, create-only, |
| @@ -922,7 +934,7 @@ func serve() { |
| addr := envOr("CONSOLE_ADDR", "127.0.0.1:8090") |
| ln, err := net.Listen("tcp", addr) |
| if err != nil { |
| - log.Fatalf("console: listen %s: %v", addr, err) |
| + fatalUnlessStopping("console: listen %s: %v", addr, err) |
| } |
| log.Printf("console: %s listening on %s", origin, addr) |
| // ReadHeaderTimeout guards against Slowloris-style slow-header connection |
| @@ -1815,14 +1827,14 @@ func haRegionsList(v string) []string { |
| // The mapping sits behind a geo.Swappable so D1 can close it (geoip spec §0 |
| // D1, §11.3, codex R10-1): a GeoLite2 override already past its 30 days is |
| // refused here, and one that expires while the console runs is closed by |
| -// watchGeoIPExpiry. The file is the operator's; the platform never deletes |
| -// it, and the log says to replace it. |
| -func openGeoIP(path string) geo.Locator { |
| +// watchGeoIPExpiry, run as one of work's workers. The file is the |
| +// operator's; the platform never deletes it, and the log says to replace it. |
| +func openGeoIP(path string, work *workers) geo.Locator { |
| sw := openGeoIPAt(path, time.Now()) |
| if sw == nil { |
| return nil |
| } |
| - go watchGeoIPExpiry(sw, path, time.Minute, time.Now) |
| + work.Go("watchGeoIPExpiry", func(ctx context.Context) { watchGeoIPExpiry(ctx, sw, path, time.Minute, time.Now) }) |
| return sw |
| } |
| @@ -1856,10 +1868,15 @@ func openGeoIPAt(path string, now time.Time) *geo.Swappable { |
| // watchGeoIPExpiry closes the override once D1 says so. It returns when it |
| // has closed it (nothing left to watch). |
| -func watchGeoIPExpiry(sw *geo.Swappable, path string, every time.Duration, now func() time.Time) { |
| +func watchGeoIPExpiry(ctx context.Context, sw *geo.Swappable, path string, every time.Duration, now func() time.Time) { |
| t := time.NewTicker(every) |
| defer t.Stop() |
| - for range t.C { |
| + for { |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-t.C: |
| + } |
| if geoIPExpiryTick(sw, path, now()) { |
| return |
| } |
| @@ -2077,17 +2094,18 @@ func consoleBoxLabel() string { |
| // consoleGeoReader is the console's one GeoIP reader. With CONSOLE_GEOIP_DB |
| // set it is that override (opened once, D1-checked, closed at expiry); |
| // otherwise it follows the generation this box's edge mirrors, under |
| -// CARLOS_DATA_DIR (default /data) as carlos/geoip, once a minute. |
| -func consoleGeoReader(override string) *geo.Swappable { |
| +// CARLOS_DATA_DIR (default /data) as carlos/geoip, once a minute. Either |
| +// loop runs as one of work's workers. |
| +func consoleGeoReader(override string, work *workers) *geo.Swappable { |
| if override != "" { |
| - if loc, ok := openGeoIP(override).(*geo.Swappable); ok { |
| + if loc, ok := openGeoIP(override, work).(*geo.Swappable); ok { |
| return loc |
| } |
| return nil |
| } |
| sw := geo.NewSwappable() |
| f := console.NewGeoipFollower(filepath.Join(envOr("CARLOS_DATA_DIR", "/data"), "carlos", "geoip"), sw) |
| - go f.Run() |
| + work.Go("geoipFollower", f.Run) |
| return sw |
| } |
diff --git a/cmd/console/region_test.go b/cmd/console/region_test.go| index 59efe142f..b83600cf7 100644 |
| --- a/cmd/console/region_test.go |
| +++ b/cmd/console/region_test.go |
| @@ -13,10 +13,10 @@ import ( |
| ) |
| func TestOpenGeoIPIsOptionalAndNeverFatal(t *testing.T) { |
| - if openGeoIP("") != nil { |
| + if openGeoIP("", testWorkers(t)) != nil { |
| t.Fatal("unset CONSOLE_GEOIP_DB must mean no locator") |
| } |
| - if openGeoIP(filepath.Join(t.TempDir(), "missing.mmdb")) != nil { |
| + if openGeoIP(filepath.Join(t.TempDir(), "missing.mmdb"), testWorkers(t)) != nil { |
| t.Fatal("an unopenable file must mean no locator, not a crash") |
| } |
| } |
| @@ -96,7 +96,7 @@ func TestGeoIPOverrideIsClosedAtExpiryAndRefusedWhenExpired(t *testing.T) { |
| } |
| func TestConsoleGeoReaderNeverYieldsATypedNil(t *testing.T) { |
| - sw := consoleGeoReader(filepath.Join(t.TempDir(), "missing.mmdb")) |
| + sw := consoleGeoReader(filepath.Join(t.TempDir(), "missing.mmdb"), testWorkers(t)) |
| if sw != nil { |
| t.Fatal("an unusable override must give no reader") |
| } |
diff --git a/cmd/console/stop.go b/cmd/console/stop.go| index c7a31f05e..f9afb3cc8 100644 |
| --- a/cmd/console/stop.go |
| +++ b/cmd/console/stop.go |
| @@ -9,7 +9,6 @@ import ( |
| "sort" |
| "strings" |
| "sync" |
| - "sync/atomic" |
| "time" |
| ) |
| @@ -42,7 +41,8 @@ const ( |
| // same bound. At the bound, whatever still runs is named in the log and |
| // cut: request contexts cancelled, connections closed, and cutGrace for |
| // the handlers to return. |
| -// 2. Cancel the background workers' context and the HA capacity observer's, |
| +// 2. Close worker admission (a worker started from here on never runs), |
| +// cancel the background workers' context and the HA capacity observer's, |
| // and wait for both for up to workerWait, naming any worker that did not |
| // return. |
| // 3. Release the app policy writer lease, so a successor need not wait out |
| @@ -50,8 +50,11 @@ const ( |
| // order the stand-down has always kept). An observer still running |
| // leaves the lease to expire instead. |
| // |
| -// A second signal at any point stops waiting: what is running is named and |
| -// cut, the lease is left to expire, and the process exits 1. |
| +// A second signal stops waiting: what is running is named and cut, and the |
| +// process exits 1. Taken before the release decision, it also leaves the |
| +// lease to expire. Taken while a release is under way, the stop exits |
| +// without waiting for it, but a release request already sent to the store |
| +// cannot be called back, so the lease may be released anyway. |
| type consoleStop struct { |
| srv *http.Server // nil until serving: a stop before it has no requests to drain |
| reqs *requests |
| @@ -144,111 +147,162 @@ func (p *consoleStop) serve(ln net.Listener, sigs <-chan os.Signal) int { |
| return code |
| } |
| -// stop runs the three steps and reports whether a second signal cut it short. |
| -func (p *consoleStop) stop(sigs <-chan os.Signal) (forced bool) { |
| - var hurried atomic.Bool |
| - force, cancelForce := context.WithCancel(context.Background()) |
| - defer cancelForce() |
| - go func() { |
| +// stopRun is one stop in progress. Its goroutine is the only reader of sigs |
| +// from the first signal on, and it reads them only inside await and |
| +// pending, so whether a second signal has been taken (forced) is decided in |
| +// one place, in order with the waits, the release decision and the exit |
| +// status: no other goroutine can hold a signal it has taken but not yet |
| +// acted on. |
| +type stopRun struct { |
| + *consoleStop |
| + sigs <-chan os.Signal |
| + force context.Context // cancelled by a second signal |
| + cancel context.CancelFunc |
| + forced bool |
| +} |
| + |
| +// hurry acts on a second signal: every wait derived from force ends. |
| +func (r *stopRun) hurry(sig os.Signal) { |
| + if r.forced { |
| + return |
| + } |
| + r.forced = true |
| + r.logf("console: %v again: stopping now", sig) |
| + r.cancel() |
| +} |
| + |
| +// pending takes a second signal already queued, without waiting. |
| +func (r *stopRun) pending() { |
| + select { |
| + case sig := <-r.sigs: |
| + r.hurry(sig) |
| + default: |
| + } |
| +} |
| + |
| +// await waits for done until ctx (derived from force) ends, taking a second |
| +// signal if one comes, and reports whether done was closed. A done already |
| +// closed wins over a ctx already ended. |
| +func (r *stopRun) await(ctx context.Context, done <-chan struct{}) bool { |
| + for { |
| select { |
| - case sig := <-sigs: |
| - p.logf("console: %v again: stopping now", sig) |
| - hurried.Store(true) |
| - cancelForce() |
| - case <-force.Done(): |
| + case <-done: |
| + return true |
| + default: |
| } |
| - }() |
| - why := func() string { |
| - if hurried.Load() { |
| - return "at the second signal" |
| + select { |
| + case <-done: |
| + return true |
| + case <-ctx.Done(): |
| + return closed(done) |
| + case sig := <-r.sigs: |
| + r.hurry(sig) |
| } |
| - return "" |
| } |
| +} |
| + |
| +func closed(ch <-chan struct{}) bool { |
| + select { |
| + case <-ch: |
| + return true |
| + default: |
| + return false |
| + } |
| +} |
| + |
| +// stop runs the three steps and reports whether a second signal cut it short. |
| +func (p *consoleStop) stop(sigs <-chan os.Signal) (forced bool) { |
| + force, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + r := &stopRun{consoleStop: p, sigs: sigs, force: force, cancel: cancel} |
| if p.srv != nil { |
| - p.drainRequests(force, why) |
| + r.drainRequests() |
| } |
| - capacityJoined := p.stopWorkers(force, why) |
| + capacityJoined := r.stopWorkers() |
| + // The release decision. A second signal queued by now counts. |
| + r.pending() |
| switch { |
| - case hurried.Load(): |
| + case r.forced: |
| p.logf("console: stop: the policy writer lease was not released (second signal); a successor waits out its TTL") |
| return true |
| case !capacityJoined: |
| p.logf("console: stop: the HA capacity observer did not stop within %s; the policy writer lease was not released and expires on its own", p.workerWait) |
| return false |
| } |
| - p.release(force) |
| - if hurried.Load() { |
| + // From here a release is issued. A second signal stops the wait for it, |
| + // and the exit status is 1, but cannot undo a release request already |
| + // sent: the lease may be released anyway. |
| + released := make(chan struct{}) |
| + go func() { |
| + defer close(released) |
| + p.release(force) |
| + }() |
| + if !r.await(force, released) || r.forced { |
| + p.logf("console: stop: exiting during the policy writer lease release (second signal); a release already sent may still land, otherwise a successor waits out its TTL") |
| + return true |
| + } |
| + r.pending() |
| + if r.forced { |
| return true |
| } |
| p.logf("console: stopped") |
| return false |
| } |
| -func (p *consoleStop) drainRequests(force context.Context, why func() string) { |
| +// why names what ended a wait early: the second signal, or else the bound. |
| +func (r *stopRun) why(bound string) string { |
| + if r.forced { |
| + return "at the second signal" |
| + } |
| + return bound |
| +} |
| + |
| +func (r *stopRun) drainRequests() { |
| + p := r.consoleStop |
| p.logf("console: stop: not accepting connections; draining requests for up to %s", p.drain) |
| - ctx, cancel := context.WithTimeout(force, p.drain) |
| + ctx, cancel := context.WithTimeout(r.force, p.drain) |
| defer cancel() |
| - err := p.srv.Shutdown(ctx) |
| - if err == nil { |
| - // Shutdown does not wait for upgraded connections' handlers; they |
| - // were closed as it started and wind down here. |
| - err = p.reqs.run.wait(ctx) |
| - } |
| - if err == nil { |
| + shut := make(chan struct{}) |
| + var shutErr error |
| + go func() { |
| + defer close(shut) |
| + shutErr = p.srv.Shutdown(ctx) |
| + }() |
| + // Shutdown does not wait for upgraded connections' handlers; they were |
| + // closed as it started and wind down in the second wait. |
| + if r.await(ctx, shut) && shutErr == nil && r.await(ctx, p.reqs.run.done()) { |
| return |
| } |
| - reason := why() |
| - if reason == "" { |
| - reason = fmt.Sprintf("after %s", p.drain) |
| - } |
| left := p.reqs.run.labels() |
| - p.logf("console: stop: cut %d request(s) still running %s: %s", len(left), reason, strings.Join(left, ", ")) |
| + p.logf("console: stop: cut %d request(s) still running %s: %s", len(left), r.why(fmt.Sprintf("after %s", p.drain)), strings.Join(left, ", ")) |
| p.cancelRequests() |
| p.srv.Close() |
| p.reqs.closeHijacked() |
| - if force.Err() != nil { |
| + if r.forced { |
| return |
| } |
| - gctx, gcancel := context.WithTimeout(force, p.cutGrace) |
| + gctx, gcancel := context.WithTimeout(r.force, p.cutGrace) |
| defer gcancel() |
| - if p.reqs.run.wait(gctx) != nil { |
| + if !r.await(gctx, p.reqs.run.done()) { |
| left := p.reqs.run.labels() |
| p.logf("console: stop: %d handler(s) still running %s after the cut, left to the exit: %s", len(left), p.cutGrace, strings.Join(left, ", ")) |
| } |
| } |
| -// stopWorkers cancels the workers and the capacity observer and waits for |
| -// both; it reports whether the observer was joined. |
| -func (p *consoleStop) stopWorkers(force context.Context, why func() string) bool { |
| +// stopWorkers closes admission, cancels the workers and the capacity |
| +// observer and waits for both; it reports whether the observer was joined. |
| +func (r *stopRun) stopWorkers() bool { |
| + p := r.consoleStop |
| + p.work.run.closeAdmission() |
| p.work.cancel() |
| p.stopCapacity() |
| - ctx, cancel := context.WithTimeout(force, p.workerWait) |
| + ctx, cancel := context.WithTimeout(r.force, p.workerWait) |
| defer cancel() |
| - if p.work.run.wait(ctx) != nil { |
| - reason := why() |
| - if reason == "" { |
| - reason = fmt.Sprintf("within %s", p.workerWait) |
| - } |
| + if !r.await(ctx, p.work.run.done()) { |
| left := p.work.run.labels() |
| - p.logf("console: stop: %d background worker(s) did not stop %s, cut: %s", len(left), reason, strings.Join(left, ", ")) |
| - } |
| - return closedBy(ctx, p.capacityDone) |
| -} |
| - |
| -// closedBy reports whether ch is closed by the time ctx ends. A channel |
| -// already closed wins over a context already done. |
| -func closedBy(ctx context.Context, ch <-chan struct{}) bool { |
| - select { |
| - case <-ch: |
| - return true |
| - default: |
| - } |
| - select { |
| - case <-ch: |
| - return true |
| - case <-ctx.Done(): |
| - return false |
| + p.logf("console: stop: %d background worker(s) did not stop %s, cut: %s", len(left), r.why(fmt.Sprintf("within %s", p.workerWait)), strings.Join(left, ", ")) |
| } |
| + return r.await(ctx, p.capacityDone) |
| } |
| // workers runs the console's background loops on one context, so a stop |
| @@ -265,13 +319,36 @@ func newWorkers(parent context.Context, now func() time.Time) *workers { |
| } |
| // Go runs f(ctx) in its own goroutine, named so a stop that outlasts its |
| -// bound can say which worker it cut. |
| -func (w *workers) Go(name string, f func(context.Context)) { |
| +// bound can say which worker it cut. Once a stop has closed admission, f |
| +// never runs and Go reports false. |
| +func (w *workers) Go(name string, f func(context.Context)) bool { |
| e := w.run.start(name) |
| + if e == nil { |
| + return false |
| + } |
| go func() { |
| defer w.run.end(e) |
| f(w.ctx) |
| }() |
| + return true |
| +} |
| + |
| +// Spawn is Go for an entry point that does its setup synchronously, starts |
| +// its own goroutine and returns a channel closed when that goroutine ends |
| +// (StartVerifyReader): start runs in the caller, and the worker counts as |
| +// running until the channel closes. Once admission is closed, start is |
| +// never called. |
| +func (w *workers) Spawn(name string, start func(context.Context) <-chan struct{}) bool { |
| + e := w.run.start(name) |
| + if e == nil { |
| + return false |
| + } |
| + done := start(w.ctx) |
| + go func() { |
| + defer w.run.end(e) |
| + <-done |
| + }() |
| + return true |
| } |
| // requests counts the handlers running and the connections they upgraded. |
| @@ -341,14 +418,15 @@ func (q *requests) closeHijacked() int { |
| // running is a set of labelled things in progress, waited on with a bound. |
| // Not a sync.WaitGroup: an add after a wait has begun (a request read just |
| -// as the server closes) is legal here. |
| +// as the server closes) is legal here, unless admission has been closed. |
| type running struct { |
| now func() time.Time |
| - mu sync.Mutex |
| - set map[*runEntry]struct{} |
| - empty chan struct{} // made by the first wait; closed once the set is empty |
| - emptied bool |
| + mu sync.Mutex |
| + set map[*runEntry]struct{} |
| + empty chan struct{} // made by the first done; closed once the set is empty |
| + emptied bool |
| + refusing bool // admission closed: start returns nil |
| } |
| type runEntry struct { |
| @@ -360,9 +438,14 @@ func newRunning(now func() time.Time) *running { |
| return &running{now: now, set: map[*runEntry]struct{}{}} |
| } |
| +// start adds label, or returns nil once admission is closed. |
| func (r *running) start(label string) *runEntry { |
| e := &runEntry{label: label, since: r.now()} |
| r.mu.Lock() |
| + if r.refusing { |
| + r.mu.Unlock() |
| + return nil |
| + } |
| if r.emptied { |
| // A wait already saw the set empty and returned; the next one |
| // waits afresh. |
| @@ -387,19 +470,24 @@ func (r *running) signalLocked() { |
| } |
| } |
| -// wait returns nil once nothing is running, or ctx's error. |
| -func (r *running) wait(ctx context.Context) error { |
| +// closeAdmission makes every later start return nil, so the set can only |
| +// shrink and a done that closes stays true. |
| +func (r *running) closeAdmission() { |
| r.mu.Lock() |
| + r.refusing = true |
| + r.mu.Unlock() |
| +} |
| + |
| +// done returns a channel closed once nothing is running. Before admission is |
| +// closed, a later start makes the next done a fresh channel. |
| +func (r *running) done() <-chan struct{} { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| if r.empty == nil { |
| r.empty = make(chan struct{}) |
| r.signalLocked() |
| } |
| - empty := r.empty |
| - r.mu.Unlock() |
| - if closedBy(ctx, empty) { |
| - return nil |
| - } |
| - return ctx.Err() |
| + return r.empty |
| } |
| // labels names what is still running, oldest first, with how long each has |
diff --git a/cmd/console/stop_test.go b/cmd/console/stop_test.go| index 6db1dcde0..3c58b5873 100644 |
| --- a/cmd/console/stop_test.go |
| +++ b/cmd/console/stop_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "net" |
| "net/http" |
| "os" |
| + "runtime" |
| "slices" |
| "strings" |
| "sync" |
| @@ -31,19 +32,42 @@ type stopRig struct { |
| } |
| func newStopRig(t *testing.T, drain, cutGrace, workerWait time.Duration) *stopRig { |
| + return buildStopRig(t, drain, cutGrace, workerWait, false) |
| +} |
| + |
| +// newBareStopRig has no worker and an observer already joined, for the |
| +// tests about one worker or one signal, so nothing else races their bound. |
| +func newBareStopRig(t *testing.T, drain, cutGrace, workerWait time.Duration) *stopRig { |
| + return buildStopRig(t, drain, cutGrace, workerWait, true) |
| +} |
| + |
| +func buildStopRig(t *testing.T, drain, cutGrace, workerWait time.Duration, bare bool) *stopRig { |
| t.Helper() |
| r := &stopRig{t: t, sigs: make(chan os.Signal, 2)} |
| work := newWorkers(context.Background(), time.Now) |
| capacityCtx, stopCapacity := context.WithCancel(work.ctx) |
| capacityDone := make(chan struct{}) |
| - go func() { |
| - <-capacityCtx.Done() |
| - r.event("capacity joined") |
| + if bare { |
| close(capacityDone) |
| - }() |
| - work.Go("loop", func(ctx context.Context) { |
| - <-ctx.Done() |
| - r.event("worker joined") |
| + } else { |
| + go func() { |
| + <-capacityCtx.Done() |
| + r.event("capacity joined") |
| + close(capacityDone) |
| + }() |
| + work.Go("loop", func(ctx context.Context) { |
| + <-ctx.Done() |
| + r.event("worker joined") |
| + }) |
| + } |
| + // Registered first, so it runs after each test's own cleanups (which |
| + // free what the test held stuck): cancel and join the fixture's |
| + // goroutines. |
| + t.Cleanup(func() { |
| + work.cancel() |
| + stopCapacity() |
| + <-capacityDone |
| + <-work.run.done() |
| }) |
| r.stop = &consoleStop{ |
| work: work, |
| @@ -313,7 +337,7 @@ func TestConsoleStopSecondSignal(t *testing.T) { |
| // observer that is not joined keeps the lease from being released. |
| func TestConsoleStopWorkerBound(t *testing.T) { |
| t.Run("stuck worker", func(t *testing.T) { |
| - r := newStopRig(t, time.Minute, time.Minute, 50*time.Millisecond) |
| + r := newBareStopRig(t, time.Minute, time.Minute, 50*time.Millisecond) |
| unstick := make(chan struct{}) |
| t.Cleanup(func() { close(unstick) }) |
| r.stop.work.Go("StartStuckPass", func(context.Context) { <-unstick }) |
| @@ -328,7 +352,7 @@ func TestConsoleStopWorkerBound(t *testing.T) { |
| } |
| }) |
| t.Run("capacity observer not joined", func(t *testing.T) { |
| - r := newStopRig(t, time.Minute, time.Minute, 50*time.Millisecond) |
| + r := newBareStopRig(t, time.Minute, time.Minute, 50*time.Millisecond) |
| r.stop.capacityDone = make(chan struct{}) // never closed |
| if r.stop.stop(r.sigs) { |
| t.Fatal("reported a second signal") |
| @@ -370,21 +394,194 @@ func TestConsoleStopBeforeServing(t *testing.T) { |
| }) |
| } |
| -// running.wait returns at once when nothing runs, and a start after a wait |
| -// that saw it empty is waited for by the next wait. |
| -func TestRunningWaitRearms(t *testing.T) { |
| +// running.done is closed at once when nothing runs, a start after a done |
| +// that saw it empty is waited for by the next done, and once admission is |
| +// closed a start is refused. |
| +func TestRunningDoneRearms(t *testing.T) { |
| r := newRunning(time.Now) |
| - ctx, cancel := context.WithCancel(context.Background()) |
| - if err := r.wait(ctx); err != nil { |
| - t.Fatalf("empty: %v", err) |
| + if !closed(r.done()) { |
| + t.Fatal("empty: done not closed") |
| } |
| e := r.start("late") |
| - cancel() |
| - if err := r.wait(ctx); err == nil { |
| - t.Fatal("wait returned nil with one running") |
| + if closed(r.done()) { |
| + t.Fatal("done closed with one running") |
| } |
| r.end(e) |
| - if err := r.wait(context.Background()); err != nil { |
| - t.Fatalf("after end: %v", err) |
| + if !closed(r.done()) { |
| + t.Fatal("after end: done not closed") |
| + } |
| + r.closeAdmission() |
| + if r.start("later") != nil { |
| + t.Fatal("a start was admitted after admission closed") |
| + } |
| + if !closed(r.done()) { |
| + t.Fatal("a refused start reopened done") |
| } |
| } |
| + |
| +// testWorkers is a workers whose goroutines the test's cleanup cancels and |
| +// joins. |
| +func testWorkers(t *testing.T) *workers { |
| + t.Helper() |
| + w := newWorkers(context.Background(), time.Now) |
| + t.Cleanup(func() { |
| + w.cancel() |
| + <-w.run.done() |
| + }) |
| + return w |
| +} |
| + |
| +// A second signal already queued when the waits have all finished is taken |
| +// at the release decision: no release, exit status 1. GOMAXPROCS(1) keeps |
| +// any other goroutine from running before stop's first block, which made |
| +// the old asynchronous watcher lose this race every time. |
| +func TestConsoleStopQueuedSecondSignalBeforeRelease(t *testing.T) { |
| + defer runtimeGOMAXPROCS(1)() |
| + r := newBareStopRig(t, time.Minute, time.Minute, time.Minute) |
| + r.sigs <- os.Interrupt |
| + if !r.stop.stop(r.sigs) { |
| + t.Fatal("a queued second signal did not make the stop forced") |
| + } |
| + if slices.Contains(r.eventList(), "lease released") { |
| + t.Fatal("the lease was released with a second signal queued") |
| + } |
| +} |
| + |
| +// A second signal while a worker is still running ends the worker wait, |
| +// names the worker, and leaves the lease unreleased. |
| +func TestConsoleStopSecondSignalDuringWorkerWait(t *testing.T) { |
| + r := newBareStopRig(t, time.Minute, time.Minute, time.Hour) |
| + cancelled, unstick := make(chan struct{}), make(chan struct{}) |
| + t.Cleanup(func() { close(unstick) }) |
| + r.stop.work.Go("StartStuckPass", func(ctx context.Context) { |
| + <-ctx.Done() |
| + close(cancelled) |
| + <-unstick |
| + }) |
| + forced := make(chan bool, 1) |
| + go func() { forced <- r.stop.stop(r.sigs) }() |
| + guard(t, cancelled, "the worker's cancellation") |
| + r.sigs <- os.Interrupt |
| + if !guard(t, forced, "the stop returning") { |
| + t.Fatal("not reported as forced") |
| + } |
| + if slices.Contains(r.eventList(), "lease released") { |
| + t.Error("the lease was released after a second signal") |
| + } |
| + if !strings.Contains(r.log(), "1 background worker(s) did not stop at the second signal, cut: StartStuckPass (") { |
| + t.Errorf("the cut worker is not named:\n%s", r.log()) |
| + } |
| +} |
| + |
| +// A second signal during the lease release returns at once with status 1, |
| +// without waiting for a release that does not return. |
| +func TestConsoleStopSecondSignalDuringRelease(t *testing.T) { |
| + r := newBareStopRig(t, time.Minute, time.Minute, time.Minute) |
| + started, unstick := make(chan struct{}), make(chan struct{}) |
| + t.Cleanup(func() { close(unstick) }) |
| + r.stop.release = func(context.Context) { |
| + close(started) |
| + <-unstick // a release that ignores its context |
| + } |
| + forced := make(chan bool, 1) |
| + go func() { forced <- r.stop.stop(r.sigs) }() |
| + guard(t, started, "the release starting") |
| + r.sigs <- os.Interrupt |
| + if !guard(t, forced, "the stop returning") { |
| + t.Fatal("not reported as forced") |
| + } |
| + if !strings.Contains(r.log(), "exiting during the policy writer lease release") { |
| + t.Errorf("the abandoned release is not logged:\n%s", r.log()) |
| + } |
| +} |
| + |
| +// Once the stop has begun joining the workers, a worker start is refused |
| +// and never runs, and the join does not end with it running. |
| +func TestConsoleStopRefusesWorkersAfterJoinBegins(t *testing.T) { |
| + r := newBareStopRig(t, time.Minute, time.Minute, time.Hour) |
| + cancelled, unstick := make(chan struct{}), make(chan struct{}) |
| + r.stop.work.Go("StartSlowPass", func(ctx context.Context) { |
| + <-ctx.Done() |
| + close(cancelled) |
| + <-unstick |
| + }) |
| + result := make(chan bool, 1) |
| + go func() { result <- r.stop.stop(r.sigs) }() |
| + guard(t, cancelled, "the worker's cancellation") |
| + ran := make(chan struct{}) |
| + never := make(chan struct{}) |
| + t.Cleanup(func() { close(never) }) |
| + if r.stop.work.Go("late", func(context.Context) { close(ran); <-never }) { |
| + t.Error("Go admitted a worker after the join began") |
| + } |
| + if r.stop.work.Spawn("lateSpawn", func(context.Context) <-chan struct{} { close(ran); return never }) { |
| + t.Error("Spawn admitted a worker after the join began") |
| + } |
| + close(unstick) |
| + if guard(t, result, "the stop returning") { |
| + t.Fatal("reported as forced") |
| + } |
| + if closed(ran) { |
| + t.Fatal("a worker started after the join began ran") |
| + } |
| + if left := r.stop.work.run.labels(); len(left) != 0 { |
| + t.Fatalf("still running after the join: %v", left) |
| + } |
| + if !slices.Contains(r.eventList(), "lease released") { |
| + t.Error("the lease was not released") |
| + } |
| +} |
| + |
| +// A worker whose own goroutine runs past its entry point (Spawn, as the |
| +// verify reader is started) is waited for until that goroutine ends, and |
| +// named when it outlasts the bound. |
| +func TestConsoleStopNamesASpawnedWorker(t *testing.T) { |
| + r := newBareStopRig(t, time.Minute, time.Minute, 50*time.Millisecond) |
| + unstick := make(chan struct{}) |
| + t.Cleanup(func() { close(unstick) }) |
| + if !r.stop.work.Spawn("StartVerifyReader", func(ctx context.Context) <-chan struct{} { |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + <-unstick // a tick that ignores ctx |
| + }() |
| + return done |
| + }) { |
| + t.Fatal("Spawn refused before any stop") |
| + } |
| + if r.stop.stop(r.sigs) { |
| + t.Fatal("reported as forced") |
| + } |
| + if !strings.Contains(r.log(), "1 background worker(s) did not stop within 50ms, cut: StartVerifyReader (") { |
| + t.Errorf("the spawned worker is not named:\n%s", r.log()) |
| + } |
| +} |
| + |
| +// The GeoIP follower runs as a worker and ends with work's context; the |
| +// override's expiry watcher ends when its context does. |
| +func TestConsoleGeoReaderRunsAsAWorker(t *testing.T) { |
| + t.Setenv("CARLOS_DATA_DIR", t.TempDir()) |
| + w := newWorkers(context.Background(), time.Now) |
| + if consoleGeoReader("", w) == nil { |
| + t.Fatal("no follower reader") |
| + } |
| + if left := w.run.labels(); len(left) != 1 || !strings.HasPrefix(left[0], "geoipFollower (") { |
| + t.Fatalf("workers running: %v, want the follower", left) |
| + } |
| + w.cancel() |
| + guard(t, w.run.done(), "the follower ending") |
| + |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + ended := make(chan struct{}) |
| + go func() { |
| + defer close(ended) |
| + watchGeoIPExpiry(ctx, nil, "override.mmdb", time.Hour, time.Now) |
| + }() |
| + guard(t, ended, "the expiry watcher ending") |
| +} |
| + |
| +func runtimeGOMAXPROCS(n int) (restore func()) { |
| + old := runtime.GOMAXPROCS(n) |
| + return func() { runtime.GOMAXPROCS(old) } |
| +} |
diff --git a/internal/console/geoipfollower.go b/internal/console/geoipfollower.go| index eb6f75762..e1bb548e2 100644 |
| --- a/internal/console/geoipfollower.go |
| +++ b/internal/console/geoipfollower.go |
| @@ -6,6 +6,7 @@ package console |
| // database without a second download or a restart. |
| import ( |
| + "context" |
| "errors" |
| "log" |
| "os" |
| @@ -98,11 +99,17 @@ func (f *geoipFollower) logHourly(msg string) { |
| } |
| } |
| -// Run ticks once a minute, forever (process lifetime, like the console's |
| -// other loops started from cmd/console). |
| -func (f *geoipFollower) Run() { |
| - f.Tick() |
| - for range time.Tick(time.Minute) { |
| +// Run ticks at once and then once a minute until ctx ends (cmd/console |
| +// runs it as one of the workers its stop cancels and waits for). |
| +func (f *geoipFollower) Run(ctx context.Context) { |
| + t := time.NewTicker(time.Minute) |
| + defer t.Stop() |
| + for { |
| f.Tick() |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-t.C: |
| + } |
| } |
| } |
diff --git a/internal/console/relayops.go b/internal/console/relayops.go| index 1fdc144fa..1bf07a801 100644 |
| --- a/internal/console/relayops.go |
| +++ b/internal/console/relayops.go |
| @@ -268,7 +268,10 @@ func (s *Server) relayWriterLoop(ctx context.Context) { |
| // StartRelay runs the relay's two background loops: the writer lease, and the |
| // converging reconcile every five minutes and once at start. Started from |
| // cmd/console beside the other passes — never from NewServer, which stays |
| -// goroutine-free so constructing a Server in a test starts nothing. |
| +// goroutine-free so constructing a Server in a test starts nothing. It |
| +// returns only once both loops have, so the console's stop, which waits for |
| +// its workers, waits for the lease loop too and names this worker if that |
| +// loop is stuck. |
| // |
| // Gated on a configured region list rather than on holding the lease: a |
| // deployment with no relay has nothing to converge and should not be reading |
| @@ -277,7 +280,13 @@ func (s *Server) StartRelay(ctx context.Context) { |
| if s.cfg.Releases == nil || len(s.relayRegions()) == 0 { |
| return |
| } |
| - go s.relayWriterLoop(ctx) |
| + var writer sync.WaitGroup |
| + writer.Add(1) |
| + go func() { |
| + defer writer.Done() |
| + s.relayWriterLoop(ctx) |
| + }() |
| + defer writer.Wait() |
| // The first reconcile is the one that finishes whatever the previous |
| // holder abandoned, so it is worth a short wait for the lease rather |
| // than five minutes of drift. |
diff --git a/internal/console/verifyreader.go b/internal/console/verifyreader.go| index 80049a344..a5373b30c 100644 |
| --- a/internal/console/verifyreader.go |
| +++ b/internal/console/verifyreader.go |
| @@ -612,16 +612,22 @@ func verifyRefOfScope(scope string) (string, bool) { |
| // ctx ends. Not on a console without a deployment store, nor on a |
| // host-claim console. watch is the record view's change watch, nil when the |
| // index is not armed (start and relists only). Call it once, before the |
| -// server listens; a second call is a no-op. |
| -func (s *Server) StartVerifyReader(ctx context.Context, watch *release.ChangeWatch) { |
| +// server listens; a second call is a no-op. The returned channel closes |
| +// when the tick has stopped (at once when none was started), so the |
| +// console's stop can wait for it. |
| +func (s *Server) StartVerifyReader(ctx context.Context, watch *release.ChangeWatch) <-chan struct{} { |
| + done := make(chan struct{}) |
| if s.cfg.Releases == nil || s.cfg.HostClaim { |
| - return |
| + close(done) |
| + return done |
| } |
| r := newVerifyReader(s.cfg.Releases, watch, time.Now) |
| if !s.verify.CompareAndSwap(nil, r) { |
| - return |
| + close(done) |
| + return done |
| } |
| go func() { |
| + defer close(done) |
| for { |
| tctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout) |
| r.tick(tctx, r.now()) |
| @@ -633,4 +639,5 @@ func (s *Server) StartVerifyReader(ctx context.Context, watch *release.ChangeWat |
| } |
| } |
| }() |
| + return done |
| } |
diff --git a/internal/console/workerjoin_test.go b/internal/console/workerjoin_test.go| new file mode 100644 |
| index 000000000..ab1aabc96 |
| --- /dev/null |
| +++ b/internal/console/workerjoin_test.go |
| @@ -0,0 +1,87 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// heldGetStore holds every Get until unblock closes, ignoring ctx, the way |
| +// a stuck store call holds the relay's lease loop. |
| +type heldGetStore struct { |
| + release.Store |
| + once sync.Once |
| + entered chan struct{} |
| + unblock chan struct{} |
| +} |
| + |
| +func (h *heldGetStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + h.once.Do(func() { close(h.entered) }) |
| + <-h.unblock |
| + return nil, "", errors.New("held store") |
| +} |
| + |
| +// StartRelay returns only after its writer-lease loop has: cmd/console's |
| +// stop waits for StartRelay, so a lease loop it left behind would run on |
| +// past the stop's join and never be named. |
| +func TestStartRelayJoinsItsWriterLoop(t *testing.T) { |
| + st := &heldGetStore{Store: release.NewDirStore(t.TempDir()), entered: make(chan struct{}), unblock: make(chan struct{})} |
| + s := &Server{cfg: Config{Releases: st, RelayRegions: []string{"eu-west-1"}}} |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + returned := make(chan struct{}) |
| + go func() { |
| + defer close(returned) |
| + s.StartRelay(ctx) |
| + }() |
| + select { |
| + case <-st.entered: |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("the writer loop never read the lease") |
| + } |
| + cancel() |
| + // Proving that something does NOT return needs a window: the main loop |
| + // returns within milliseconds of the cancel when it does not join. |
| + select { |
| + case <-returned: |
| + close(st.unblock) |
| + t.Fatal("StartRelay returned while its writer loop was still in a store call") |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + close(st.unblock) |
| + select { |
| + case <-returned: |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("StartRelay did not return once its writer loop could") |
| + } |
| +} |
| + |
| +// StartVerifyReader's channel closes when its tick goroutine ends, and at |
| +// once when it starts none. |
| +func TestStartVerifyReaderReportsItsEnd(t *testing.T) { |
| + srv, err := NewServer(Config{Releases: release.NewDirStore(t.TempDir())}, openTestStore(t)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := srv.StartVerifyReader(ctx, nil) |
| + select { |
| + case <-done: |
| + t.Fatal("closed while the tick runs") |
| + default: |
| + } |
| + select { |
| + case <-srv.StartVerifyReader(ctx, nil): |
| + default: |
| + t.Fatal("a second call, which starts nothing, did not close at once") |
| + } |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("the tick did not end with its context") |
| + } |
| +} |