fix(cmd): retry a rejected reload and tighten the drain lifecycle

Review findings on the standalone config reload:

- A rejected config is now retried on every check, because the cause can
  be outside the file, such as a secret file that is not mounted yet.
  Each distinct error is logged once. A read error and a build error are
  tracked apart, so one does not hide the other.
- A closed generation stops its drain timer, so the timer no longer
  holds the old gateway in memory until it fires.
- closeCurrent marks the generation retired before it closes, so a late
  request does not run on a closed gateway.
- -reload-drain-timeout must be positive. A zero value closed running
  requests at once.
- The listen-error path waits for the reloader before the close, the
  same as the signal path. The reloader does not build after ctx ends.
This commit is contained in:
2026-11-26 16:30:20 +00:00
parent 86520acc2f
commit 60029a047e
4 changed files with 130 additions and 36 deletions
+7 -2
View File
@@ -147,8 +147,11 @@ func parseOptions(args []string, stderr *os.File) (*options, error) {
if err := fs.Parse(args); err != nil {
return nil, err
}
if o.reloadEvery < 0 || o.reloadDrain < 0 {
return nil, fmt.Errorf("-reload-interval and -reload-drain-timeout must not be negative")
if o.reloadEvery < 0 {
return nil, fmt.Errorf("-reload-interval must not be negative, got %s", o.reloadEvery)
}
if o.reloadDrain <= 0 {
return nil, fmt.Errorf("-reload-drain-timeout must be positive, got %s", o.reloadDrain)
}
if o.healthPath == o.readyPath {
return nil, fmt.Errorf("-health-path and -ready-path must differ (both are %q)", o.healthPath)
@@ -323,6 +326,8 @@ func run() error {
// ErrServerClosed only ever arrives after a Shutdown this
// function did not start, so reaching it here is a real failure.
if !errors.Is(err, http.ErrServerClosed) {
stop()
<-reloadDone
sw.closeCurrent()
return fmt.Errorf("listen on %s: %w", opts.listenAddr, err)
}
+64 -29
View File
@@ -19,10 +19,12 @@ const genRetired int64 = 1 << 62
// generation is one constructed gateway and the requests running on it.
type generation struct {
h http.Handler
closeFn func()
state atomic.Int64
once sync.Once
h http.Handler
closeFn func()
timer atomic.Pointer[time.Timer]
state atomic.Int64
once sync.Once
shutDone atomic.Bool
}
func newGeneration(h http.Handler, closeFn func()) *generation {
@@ -46,23 +48,48 @@ func (g *generation) leave() {
// retire stops new requests. The gateway closes when the last running request leaves, or after maxWait.
func (g *generation) retire(maxWait time.Duration) {
if !g.markRetired() {
return
}
g.timer.Store(time.AfterFunc(maxWait, g.shut))
// A shut that ran before the Store could not stop the timer, so stop it here.
if g.shutDone.Load() {
g.stopTimer()
}
}
// markRetired sets the retired flag. It returns true when requests are still running, so the close waits for them.
// It closes an idle generation at once, and returns false when the generation was already retired.
func (g *generation) markRetired() bool {
for {
old := g.state.Load()
if old&genRetired != 0 {
return
return false
}
if g.state.CompareAndSwap(old, old|genRetired) {
if old == 0 {
g.shut()
return
return false
}
break
return true
}
}
time.AfterFunc(maxWait, g.shut)
}
func (g *generation) shut() { g.once.Do(g.closeFn) }
// shut closes the gateway once and stops the drain timer, so a closed generation is not held until it fires.
func (g *generation) shut() {
g.once.Do(func() {
g.closeFn()
g.shutDone.Store(true)
g.stopTimer()
})
}
func (g *generation) stopTimer() {
if t := g.timer.Load(); t != nil {
t.Stop()
}
}
// swapHandler serves every request on the current generation.
type swapHandler struct {
@@ -86,9 +113,11 @@ func (s *swapHandler) swap(next *generation, drain time.Duration) {
s.cur.Swap(next).retire(drain)
}
// closeCurrent closes the serving generation. Call it only after the server stopped serving.
// closeCurrent closes the serving generation and turns away any request that arrives later.
// Call it only after the server stopped serving.
func (s *swapHandler) closeCurrent() {
if g := s.cur.Load(); g != nil {
g.markRetired()
g.shut()
}
}
@@ -111,13 +140,14 @@ func gatewayBuilder(ctx context.Context, path, name string, log *logger) func(ra
// reloader rebuilds the gateway when the config file content changes. Only its run goroutine calls check.
type reloader struct {
build func(raw []byte) (http.Handler, error)
swap *swapHandler
log *logger
path string
lastErr string
drain time.Duration
last [sha256.Size]byte
build func(raw []byte) (http.Handler, error)
swap *swapHandler
log *logger
path string
readErr string
buildErr string
drain time.Duration
last [sha256.Size]byte
}
// newReloader starts from the content the serving gateway was built from.
@@ -125,36 +155,37 @@ func newReloader(path string, raw []byte, build func([]byte) (http.Handler, erro
return &reloader{build: build, swap: swap, log: log, path: path, drain: drain, last: sha256.Sum256(raw)}
}
// check rebuilds when the file content differs from the last attempt, or always when force is set.
// A rejected config keeps the old gateway serving and is not retried until the file changes again.
// check rebuilds when the file content differs from the serving config, or always when force is set.
// A rejected config keeps the old gateway serving. It is retried on every check, because the cause can be outside
// the file (a secret file not mounted yet); each distinct error is logged once.
func (r *reloader) check(force bool) {
raw, err := os.ReadFile(r.path)
if err != nil {
r.logOnce(fmt.Sprintf("reload: read %s: %v; still serving the previous config", r.path, err))
r.readErr = r.logOnce(r.readErr, fmt.Sprintf("reload: read %s: %v; still serving the previous config", r.path, err))
return
}
r.readErr = ""
sum := sha256.Sum256(raw)
if sum == r.last && !force {
return
}
r.last = sum
h, err := r.build(raw)
r.lastErr = ""
if err != nil {
r.log.error("reload: config %s rejected; still serving the previous config: %v", r.path, err)
r.buildErr = r.logOnce(r.buildErr, fmt.Sprintf("reload: config %s rejected; still serving the previous config: %v", r.path, err))
return
}
r.buildErr = ""
r.last = sum
r.swap.swap(newGeneration(h, func() { closeGateway(h, r.log) }), r.drain)
r.log.info("reload: config %s applied", r.path)
}
// logOnce logs msg unless it repeats the previous error, so a missing file does not log every interval.
func (r *reloader) logOnce(msg string) {
if msg == r.lastErr {
return
// logOnce logs msg unless it equals prev, and returns msg as the new previous error.
func (r *reloader) logOnce(prev, msg string) string {
if msg != prev {
r.log.error("%s", msg)
}
r.lastErr = msg
r.log.error("%s", msg)
return msg
}
// run checks the file every interval (never when interval is 0) and on every value from hup, until ctx ends.
@@ -170,6 +201,10 @@ func (r *reloader) run(ctx context.Context, interval time.Duration, hup <-chan o
case <-ctx.Done():
return
case <-tick:
// select picks at random when ctx and tick are both ready; do not build after a shutdown signal.
if ctx.Err() != nil {
return
}
r.check(false)
case <-hup:
r.log.info("reload: SIGHUP, rebuilding from %s", r.path)
+55 -3
View File
@@ -174,6 +174,57 @@ func TestSwapHandlerNeverServesOnClosedGeneration(t *testing.T) {
}
}
func TestCloseCurrentTurnsAwayLaterRequests(t *testing.T) {
var closes atomic.Int32
sw := &swapHandler{}
g := countingGen(okHandler(), &closes)
sw.cur.Store(g)
sw.closeCurrent()
if closes.Load() != 1 {
t.Fatalf("closes = %d, want 1", closes.Load())
}
if g.enter() {
t.Error("enter after closeCurrent must return false")
}
}
func TestShutStopsDrainTimer(t *testing.T) {
var closes atomic.Int32
g := countingGen(okHandler(), &closes)
g.enter()
g.retire(time.Hour)
g.leave()
tm := g.timer.Load()
if tm == nil {
t.Fatal("retire with a running request set no drain timer")
}
if tm.Stop() {
t.Error("drain timer still pending after the generation closed")
}
}
func TestParseOptionsReloadBounds(t *testing.T) {
tests := []struct {
name string
args []string
wantErr bool
}{
{"defaults", nil, false},
{"polling off", []string{"-reload-interval", "0"}, false},
{"negative interval", []string{"-reload-interval", "-1s"}, true},
{"zero drain", []string{"-reload-drain-timeout", "0"}, true},
{"negative drain", []string{"-reload-drain-timeout", "-1s"}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := parseOptions(tt.args, os.Stderr)
if (err != nil) != tt.wantErr {
t.Errorf("err = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
// fakeBuild records each build and fails when the file holds "bad".
type fakeBuild struct {
calls atomic.Int32
@@ -221,9 +272,10 @@ func TestReloaderAppliesOnlyChangedValidConfig(t *testing.T) {
{"same content does not rebuild", "one", "one", 0, false},
{"changed content applies", "two", "two", 1, false},
{"rejected config keeps the old gateway", "bad", "two", 2, false},
{"rejected content is not retried until it changes", "bad", "two", 2, false},
{"a fixed file applies", "three", "three", 3, false},
{"force rebuilds unchanged content", "three", "three", 4, true},
{"rejected content is retried on the next check", "bad", "two", 3, false},
{"a fixed file applies", "three", "three", 4, false},
{"applied content is not rebuilt again", "three", "three", 4, false},
{"force rebuilds unchanged content", "three", "three", 5, true},
}
for _, s := range steps {
write(s.content)