carlos / platform Public

console: graceful stop drains requests and joins workers

SIGTERM used to stop the HA capacity observer, release the app policy
writer lease and os.Exit(0): the HTTP server was never shut down, so
every console roll dropped requests in flight, and the background
workers ran on context.Background() and were cut mid-work.

The stop (cmd/console/stop.go) now, in order:
1. closes the listener (new connections refused) and drains requests
   with http.Server.Shutdown for up to 20 s. Upgraded connections (the
   WebSocket doors), which Shutdown does not track, are closed as it
   starts so their handlers wind down inside the bound. At the bound
   the requests still running are named in the log (method and path,
   no query) and cut: request contexts cancelled, connections closed,
   2 s for handlers to return.
2. cancels one worker context that every background loop in serve now
   runs on (all claim workers, demo jobs, region names, the backfills,
   the mail ensure and sweeps, the record view backstop), with the
   capacity observer's context its child, and waits up to 10 s, naming
   any worker it cut.
3. releases the policy writer lease, only once the capacity observer
   has been joined (the order the stand-down already kept); an
   observer still running leaves the lease to its TTL.

A second signal stops waiting, cuts what runs, leaves the lease and
exits 1. A signal before serving begins runs steps 2 and 3. Worst case
37 s against systemd's default 90 s TimeoutStopSec (console.service
names none).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b4e7a657072895e7ff63c5d4028d92b2a310453e parent c4b44c3
7 files changed, +932 −68
  • cmd/console/claim_sweep_test.go +1 −1
  • cmd/console/claimworkers_started_test.go +10 −1
  • cmd/console/hacapacity_test.go +30 −6
  • cmd/console/main.go +79 −59
  • cmd/console/plansponsor_test.go +1 −1
  • cmd/console/stop.go +421 −0
  • cmd/console/stop_test.go +390 −0

CI cancelled — superseded by a newer push — run details

diff --git a/cmd/console/claim_sweep_test.go b/cmd/console/claim_sweep_test.go
index 42c574a20..aaf2a719d 100644
--- a/cmd/console/claim_sweep_test.go
+++ b/cmd/console/claim_sweep_test.go
@@ -38,7 +38,7 @@ func TestClaimLegacySweepRefusesEnabled(t *testing.T) {
old := log.Writer()
log.SetOutput(&logs)
defer log.SetOutput(old)
- sweepLegacyMail(enabled, s, st)
+ sweepLegacyMail(ctx, enabled, s, st)
_, _, err = s.Get(ctx, key)
if enabled {
if err != nil {
diff --git a/cmd/console/claimworkers_started_test.go b/cmd/console/claimworkers_started_test.go
index 8ca9f24eb..b0b4e8964 100644
--- a/cmd/console/claimworkers_started_test.go
+++ b/cmd/console/claimworkers_started_test.go
@@ -23,10 +23,19 @@ func TestEveryRegisteredClaimWorkerIsStarted(t *testing.T) {
if len(registered) < 10 {
t.Fatalf("found only %d registered workers; the pattern no longer matches claim_workers.go", len(registered))
}
+ // Each is started through startClaimWorker, which runs it on the stop's
+ // worker context (stop.go), never on a background one a stop cannot
+ // cancel or wait for.
started := map[string]bool{}
- for _, m := range regexp.MustCompile(`RunClaimWorker\(context\.Background\(\), "([A-Za-z]+)"\)`).FindAllSubmatch(main, -1) {
+ for _, m := range regexp.MustCompile(`(?m)^\tstartClaimWorker\("([A-Za-z]+)"\)$`).FindAllSubmatch(main, -1) {
started[string(m[1])] = true
}
+ if !regexp.MustCompile(`startClaimWorker := func\(name string\) \{\s+work\.Go\(name, func\(ctx context\.Context\) \{ srv\.RunClaimWorker\(ctx, name\) \}\)`).Match(main) {
+ t.Error("startClaimWorker no longer runs RunClaimWorker on work's context")
+ }
+ if regexp.MustCompile(`RunClaimWorker\(context\.Background\(\)`).Match(main) {
+ t.Error("a claim worker is started on context.Background(), which a stop cannot cancel or wait for")
+ }
names := map[string]bool{}
for _, m := range registered {
name := string(m[1])
diff --git a/cmd/console/hacapacity_test.go b/cmd/console/hacapacity_test.go
index 9de008463..3108ab8e6 100644
--- a/cmd/console/hacapacity_test.go
+++ b/cmd/console/hacapacity_test.go
@@ -59,9 +59,36 @@ func TestHACapacityServeWiring(t *testing.T) {
if serve == nil {
t.Fatal("serve missing")
}
- var starts, stops, waits int
+ var starts, stops, handed int
fields := map[string]string{}
ast.Inspect(serve.Body, func(n ast.Node) bool {
+ // The stop (stop.go) is handed the observer's cancel and its join;
+ // TestConsoleStopOrder proves it cancels and joins it before the
+ // lease release.
+ if lit, ok := n.(*ast.CompositeLit); ok {
+ if u, ok := lit.Type.(*ast.Ident); ok && u.Name == "consoleStop" {
+ for _, e := range lit.Elts {
+ if kv, ok := e.(*ast.KeyValueExpr); ok {
+ switch {
+ case isIdent(kv.Key, "stopCapacity") && isIdent(kv.Value, "stopCapacity"),
+ isIdent(kv.Key, "capacityDone") && isIdent(kv.Value, "capacityDone"):
+ handed++
+ }
+ }
+ }
+ }
+ }
+ // The observer's context is the workers' context's child: a stop
+ // cancels it with them.
+ if as, ok := n.(*ast.AssignStmt); ok && len(as.Lhs) == 2 && isIdent(as.Lhs[0], "capacityCtx") && len(as.Rhs) == 1 {
+ call, ok := as.Rhs[0].(*ast.CallExpr)
+ sel, ok2 := call.Fun.(*ast.SelectorExpr)
+ if !ok || !ok2 || sel.Sel.Name != "WithCancel" || len(call.Args) != 1 {
+ t.Error("capacityCtx is not a WithCancel context")
+ } else if arg, ok := call.Args[0].(*ast.SelectorExpr); !ok || !isIdent(arg.X, "work") || arg.Sel.Name != "ctx" {
+ t.Error("capacityCtx does not derive from work.ctx")
+ }
+ }
if kv, ok := n.(*ast.KeyValueExpr); ok {
if k, ok := kv.Key.(*ast.Ident); ok {
if call, ok := kv.Value.(*ast.CallExpr); ok && len(call.Args) == 1 {
@@ -86,13 +113,10 @@ func TestHACapacityServeWiring(t *testing.T) {
}
}
}
- if u, ok := n.(*ast.UnaryExpr); ok && u.Op == token.ARROW && isIdent(u.X, "capacityDone") {
- waits++
- }
return true
})
- if starts != 1 || stops != 2 || waits != 1 {
- t.Fatalf("start=%d cancel=%d shutdown wait=%d", starts, stops, waits)
+ if starts != 1 || stops != 1 || handed != 2 {
+ t.Fatalf("start=%d deferred cancel=%d handed to the stop=%d", starts, stops, handed)
}
if fields["HACapacityConfig"] != `"CONSOLE_HA_CAPACITY_CONFIG"` || fields["HACapacityDirectory"] != `"CARLOS_DEPLOYMENT_DIR"` {
t.Fatalf("configuration wiring: %v", fields)
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 2790394ab..41631e3ec 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -692,22 +692,33 @@ func serve() {
defer cancel()
srv.LoadHostsMode(ctx)
}()
- capacityCtx, stopCapacity := context.WithCancel(context.Background())
+ // 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)
- // A graceful stop releases the app policy writer lease, so a rolled
- // console's successor need not wait out its TTL (the housekeeper's
- // "graceful stand-down must be reachable"). Cancel and join the capacity
- // observer before releasing the lease and exiting.
- go func() {
- sig := make(chan os.Signal, 1)
- signal.Notify(sig, syscall.SIGTERM, os.Interrupt)
- <-sig
- stopCapacity()
- <-capacityDone
- srv.ReleasePolicyWriter(context.Background())
- os.Exit(0)
- }()
+ // The graceful stop (stop.go): drain the requests, cancel and join the
+ // workers and the capacity observer, then release the app policy writer
+ // lease, so a rolled console's successor need not wait out its TTL (the
+ // housekeeper's "graceful stand-down must be reachable"). The capacity
+ // observer is joined before the lease is released. Armed here, before
+ // the first worker starts; until serving begins a signal stops with no
+ // requests to drain.
+ sigs := make(chan os.Signal, 2)
+ signal.Notify(sigs, syscall.SIGTERM, os.Interrupt)
+ stop := &consoleStop{
+ work: work,
+ stopCapacity: stopCapacity,
+ capacityDone: capacityDone,
+ release: srv.ReleasePolicyWriter,
+ drain: stopDrainBound,
+ cutGrace: stopCutGrace,
+ workerWait: stopWorkerBound,
+ logf: log.Printf,
+ now: time.Now,
+ }
+ handOff := stop.untilServing(sigs, os.Exit)
// 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
@@ -715,18 +726,18 @@ func serve() {
// no overall timeout, and an ensure that never returns would hold the
// mailer for good (a send gives up at its own deadline, but every one
// would).
- go func() {
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ work.Go("ensureConsoleMail", func(ctx context.Context) {
+ ctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
ensureConsoleMail(ctx)
- }()
+ })
// The senders migration's tail (tenant-email senders design §5): once a
// release has passed with every console writing senders/app.json, an
// operator sets CARLOS_MAIL_LEGACY_SWEEP=1 and the next start deletes the
// email.json objects that have already been replaced. Off by default, and
// it never touches an app that has not been migrated.
if os.Getenv("CARLOS_MAIL_LEGACY_SWEEP") == "1" {
- go sweepLegacyMail(cfg.HostClaim, rel, st)
+ work.Go("sweepLegacyMail", func(ctx context.Context) { sweepLegacyMail(ctx, cfg.HostClaim, rel, st) })
}
// The mail user boundary backfill (CARLOS_MAIL_USER_BOUNDARY): an
// operator sets CARLOS_MAIL_BOUNDARY_SWEEP=1 and the next start puts the
@@ -737,7 +748,9 @@ func serve() {
// the legacy sweep is: it would act on IAM users outside the claim mail
// gate and the apps' permits.
if os.Getenv("CARLOS_MAIL_BOUNDARY_SWEEP") == "1" {
- go sweepMailBoundaries(context.Background(), cfg.HostClaim, mailProvisioner, log.Printf)
+ work.Go("sweepMailBoundaries", func(ctx context.Context) {
+ sweepMailBoundaries(ctx, cfg.HostClaim, mailProvisioner, log.Printf)
+ })
}
// The S3 change index's reader (CARLOS_CHANGE_INDEX=read, change-index
// design §4.6): the run and seed sweeps read their records through a
@@ -761,18 +774,19 @@ func serve() {
log.Fatalf("console: demo job recovery: %v", recoveryErr)
}
if demoView != nil || cfg.Demo.Enabled || cfg.Demo.BoxMode() {
- go recordViewBackstopLoop(context.Background(), demoView, srv)
+ work.Go("recordViewBackstopLoop", func(ctx context.Context) { recordViewBackstopLoop(ctx, demoView, srv) })
}
- go srv.RunDemoJobs(context.Background(), edgesWatch)
+ work.Go("RunDemoJobs", func(ctx context.Context) { srv.RunDemoJobs(ctx, edgesWatch) })
// The region labels' name map (region labels spec §3.2): one edges read
// at start, then at most every 10 minutes on a generation change, else
// every 30 (±10%).
- go srv.RunRegionNames(context.Background(), edgesWatch)
+ work.Go("RunRegionNames", func(ctx context.Context) { srv.RunRegionNames(ctx, edgesWatch) })
// 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.
- srv.StartVerifyReader(context.Background(), edgesWatch)
+ // 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)
// 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)
@@ -790,117 +804,121 @@ func serve() {
// the placement column from routes, for apps placed before the column
// existed. Not before the first seal: sealKeyFor reads the same routes
// until it lands.
- go func() {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ work.Go("fleetBackfills", func(ctx context.Context) {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
srv.RunFleetOwnerBackfill(ctx)
srv.RunAppPlacementBackfill(ctx)
- }()
+ })
+ // Each claim worker runs on work's context under its own name.
+ startClaimWorker := func(name string) {
+ work.Go(name, func(ctx context.Context) { srv.RunClaimWorker(ctx, name) })
+ }
// The alert engine reads the alert signals every minute, steps the
// incidents and sends what they owe (internal/console/alertwatch.go).
// It refuses on a host-claim console and says so in its job status.
// Started here rather than in NewServer so constructing a Server —
// which every console test does — never starts a goroutine or sends
// anything.
- go srv.RunClaimWorker(context.Background(), "StartHostReports")
- go srv.RunClaimWorker(context.Background(), "StartAlertEngine")
+ startClaimWorker("StartHostReports")
+ startClaimWorker("StartAlertEngine")
// The geoip orphan sweep and D1 expiry, at startup and daily.
- go srv.RunClaimWorker(context.Background(), "StartGeoipJobs")
+ startClaimWorker("StartGeoipJobs")
// The moves console record (moves Task 13): with the switch on or a
// secrets key, best-effort, logged by the method itself.
- go srv.RunClaimWorker(context.Background(), "PublishMovesConsole")
+ startClaimWorker("PublishMovesConsole")
// The economics pass writes the daily usage/census/storage/statement
// objects and pulls the AWS bill (internal/console/economicspass.go).
// Same placement rule as the alert engine: started here, never in
// NewServer, so constructing a Server stays goroutine-free.
- go srv.RunClaimWorker(context.Background(), "StartClaimRecoveryPass")
- go srv.RunClaimWorker(context.Background(), "StartEconomicsPass")
+ startClaimWorker("StartClaimRecoveryPass")
+ startClaimWorker("StartEconomicsPass")
// The infrastructure inventory pass writes infra/inventory.json for
// /fleet/architecture (internal/console/infrapass.go). Same placement
// rule as the economics pass: started here, never in NewServer.
- go srv.RunClaimWorker(context.Background(), "StartInfraPass")
+ startClaimWorker("StartInfraPass")
// The object-storage scan pass advances each opted-in store's coverage
// (internal/console/scanpass.go). Same placement rule again: started
// here, never in NewServer. It returns immediately when no engine is
// configured, which is every deployment that has not opted in.
- go srv.RunClaimWorker(context.Background(), "StartScanPass")
+ startClaimWorker("StartScanPass")
// The on-demand drain, on its own clock (spec §7.2). Separate goroutine
// from the sweep above and not a phase inside it: a queue phase behind a
// sequential per-app budget would starve for as long as the sweep takes.
- go srv.RunClaimWorker(context.Background(), "StartScanDrain")
+ startClaimWorker("StartScanDrain")
// The temporary-app expiry pass (internal/console/expirypass.go). Same
// placement rule as every pass above: started here, never in NewServer.
- go srv.RunClaimWorker(context.Background(), "StartExpiryPass")
+ startClaimWorker("StartExpiryPass")
// The plan limits pass (internal/console/planlimits.go): publishes each
// account's limits record. A no-op with CARLOS_PLAN_CATALOG unset.
- go srv.RunClaimWorker(context.Background(), "StartPlanLimitsPass")
- go srv.RunClaimWorker(context.Background(), "StartPlanGracePass")
+ startClaimWorker("StartPlanLimitsPass")
+ startClaimWorker("StartPlanGracePass")
// The billing sync (internal/console/billingpass.go, plans 6a): returns
// at once with CARLOS_BILLING off.
- go srv.RunClaimWorker(context.Background(), "StartBillingSyncPass")
- go srv.RunClaimWorker(context.Background(), "StartDomainPurchasePass")
+ startClaimWorker("StartBillingSyncPass")
+ startClaimWorker("StartDomainPurchasePass")
// The plans deployment marker (internal/console/plansmarker.go): once per
// start. Writes nothing on a deployment that never set a catalog.
- go srv.RunClaimWorker(context.Background(), "PublishPlansMarker")
+ startClaimWorker("PublishPlansMarker")
// The run sweep (internal/console/runsweep.go): expires queued runs,
// ends lost ones, deletes a day-old run's objects. Same placement rule.
- go srv.RunClaimWorker(context.Background(), "StartRunSweep")
+ startClaimWorker("StartRunSweep")
// The seeds sweep (internal/console/seedsweep.go, seeded-instances spec
// §3.1, §5.6): abandons stale reservations and imports, finishes
// rolled-back seeds, deletes snapshots no live seed needs. Same
// placement rule as every pass above.
- go srv.RunClaimWorker(context.Background(), "StartSeedsPass")
+ startClaimWorker("StartSeedsPass")
// The lifetimes cutover watch (internal/console/lifetimes_cutover.go):
// reads control/lifetimes-cutover.json every 10 seconds, turns instance
// lifetimes on once the work admitted before it has drained, and runs the
// claims-off app materialisation as its first admitted iteration. Off on
// a host-claim console.
- go srv.RunClaimWorker(context.Background(), "StartLifetimesCutoverWatch")
+ startClaimWorker("StartLifetimesCutoverWatch")
// The lifetime recovery pass (internal/console/lifetimes_recovery.go):
// every 60 seconds, finishes or ends each create and orphan retirement
// a crash or a failed write left pending. It does work only once
// lifetimes are on, and is off on a host-claim console.
- go srv.RunClaimWorker(context.Background(), "StartLifetimeRecoveryPass")
+ startClaimWorker("StartLifetimeRecoveryPass")
// The incarnation migration pass (internal/console/lifetimes_migrate.go):
// every 60 seconds, moves up to 50 fieldless instance records into
// slot-governed lifetimes, oldest first. Off unless
// CARLOS_LIFETIMES_MIGRATE=1, it does work only once lifetimes are on,
// and is off on a host-claim console.
- go srv.RunClaimWorker(context.Background(), "StartIncarnationMigrationPass")
+ startClaimWorker("StartIncarnationMigrationPass")
// The relay's writer lease and its converging reconcile
// (internal/console/relayops.go). Same placement rule as every pass
// above, and it returns immediately when CARLOS_RELAY_REGIONS is empty —
// which is every deployment that has not armed a relay.
- go srv.RunClaimWorker(context.Background(), "StartRelay")
+ startClaimWorker("StartRelay")
// The email-events push (internal/console/mailpush.go): delivers the
// SES outcomes an app asked to be told about. Same placement rule as
// every pass above; with nothing queued, a pass is two indexed queries.
- go srv.RunClaimWorker(context.Background(), "StartMailEventPush")
+ startClaimWorker("StartMailEventPush")
// Door keys (#175 P7): re-sign every app's record before its 72-hour
// expiry, once at startup and then every 12 hours. Inert without a
// signing key or a deployment bucket.
- go srv.RunClaimWorker(context.Background(), "StartDoorKeyResign")
+ startClaimWorker("StartDoorKeyResign")
// The fleet-address report (internal/console/egressfleet.go, #328):
// re-checks every live egress allow against the boxes' published
// addresses on an edges change and the 30-minute backstop, and alerts.
// Read-only, on every console; idle with no allow.
- go srv.RunClaimWorker(context.Background(), "StartEgressReport")
+ startClaimWorker("StartEgressReport")
// Once, at boot: log any route already sitting at another app's platform
// apex (internal/console/apex.go). Reports; repairs nothing.
- go srv.RunClaimWorker(context.Background(), "ReportApexSquats")
+ startClaimWorker("ReportApexSquats")
// Spec §5.7: after any roll, list possible placement discrepancies for
// operator review. Read-only; never blocks startup.
- go srv.RunClaimWorker(context.Background(), "LogPlacementDiscrepancies")
+ startClaimWorker("LogPlacementDiscrepancies")
// Managed fleets 1b (rules 2, 4, 5, 8): every 5 minutes, label existing
// fleet records to the box their binding names, move records off lost
// and draining boxes, and pause with an alert while a fleet box is below
// the label floor. Off on a host-claim console.
- go srv.RunClaimWorker(context.Background(), "FleetRelabel")
- go srv.RunClaimWorker(context.Background(), "ManagedFleets")
+ startClaimWorker("FleetRelabel")
+ startClaimWorker("ManagedFleets")
// The link sync (internal/console/links_sync.go): every 10 seconds,
// and once at start, writes the hub registry's channel for each linked
// deployment whose last write failed. Reads only the console database.
- go srv.RunClaimWorker(context.Background(), "LinkSync")
+ startClaimWorker("LinkSync")
addr := envOr("CONSOLE_ADDR", "127.0.0.1:8090")
ln, err := net.Listen("tcp", addr)
if err != nil {
@@ -931,10 +949,12 @@ func serve() {
// line fails its restart — and the adopt pass rolls the symlink back and
// starts the previous version, instead of stamping a build that never
// served (internal/release/adopt.go).
+ stop.attach(httpSrv)
+ handOff()
if err := NotifyReady(); err != nil {
log.Printf("console: notifying systemd of readiness: %v", err)
}
- log.Fatal(httpSrv.Serve(ln))
+ os.Exit(stop.serve(ln, sigs))
}
// openServeDB is openConsoleDB for the serving console. With
@@ -2081,12 +2101,12 @@ func geoLocator(sw *geo.Swappable) geo.Locator {
return sw
}
-func sweepLegacyMail(claims bool, rel release.Store, st *console.Store) {
+func sweepLegacyMail(ctx context.Context, claims bool, rel release.Store, st *console.Store) {
if claims {
log.Printf("console: mail legacy sweep: %v", mail.ErrClaimMailPending)
return
}
- n, err := mail.SweepLegacyRecords(context.Background(), rel, true)
+ n, err := mail.SweepLegacyRecords(ctx, rel, true)
if err != nil {
log.Printf("console: mail legacy sweep: %v", err)
return
diff --git a/cmd/console/plansponsor_test.go b/cmd/console/plansponsor_test.go
index e7f58abf8..5b400a734 100644
--- a/cmd/console/plansponsor_test.go
+++ b/cmd/console/plansponsor_test.go
@@ -163,7 +163,7 @@ func TestServeSettlesTheSponsorshipBeforeItServes(t *testing.T) {
if p, ok := first["planCatalog"]; !ok || p > at {
t.Error("sponsorAtStart runs before planCatalog loads the catalog")
}
- for _, later := range []string{"billingConfigFor", "console.NewServer", "srv.RunClaimWorker", "net.Listen", "httpSrv.Serve", "NotifyReady"} {
+ for _, later := range []string{"billingConfigFor", "console.NewServer", "srv.RunClaimWorker", "net.Listen", "stop.serve", "NotifyReady"} {
p, ok := first[later]
if !ok {
t.Errorf("serve() no longer calls %s; update this test", later)
diff --git a/cmd/console/stop.go b/cmd/console/stop.go
new file mode 100644
index 000000000..c7a31f05e
--- /dev/null
+++ b/cmd/console/stop.go
@@ -0,0 +1,421 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "sort"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+// How long each step of a graceful stop may take. console.service names no
+// TimeoutStopSec (the unit is written on each console box and is in no
+// repo), so systemd's DefaultTimeoutStopSec applies: SIGTERM, then SIGKILL
+// 90 s later. The adopt pass's `systemctl try-restart` waits for that stop
+// before its settle window starts. The worst case here is drain 20 s + cut
+// grace 2 s + workers 10 s + the policy lease release's own 5 s budget
+// (policyLeaseReleaseBudget) = 37 s, well inside the 90.
+//
+// The drain is the one a roll feels: the listener closes as the stop
+// starts, so for as long as a request is still running the edge in front
+// gets refused connections. An ordinary page or API call finishes in well
+// under a second; 20 s also covers a policy write's signing attempt
+// (policyAttemptWindow, 10 s). A longer upload or stream is cut.
+const (
+ stopDrainBound = 20 * time.Second
+ stopCutGrace = 2 * time.Second
+ stopWorkerBound = 10 * time.Second
+)
+
+// consoleStop is the console's graceful stop (SIGTERM or SIGINT), in order:
+//
+// 1. Stop accepting and drain: http.Server.Shutdown closes the listener at
+// once (a new connection is refused) and waits for the requests in
+// flight, for up to drain. Upgraded connections (the WebSocket doors:
+// interactive sessions, run and demo box legs), which Shutdown does not
+// track, are closed as it starts, so their handlers wind down inside the
+// 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,
+// 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
+// its TTL, and only once the capacity observer has been joined (the
+// 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.
+type consoleStop struct {
+ srv *http.Server // nil until serving: a stop before it has no requests to drain
+ reqs *requests
+ cancelRequests context.CancelFunc
+
+ work *workers
+ stopCapacity func()
+ capacityDone <-chan struct{}
+ release func(context.Context)
+
+ drain, cutGrace, workerWait time.Duration
+ logf func(string, ...any)
+ now func() time.Time
+}
+
+// attach makes h the server a stop drains: request contexts derive from one
+// the cut cancels, each handler is counted while it runs, and upgraded
+// connections are tracked so the stop can close them.
+func (p *consoleStop) attach(h *http.Server) {
+ reqCtx, cancel := context.WithCancel(context.Background())
+ p.reqs = newRequests(p.now)
+ p.cancelRequests = cancel
+ h.BaseContext = func(net.Listener) context.Context { return reqCtx }
+ connCtx := h.ConnContext
+ h.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
+ if connCtx != nil {
+ ctx = connCtx(ctx, c)
+ }
+ return context.WithValue(ctx, connKey{}, c)
+ }
+ connState := h.ConnState
+ h.ConnState = func(c net.Conn, st http.ConnState) {
+ if connState != nil {
+ connState(c, st)
+ }
+ if st == http.StateHijacked {
+ p.reqs.hijacked(c)
+ }
+ }
+ h.Handler = p.reqs.wrap(h.Handler)
+ h.RegisterOnShutdown(func() {
+ if n := p.reqs.closeHijacked(); n > 0 {
+ p.logf("console: stop: closed %d upgraded connection(s) (WebSocket sessions and box legs)", n)
+ }
+ })
+ p.srv = h
+}
+
+// untilServing handles a signal that arrives while serve is still starting
+// (workers running, nothing listening yet): the same stop with no requests
+// to drain, then exit. The returned handOff is called just before serving;
+// it returns once the early handler has stood down, or never if a signal
+// already started a stop (exit ends the process).
+func (p *consoleStop) untilServing(sigs <-chan os.Signal, exit func(int)) (handOff func()) {
+ early := *p // no server yet; main may set p.srv while this goroutine waits
+ taken := make(chan struct{})
+ go func() {
+ select {
+ case sig := <-sigs:
+ early.logf("console: %v before serving: stopping", sig)
+ code := 0
+ if early.stop(sigs) {
+ code = 1
+ }
+ exit(code)
+ case taken <- struct{}{}:
+ }
+ }()
+ return func() { <-taken }
+}
+
+// serve serves ln until a signal (or a failed Serve), then stops, and
+// returns the exit status: 0 after a requested stop, even one whose bound
+// cut something (the log names it); 1 after a second signal or when Serve
+// itself failed.
+func (p *consoleStop) serve(ln net.Listener, sigs <-chan os.Signal) int {
+ served := make(chan error, 1)
+ go func() { served <- p.srv.Serve(ln) }()
+ code := 0
+ select {
+ case sig := <-sigs:
+ p.logf("console: %v: stopping", sig)
+ case err := <-served:
+ p.logf("console: serving failed: %v; stopping", err)
+ code = 1
+ }
+ if p.stop(sigs) {
+ code = 1
+ }
+ 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() {
+ select {
+ case sig := <-sigs:
+ p.logf("console: %v again: stopping now", sig)
+ hurried.Store(true)
+ cancelForce()
+ case <-force.Done():
+ }
+ }()
+ why := func() string {
+ if hurried.Load() {
+ return "at the second signal"
+ }
+ return ""
+ }
+ if p.srv != nil {
+ p.drainRequests(force, why)
+ }
+ capacityJoined := p.stopWorkers(force, why)
+ switch {
+ case hurried.Load():
+ 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() {
+ return true
+ }
+ p.logf("console: stopped")
+ return false
+}
+
+func (p *consoleStop) drainRequests(force context.Context, why func() string) {
+ p.logf("console: stop: not accepting connections; draining requests for up to %s", p.drain)
+ ctx, cancel := context.WithTimeout(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 {
+ 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.cancelRequests()
+ p.srv.Close()
+ p.reqs.closeHijacked()
+ if force.Err() != nil {
+ return
+ }
+ gctx, gcancel := context.WithTimeout(force, p.cutGrace)
+ defer gcancel()
+ if p.reqs.run.wait(gctx) != nil {
+ 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 {
+ p.work.cancel()
+ p.stopCapacity()
+ ctx, cancel := context.WithTimeout(force, p.workerWait)
+ defer cancel()
+ if p.work.run.wait(ctx) != nil {
+ reason := why()
+ if reason == "" {
+ reason = fmt.Sprintf("within %s", p.workerWait)
+ }
+ 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
+ }
+}
+
+// workers runs the console's background loops on one context, so a stop
+// cancels them together and can wait for them with a bound.
+type workers struct {
+ ctx context.Context
+ cancel context.CancelFunc
+ run *running
+}
+
+func newWorkers(parent context.Context, now func() time.Time) *workers {
+ ctx, cancel := context.WithCancel(parent)
+ return &workers{ctx: ctx, cancel: cancel, run: newRunning(now)}
+}
+
+// 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)) {
+ e := w.run.start(name)
+ go func() {
+ defer w.run.end(e)
+ f(w.ctx)
+ }()
+}
+
+// requests counts the handlers running and the connections they upgraded.
+type requests struct {
+ run *running
+
+ mu sync.Mutex
+ conns map[net.Conn]struct{}
+ closing bool
+}
+
+type connKey struct{}
+
+func newRequests(now func() time.Time) *requests {
+ return &requests{run: newRunning(now), conns: map[net.Conn]struct{}{}}
+}
+
+// wrap counts h's handlers. The writer and request pass through unchanged.
+// Only the path is logged at a cut, never the query string.
+func (q *requests) wrap(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ e := q.run.start(r.Method + " " + r.URL.Path)
+ defer q.run.end(e)
+ if c, ok := r.Context().Value(connKey{}).(net.Conn); ok {
+ defer q.forget(c)
+ }
+ h.ServeHTTP(w, r)
+ })
+}
+
+// hijacked records a connection a handler took over; once the stop has
+// started it is closed at once instead.
+func (q *requests) hijacked(c net.Conn) {
+ q.mu.Lock()
+ if q.closing {
+ q.mu.Unlock()
+ c.Close()
+ return
+ }
+ q.conns[c] = struct{}{}
+ q.mu.Unlock()
+}
+
+// forget drops c when the handler that may have upgraded it returns.
+func (q *requests) forget(c net.Conn) {
+ q.mu.Lock()
+ delete(q.conns, c)
+ q.mu.Unlock()
+}
+
+// closeHijacked closes every upgraded connection and every one upgraded
+// from now on, and returns how many it closed now.
+func (q *requests) closeHijacked() int {
+ q.mu.Lock()
+ q.closing = true
+ conns := make([]net.Conn, 0, len(q.conns))
+ for c := range q.conns {
+ conns = append(conns, c)
+ }
+ clear(q.conns)
+ q.mu.Unlock()
+ for _, c := range conns {
+ c.Close()
+ }
+ return len(conns)
+}
+
+// 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.
+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
+}
+
+type runEntry struct {
+ label string
+ since time.Time
+}
+
+func newRunning(now func() time.Time) *running {
+ return &running{now: now, set: map[*runEntry]struct{}{}}
+}
+
+func (r *running) start(label string) *runEntry {
+ e := &runEntry{label: label, since: r.now()}
+ r.mu.Lock()
+ if r.emptied {
+ // A wait already saw the set empty and returned; the next one
+ // waits afresh.
+ r.empty, r.emptied = nil, false
+ }
+ r.set[e] = struct{}{}
+ r.mu.Unlock()
+ return e
+}
+
+func (r *running) end(e *runEntry) {
+ r.mu.Lock()
+ delete(r.set, e)
+ r.signalLocked()
+ r.mu.Unlock()
+}
+
+func (r *running) signalLocked() {
+ if r.empty != nil && !r.emptied && len(r.set) == 0 {
+ r.emptied = true
+ close(r.empty)
+ }
+}
+
+// wait returns nil once nothing is running, or ctx's error.
+func (r *running) wait(ctx context.Context) error {
+ r.mu.Lock()
+ 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()
+}
+
+// labels names what is still running, oldest first, with how long each has
+// run.
+func (r *running) labels() []string {
+ r.mu.Lock()
+ entries := make([]*runEntry, 0, len(r.set))
+ for e := range r.set {
+ entries = append(entries, e)
+ }
+ r.mu.Unlock()
+ sort.Slice(entries, func(i, j int) bool { return entries[i].since.Before(entries[j].since) })
+ now := r.now()
+ out := make([]string, len(entries))
+ for i, e := range entries {
+ out[i] = fmt.Sprintf("%s (%s)", e.label, now.Sub(e.since).Round(time.Second))
+ }
+ return out
+}
diff --git a/cmd/console/stop_test.go b/cmd/console/stop_test.go
new file mode 100644
index 000000000..6db1dcde0
--- /dev/null
+++ b/cmd/console/stop_test.go
@@ -0,0 +1,390 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "slices"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+)
+
+// stopRig is a consoleStop wired to fakes that record what happened in
+// which order: one worker that returns when its context ends, a capacity
+// observer that is joined when cancelled, and a lease release.
+type stopRig struct {
+ t *testing.T
+ stop *consoleStop
+ sigs chan os.Signal
+ mu sync.Mutex
+ events []string
+ logs []string
+}
+
+func newStopRig(t *testing.T, drain, cutGrace, workerWait time.Duration) *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")
+ close(capacityDone)
+ }()
+ work.Go("loop", func(ctx context.Context) {
+ <-ctx.Done()
+ r.event("worker joined")
+ })
+ r.stop = &consoleStop{
+ work: work,
+ stopCapacity: stopCapacity,
+ capacityDone: capacityDone,
+ release: func(context.Context) { r.event("lease released") },
+ drain: drain,
+ cutGrace: cutGrace,
+ workerWait: workerWait,
+ logf: func(format string, a ...any) {
+ r.mu.Lock()
+ r.logs = append(r.logs, fmt.Sprintf(format, a...))
+ r.mu.Unlock()
+ },
+ now: time.Now,
+ }
+ return r
+}
+
+func (r *stopRig) event(e string) {
+ r.mu.Lock()
+ r.events = append(r.events, e)
+ r.mu.Unlock()
+}
+
+func (r *stopRig) eventList() []string {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return slices.Clone(r.events)
+}
+
+func (r *stopRig) log() string {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return strings.Join(r.logs, "\n")
+}
+
+// serve attaches h through the production constructor and serves it on a
+// loopback listener. It returns the address, a channel closed once Shutdown
+// has closed the listener, and the serve result.
+func (r *stopRig) serve(h http.Handler) (addr string, shutdownStarted <-chan struct{}, result <-chan int) {
+ r.t.Helper()
+ srv := console.NewHTTPServer(h)
+ r.stop.attach(srv)
+ started := make(chan struct{})
+ // Shutdown runs its hooks after it has closed the listeners.
+ srv.RegisterOnShutdown(func() { close(started) })
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ res := make(chan int, 1)
+ go func() { res <- r.stop.serve(ln, r.sigs) }()
+ return ln.Addr().String(), started, res
+}
+
+// guard fails the test rather than hang it when ch never delivers.
+func guard[T any](t *testing.T, ch <-chan T, what string) T {
+ t.Helper()
+ select {
+ case v := <-ch:
+ return v
+ case <-time.After(30 * time.Second):
+ t.Fatalf("%s: nothing after 30s", what)
+ panic("unreachable")
+ }
+}
+
+func indexOf(t *testing.T, events []string, e string) int {
+ t.Helper()
+ i := slices.Index(events, e)
+ if i < 0 {
+ t.Fatalf("no %q in %v", e, events)
+ }
+ return i
+}
+
+// A request in flight at SIGTERM completes; a new connection after the
+// signal is refused; the workers and the capacity observer are joined after
+// the drain, and the lease is released last.
+func TestConsoleStopDrainsInFlightRequest(t *testing.T) {
+ r := newStopRig(t, time.Minute, time.Minute, time.Minute)
+ entered, proceed := make(chan struct{}), make(chan struct{})
+ addr, shutdownStarted, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ close(entered)
+ <-proceed
+ io.WriteString(w, "done")
+ r.event("handler returned")
+ }))
+ type reply struct {
+ status int
+ body string
+ err error
+ }
+ got := make(chan reply, 1)
+ go func() {
+ resp, err := http.Get("http://" + addr + "/slow")
+ if err != nil {
+ got <- reply{err: err}
+ return
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(resp.Body)
+ got <- reply{resp.StatusCode, string(b), err}
+ }()
+ guard(t, entered, "request entering the handler")
+ r.sigs <- syscall.SIGTERM
+ guard(t, shutdownStarted, "Shutdown starting")
+
+ if c, err := net.Dial("tcp", addr); err == nil {
+ c.Close()
+ t.Fatal("a new connection was accepted after the signal")
+ }
+ select {
+ case code := <-result:
+ t.Fatalf("serve returned %d with a request still in flight", code)
+ default:
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Fatal("the lease was released while a request was in flight")
+ }
+
+ close(proceed)
+ rep := guard(t, got, "the in-flight reply")
+ if rep.err != nil || rep.status != http.StatusOK || rep.body != "done" {
+ t.Fatalf("in-flight request: status %d body %q err %v; want 200 \"done\"", rep.status, rep.body, rep.err)
+ }
+ if code := guard(t, result, "serve returning"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ ev := r.eventList()
+ handler, worker, capacity, release := indexOf(t, ev, "handler returned"), indexOf(t, ev, "worker joined"), indexOf(t, ev, "capacity joined"), indexOf(t, ev, "lease released")
+ if handler > worker || handler > capacity {
+ t.Errorf("workers stopped before the drain finished: %v", ev)
+ }
+ if release < worker || release < capacity {
+ t.Errorf("lease released before the workers and capacity observer were joined: %v", ev)
+ }
+ if strings.Contains(r.log(), "cut") {
+ t.Errorf("a clean drain logged a cut:\n%s", r.log())
+ }
+}
+
+// A handler that ignores its context and never returns is cut at the
+// drain bound: the stop names it, the client's connection is closed, the
+// lease is still released, and serve returns.
+func TestConsoleStopCutsStuckHandlerAtBound(t *testing.T) {
+ r := newStopRig(t, 50*time.Millisecond, 50*time.Millisecond, time.Minute)
+ entered, unstick := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ addr, _, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ close(entered)
+ <-unstick
+ }))
+ clientErr := make(chan error, 1)
+ go func() {
+ resp, err := http.Get("http://" + addr + "/stuck?token=secret")
+ if err == nil {
+ resp.Body.Close()
+ }
+ clientErr <- err
+ }()
+ guard(t, entered, "request entering the handler")
+ r.sigs <- syscall.SIGTERM
+ if code := guard(t, result, "serve returning"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ if err := guard(t, clientErr, "the client"); err == nil {
+ t.Error("the cut request's client got a response")
+ }
+ log := r.log()
+ if !strings.Contains(log, "cut 1 request(s) still running after 50ms: GET /stuck (") {
+ t.Errorf("the cut is not named:\n%s", log)
+ }
+ if strings.Contains(log, "secret") {
+ t.Errorf("a query string reached the log:\n%s", log)
+ }
+ if !strings.Contains(log, "1 handler(s) still running 50ms after the cut") {
+ t.Errorf("the handler left running is not named:\n%s", log)
+ }
+ ev := r.eventList()
+ if indexOf(t, ev, "lease released") < indexOf(t, ev, "capacity joined") {
+ t.Errorf("lease released before the capacity observer was joined: %v", ev)
+ }
+}
+
+// Upgraded connections (the WebSocket doors), which Shutdown does not wait
+// for, are closed as the stop starts, so a session cannot hold the drain to
+// its bound.
+func TestConsoleStopClosesUpgradedConnections(t *testing.T) {
+ r := newStopRig(t, time.Hour, time.Hour, time.Minute)
+ upgraded := make(chan struct{})
+ addr, _, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ c, buf, err := http.NewResponseController(w).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer c.Close()
+ buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n")
+ buf.Flush()
+ close(upgraded)
+ _, _ = io.Copy(io.Discard, c) // until the connection is closed
+ r.event("session returned")
+ }))
+ c, err := net.Dial("tcp", addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer c.Close()
+ fmt.Fprintf(c, "GET /session HTTP/1.1\r\nHost: console\r\nUpgrade: test\r\nConnection: Upgrade\r\n\r\n")
+ if line, err := bufio.NewReader(c).ReadString('\n'); err != nil || !strings.Contains(line, "101") {
+ t.Fatalf("upgrade: %q %v", line, err)
+ }
+ guard(t, upgraded, "the upgrade")
+ r.sigs <- syscall.SIGTERM
+ if code := guard(t, result, "serve returning"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ ev := r.eventList()
+ if indexOf(t, ev, "session returned") > indexOf(t, ev, "lease released") {
+ t.Errorf("the session handler returned after the lease release: %v", ev)
+ }
+ if !strings.Contains(r.log(), "closed 1 upgraded connection(s)") {
+ t.Errorf("the closed session is not logged:\n%s", r.log())
+ }
+ if strings.Contains(r.log(), "cut") {
+ t.Errorf("the session was cut at the bound, not closed at the start:\n%s", r.log())
+ }
+}
+
+// A second signal stops waiting: the stuck request is named and cut, the
+// lease is left to expire, and the exit status is 1.
+func TestConsoleStopSecondSignal(t *testing.T) {
+ r := newStopRig(t, time.Hour, time.Hour, time.Hour)
+ entered, unstick := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ addr, shutdownStarted, result := r.serve(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ close(entered)
+ <-unstick
+ }))
+ go func() {
+ if resp, err := http.Get("http://" + addr + "/stuck"); err == nil {
+ resp.Body.Close()
+ }
+ }()
+ guard(t, entered, "request entering the handler")
+ r.sigs <- syscall.SIGTERM
+ guard(t, shutdownStarted, "Shutdown starting")
+ r.sigs <- os.Interrupt
+ if code := guard(t, result, "serve returning"); code != 1 {
+ t.Fatalf("exit status %d, want 1", code)
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was released after a second signal")
+ }
+ log := r.log()
+ for _, want := range []string{"interrupt again: stopping now", "cut 1 request(s) still running at the second signal: GET /stuck (", "not released (second signal)"} {
+ if !strings.Contains(log, want) {
+ t.Errorf("log lacks %q:\n%s", want, log)
+ }
+ }
+}
+
+// A worker that ignores its context is named at the worker bound and the
+// lease is still released, since the capacity observer was joined. An
+// 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)
+ unstick := make(chan struct{})
+ t.Cleanup(func() { close(unstick) })
+ r.stop.work.Go("StartStuckPass", func(context.Context) { <-unstick })
+ if r.stop.stop(r.sigs) {
+ t.Fatal("reported a second signal")
+ }
+ if !strings.Contains(r.log(), "1 background worker(s) did not stop within 50ms, cut: StartStuckPass (") {
+ t.Errorf("the stuck worker is not named:\n%s", r.log())
+ }
+ if !slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was not released")
+ }
+ })
+ t.Run("capacity observer not joined", func(t *testing.T) {
+ r := newStopRig(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")
+ }
+ if slices.Contains(r.eventList(), "lease released") {
+ t.Error("the lease was released before the capacity observer was joined")
+ }
+ if !strings.Contains(r.log(), "HA capacity observer did not stop") {
+ t.Errorf("the skipped release is not logged:\n%s", r.log())
+ }
+ })
+}
+
+// A signal before serving begins stops the workers, releases the lease and
+// exits 0; with no signal, handOff stands the early handler down so the
+// next signal reaches serve.
+func TestConsoleStopBeforeServing(t *testing.T) {
+ t.Run("signal", func(t *testing.T) {
+ r := newStopRig(t, time.Minute, time.Minute, time.Minute)
+ exited := make(chan int, 1)
+ r.stop.untilServing(r.sigs, func(code int) { exited <- code })
+ r.sigs <- syscall.SIGTERM
+ if code := guard(t, exited, "the early stop exiting"); code != 0 {
+ t.Fatalf("exit status %d, want 0", code)
+ }
+ ev := r.eventList()
+ if indexOf(t, ev, "lease released") < indexOf(t, ev, "capacity joined") || indexOf(t, ev, "lease released") < indexOf(t, ev, "worker joined") {
+ t.Errorf("lease released before the joins: %v", ev)
+ }
+ })
+ t.Run("hand off", func(t *testing.T) {
+ r := newStopRig(t, time.Minute, time.Minute, time.Minute)
+ handOff := r.stop.untilServing(r.sigs, func(code int) { t.Errorf("early stop exited %d", code) })
+ handOff()
+ r.sigs <- syscall.SIGTERM
+ if len(r.sigs) != 1 {
+ t.Fatal("the early handler took a signal after the hand-off")
+ }
+ })
+}
+
+// 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) {
+ r := newRunning(time.Now)
+ ctx, cancel := context.WithCancel(context.Background())
+ if err := r.wait(ctx); err != nil {
+ t.Fatalf("empty: %v", err)
+ }
+ e := r.start("late")
+ cancel()
+ if err := r.wait(ctx); err == nil {
+ t.Fatal("wait returned nil with one running")
+ }
+ r.end(e)
+ if err := r.wait(context.Background()); err != nil {
+ t.Fatalf("after end: %v", err)
+ }
+}