shutdown

package
v1.0.521 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package shutdown owns ordered, bounded execution of application-supplied shutdown hooks.

Index

Constants

View Source
const DefaultGrace = 3 * time.Second

DefaultGrace is the extra time a phase may overrun its own deadline while hooks unwind. A hook that observes ctx returns as soon as the phase deadline passes; this grace exists for the hooks that CANNOT observe it — an fsync inside a durable close, a badger compaction, a write(2) into a wedged NFS mount. Past it the hook is abandoned so the hooks AFTER it still run: at shutdown, leaking one goroutine is free (the process is exiting) and a stalled hook that blocks the flush hooks behind it is not.

CHAOS-56. It is charged ONCE PER PHASE, not per hook: RunAll folds it into the phase HORIZON (phaseEnd + grace) and hookBudget measures every hook's slice against that, so a phase in which every hook stalls still finishes within its own deadline plus one grace and the envelope in main_shutdown.go adds it exactly twice: once for the drain phase, once for the flush phase.

Sharing it is load-bearing, and so is sharing it THIS way. It was originally charged per hook on the reasoning that hookBudget hands an overrunning hook's unused SLICE to the hooks behind it — true, but the grace is added ON TOP of each hook's deadline and is never charged against the phase's remaining time, so each stalled hook extended the phase by a further full grace. Measured on the shipped constants with every hook stalled, the sequence took 59.2s against the 51s this envelope claims and a 60s compose stop_grace_period; one more durable closer crossed it. Past that it is SIGKILL, which skips the durable flushes the whole three-phase design exists to guarantee.

The first repair only CLAMPED the abandon instant at phaseEnd+grace. That bounded the total but broke the other half: once the clamp was reached a later hook got an already-expired watchdog, so it could be abandoned before its goroutine even entered h.stop, and because main exits as soon as the sequence returns those bodies never ran — request-log-close, audit-log-close and log-closer, the durable compliance record and the flush holding the evidence, starved by the fix meant to protect them (Codex P1, PR #1311). Folding the grace into the horizon instead keeps BOTH: the phase ends at phaseEnd+grace, and every hook still gets its own non-zero slice.

The default is immutable. A constructor may supply a different per-instance value; partitioning preserves that value without sharing mutable settings.

View Source
const DefaultMinSlice = 1 * time.Second

DefaultMinSlice is the watchdog budget every hook is guaranteed however much of the phase the hooks before it consumed. See hookBudget — this is what stops one stalled durable close from starving the closers behind it, which is the flush reserve's own argument applied within a phase.

The default is immutable; Options.MinSlice is instance-owned.

Variables

View Source
var ErrAbandoned = errors.New("exceeded the shutdown budget and was abandoned")

ErrAbandoned marks a hook the watchdog gave up waiting for. It is aggregated into RunAll's error like any other hook failure, but the operator-visible record is the log line emitted at the point of abandonment — the aggregate is returned to the caller AFTER the phase, and on the flush phase that is after the log sink has been closed.

Functions

This section is empty.

Types

type HookInfo

type HookInfo struct {
	Name  string
	Order int
}

HookInfo describes a registered hook without exposing its callback. Hooks returns detached values in registration order, not execution order.

type Options

type Options struct {
	Grace    time.Duration
	MinSlice time.Duration
	Logf     func(string, ...any)
}

Options are copied at construction; there are no runtime setters. Zero durations select the production defaults. Negative durations are rejected. Logf receives an abandonment diagnostic before later hooks can close the sink. A nil Logf discards diagnostics; RunAll still returns every failure.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry collects ordered, named shutdown hooks and runs them as a single batch via RunAll. The contract:

  • Hooks run in ascending order. Hooks with the same order run in registration order (sort.SliceStable preserves the tie-break).
  • All hooks run even if one returns an error. Failures are aggregated via errors.Join into a single returned error; each wrapped error is prefixed with its hook name.
  • RunAll is idempotent: a second call returns nil without re-running any hook.
  • Register panics if stop is nil — registering a no-op hook is a programming error and should fail fast at wire-up time.

Concurrency: Register and RunAll are mutex-protected. The hook list is snapshotted before the lock is released, so user-provided stop functions run without the registry lock held.

Application code owns concrete callbacks and phase sequencing. This package owns execution only; it starts no goroutines until RunAll.

func New

func New(options Options) *Registry

New constructs an independent registry. Its zero value also works with the default timing and no diagnostic sink. A Registry must not be copied after use.

func (*Registry) Hooks

func (r *Registry) Hooks() []HookInfo

Hooks returns a copy of the registration inventory for wiring diagnostics.

func (*Registry) PartitionAt

func (r *Registry) PartitionAt(boundary int) (atOrBelow, above *Registry)

PartitionAt splits the registry into two registries by hook order: `at or below` receives every hook whose order <= boundary, `above` the rest. Both carry the hooks in registration order, so RunAll's (order, registration) sort produces exactly the sequence the undivided registry would have.

CHAOS-56 — this is how the late phase gets a RESERVE. The late hooks fall into two classes with opposite failure costs: drain hooks (stop accepting, let in-flight work finish) are best-effort and their loss costs a retry, while flush hooks (cluster store, syslog, badger, request log, audit, log sink) are what make the next boot clean and their loss costs durability or a corrupt store. Sharing one budget lets a stuck drain consume the whole envelope and starve every flush behind it; partitioning gives the flush hooks a slice that a drain cannot spend.

The split CONSUMES the source registry: it is marked as run, so a later RunAll on it is the documented idempotent no-op rather than a second execution of every hook, and a later Register panics exactly as it would after a RunAll. Without that, a caller that partitioned and then ran the original would close every store twice.

func (*Registry) Register

func (r *Registry) Register(name string, order int, stop func(context.Context) error)

Register adds a hook. name is a human-readable identifier used in error messages and logs. order determines execution order (lower runs first). Hooks with the same order run in registration order. Panics if stop is nil, or if Register is called after RunAll has executed — silently dropping a late registration would let a wiring mistake (e.g. P2.2 registering a hook after the shutdown path already ran in tests) skip shutdown logic without warning.

func (*Registry) RunAll

func (r *Registry) RunAll(ctx context.Context) error

RunAll executes all registered hooks in (order, registration-index) ascending order, passing ctx to each. All hooks run even if one returns an error; failures are aggregated via errors.Join and each wrapped error is labelled with its hook name. Idempotent: a second call returns nil without re-running.

CHAOS-56 — each hook runs under a WATCHDOG bounded by ctx's deadline plus DefaultGrace, and PANICS are contained. Before this, `ctx` was purely advisory: RunAll called every hook synchronously and several of them ignore the parameter entirely (the tunnel drain ran its own independent 15s timer; the badger/syslog/reqlog closers take no ctx at all), so a single hook that did not return — a gRPC GracefulStop behind a handler blocked on a wedged volume, a close on that same volume — stalled every hook after it for as long as the fault lasted. The hooks after it are the ones that make the NEXT boot clean, and the container's stop grace was the only thing bounding the sequence: the fault was resolved by SIGKILL, which abandons the stalled hook anyway and takes the durable flushes with it. Abandoning one hook is therefore never worse than the SIGKILL it replaces, and is usually much better.

Each hook's own budget comes from hookBudget, which reserves a minimum slice for every hook still behind it — see there for why the watchdog deadline is per-hook rather than per-phase. The overrun GRACE is the phase's, not the hook's: it is folded once into the horizon derived here, and hookBudget measures every slice against that horizon, so the phase overruns by at most one grace however many hooks stall AND no hook is left with an expired budget before it starts (see DefaultGrace).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL