diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index a8d69b693..798cdc4f4 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -354,6 +354,11 @@ func Run() int { defer stop() b := newBootstrap() + // Arm the shutdown watchdog before any cleanup is registered so its + // disarm runs last in the LIFO cleanup chain: it force-exits the process + // as a backstop if graceful shutdown hangs past the drain-plus-grace + // leash, and stands down once every subsystem has shut down cleanly. + b.startShutdownWatchdog(ctx) if err := b.loadConfig(ctx, args.cfgPath, args.overlayPath, args.noConfigOverlay); err != nil { return 1 } diff --git a/internal/app/archied/shutdown_watchdog.go b/internal/app/archied/shutdown_watchdog.go new file mode 100644 index 000000000..075b10ca0 --- /dev/null +++ b/internal/app/archied/shutdown_watchdog.go @@ -0,0 +1,95 @@ +package archied + +import ( + "context" + "log/slog" + "os" + "sync" + "time" +) + +// shutdownGracePeriod is the fixed grace added to the drain window before the +// shutdown watchdog force-exits the process. +const shutdownGracePeriod = 60 * time.Second + +// defaultShutdownDrainTimeout is the graceful-shutdown drain window used to +// compute the watchdog leash when no drain timeout is configured. It bounds +// how long the daemon waits for in-flight work to finish before the +// watchdog's backstop applies. The drain-control marker/timeout is a sibling +// effort; when it lands it supplies this value and the leash is recomputed +// from it. +const defaultShutdownDrainTimeout = 60 * time.Second + +// shutdownLeash is the total leash the shutdown watchdog allows: the drain +// window plus the grace period. Shutdown normally completes well within it; +// the leash only bites when the graceful-shutdown machinery hangs. +func shutdownLeash() time.Duration { + return defaultShutdownDrainTimeout + shutdownGracePeriod +} + +// shutdownWatchdog force-exits the daemon if graceful shutdown does not +// complete within the leash. It runs in its own goroutine outside the +// daemon's event loop, so it fires even when the graceful-shutdown machinery +// it backstops is itself the thing that is hung. It depends only on the +// process being alive, never on a subsystem's clean shutdown. +type shutdownWatchdog struct { + leash time.Duration + log *slog.Logger + exit func(int) +} + +// newShutdownWatchdog builds a watchdog that, once shutdown begins, stops the +// process if it does not complete within leash. exit is injectable so tests +// can observe a forced exit without terminating the test process. +func newShutdownWatchdog(leash time.Duration, log *slog.Logger) *shutdownWatchdog { + return &shutdownWatchdog{leash: leash, log: log, exit: os.Exit} +} + +// watch starts the watchdog goroutine. The returned func disarms it: call it +// once graceful shutdown has completed so a shutdown that finishes within the +// leash is never cut short. If that func is never called -- a hung shutdown -- +// the watchdog force-exits the process as soon as the leash expires. +// +// The goroutine blocks on a single select pair and never touches the daemon's +// own event loop or shutdown machinery, which is precisely the point: it must +// still be able to run when those are the parts that are stuck. +func (w *shutdownWatchdog) watch(shutdown <-chan struct{}) func() { + var once sync.Once + done := make(chan struct{}) + disarm := func() { once.Do(func() { close(done) }) } + + go func() { + // Wait for graceful shutdown to begin. If the process is exiting for + // some other reason, done is closed and the watchdog stands down + // before doing anything. + select { + case <-shutdown: + case <-done: + return + } + + timer := time.NewTimer(w.leash) + defer timer.Stop() + + select { + case <-timer.C: + w.log.Error("shutdown watchdog: graceful shutdown did not complete within leash; forcing exit", + "leash", w.leash.String()) + w.exit(1) + case <-done: + // Shutdown completed within the leash; stand down. + } + }() + + return disarm +} + +// startShutdownWatchdog arms the daemon's shutdown watchdog. It must be called +// before any other cleanup is registered so its disarm runs last in the LIFO +// cleanup chain: the watchdog stands down only after every other subsystem has +// shut down cleanly. A subsystem that hangs never runs the disarm, so the +// watchdog force-exits. +func (b *boot) startShutdownWatchdog(ctx context.Context) { + disarm := newShutdownWatchdog(shutdownLeash(), b.log).watch(ctx.Done()) + b.addCleanup(disarm) +} diff --git a/internal/app/archied/shutdown_watchdog_test.go b/internal/app/archied/shutdown_watchdog_test.go new file mode 100644 index 000000000..62df797e6 --- /dev/null +++ b/internal/app/archied/shutdown_watchdog_test.go @@ -0,0 +1,93 @@ +package archied + +import ( + "context" + "log/slog" + "testing" + "time" +) + +// testWatchdogLeash is deliberately short so the watchdog tests are fast and +// deterministic. The real production leash is drain timeout plus grace +// period -- far longer than anything a unit test should wait for. +const testWatchdogLeash = 30 * time.Millisecond + +func discardWatchdogLogger() *slog.Logger { + return slog.New(slog.DiscardHandler) +} + +// TestShutdownWatchdogHangingPastLeashForcesExit proves the backstop: once +// graceful shutdown begins and never completes (the shutdown machinery is +// hung, so the disarm is never called), the watchdog force-exits the process +// after the leash expires. +func TestShutdownWatchdogHangingPastLeashForcesExit(t *testing.T) { + exited := make(chan int, 1) + w := newShutdownWatchdog(testWatchdogLeash, discardWatchdogLogger()) + w.exit = func(code int) { exited <- code } + + began := make(chan struct{}) + _ = w.watch(began) + + // Graceful shutdown begins and never completes: no disarm is called. + close(began) + + select { + case code := <-exited: + if code != 1 { + t.Fatalf("watchdog force-exited with code %d, want 1", code) + } + case <-time.After(testWatchdogLeash * 2): + t.Fatalf("watchdog did not force-exit within leash %s", testWatchdogLeash) + } +} + +// TestShutdownWatchdogCompletingWithinLeashDoesNotExit proves the inverse: +// a shutdown that completes within the leash (the disarm is called before the +// leash expires) does not trigger the watchdog. +func TestShutdownWatchdogCompletingWithinLeashDoesNotExit(t *testing.T) { + exited := make(chan int, 1) + w := newShutdownWatchdog(testWatchdogLeash, discardWatchdogLogger()) + w.exit = func(code int) { exited <- code } + + began := make(chan struct{}) + disarm := w.watch(began) + + // Shutdown begins and completes immediately, well within the leash. + close(began) + disarm() + + select { + case code := <-exited: + t.Fatalf("watchdog force-exited with code %d despite completing within leash", code) + case <-time.After(testWatchdogLeash * 3): + // Correct: a shutdown that completed within the leash did not + // trigger the forced exit. + } +} + +// TestBootStartShutdownWatchdogDisarmRunsLast pins the wiring invariant that +// makes the backstop sound: the disarm the watchdog registers must be the +// FIRST cleanup so it runs LAST in the LIFO shutdown chain. If it were +// registered after a subsystem's cleanup, a hung subsystem would let the +// disarm run early and the watchdog would stand down before the backstop was +// needed. +func TestBootStartShutdownWatchdogDisarmRunsLast(t *testing.T) { + b := newBootstrap() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + b.startShutdownWatchdog(ctx) + + if len(b.cleanups) != 1 { + t.Fatalf("startShutdownWatchdog registered %d cleanups, want exactly the disarm", len(b.cleanups)) + } + + // A later subsystem's shutdown cleanup is appended after the disarm, so in + // the LIFO chain it runs BEFORE the disarm. + var ran []string + b.addCleanup(func() { ran = append(ran, "subsystem") }) + b.cleanup() + + if len(ran) != 1 || ran[0] != "subsystem" { + t.Fatalf("cleanup order = %v, want the disarm to run after the subsystem cleanup", ran) + } +}