From 6766d92bdd4b7cbb7aee171cddc9b79e655b1693 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Thu, 26 Nov 2026 16:26:10 +0000 Subject: [PATCH] feat(cmd): reload the standalone config when the file changes The standalone binary now reads its config file every -reload-interval (default 5s) and on SIGHUP. When the content changes, it builds a new gateway and sends new requests to it. Requests that already run finish on the old gateway, which closes when the last one leaves or after -reload-drain-timeout (default 10m). A config that does not decode or that New() rejects is logged, and the old gateway keeps serving. SIGHUP rebuilds even when the content is unchanged, so a rotated file: secret takes effect. One atomic word holds the request count and the retired flag. With two separate atomics, a reload between them could close a gateway that a new request is still serving. --- cmd/gateway/main.go | 86 +++++++--- cmd/gateway/reload.go | 179 +++++++++++++++++++++ cmd/gateway/reload_test.go | 322 +++++++++++++++++++++++++++++++++++++ 3 files changed, 562 insertions(+), 25 deletions(-) create mode 100644 cmd/gateway/reload.go create mode 100644 cmd/gateway/reload_test.go diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go index c60e1b5..8f9b3e2 100644 --- a/cmd/gateway/main.go +++ b/cmd/gateway/main.go @@ -1,5 +1,5 @@ // Command gateway runs the LLM gateway as a standalone compiled binary, -// sitting BEHIND Traefik rather than inside it. +// sitting behind a reverse proxy rather than inside Traefik. // // This is deployment form (B). Form (A) — the Yaegi-interpreted Traefik // middleware plugin — is unchanged and remains the default; both forms are @@ -74,6 +74,8 @@ const ( defaultReadHeaderWait = 10 * time.Second defaultIdleTimeout = 120 * time.Second defaultMaxHeaderBytes = 1 << 20 + defaultReloadEvery = 5 * time.Second + defaultReloadDrain = 10 * time.Minute ) // telemetryOptOutVars are the environment variables oss-telemetry itself @@ -105,6 +107,8 @@ type options struct { readyPath string shutdownWait time.Duration drainDelay time.Duration + reloadEvery time.Duration + reloadDrain time.Duration showVersion bool } @@ -135,10 +139,17 @@ func parseOptions(args []string, stderr *os.File) (*options, error) { fs.DurationVar(&o.drainDelay, "drain-delay", envDurationOr("LLMGW_DRAIN_DELAY", defaultDrainDelay), "how long to keep serving after readiness starts failing, so the load balancer can drop this "+ "endpoint before the listener closes [LLMGW_DRAIN_DELAY]") + fs.DurationVar(&o.reloadEvery, "reload-interval", envDurationOr("LLMGW_RELOAD_INTERVAL", defaultReloadEvery), + "how often to check the config file for changes; 0 turns polling off (SIGHUP still reloads) [LLMGW_RELOAD_INTERVAL]") + fs.DurationVar(&o.reloadDrain, "reload-drain-timeout", envDurationOr("LLMGW_RELOAD_DRAIN_TIMEOUT", defaultReloadDrain), + "how long a replaced gateway keeps running for its in-flight requests before it is closed [LLMGW_RELOAD_DRAIN_TIMEOUT]") fs.BoolVar(&o.showVersion, "version", false, "print this binary's version and exit") 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.healthPath == o.readyPath { return nil, fmt.Errorf("-health-path and -ready-path must differ (both are %q)", o.healthPath) } @@ -219,30 +230,13 @@ func run() error { } log := newLogger(opts.logLevel) - cfg, err := loadConfig(opts.configPath) + raw, err := os.ReadFile(opts.configPath) if err != nil { - return err + return fmt.Errorf("read config: %w", err) } log.info("starting version=%s name=%s config=%s listen=%s", version, opts.name, opts.configPath, opts.listenAddr) logTelemetryOptOut(log) - // passthroughUnknown routes an unrecognized path to the `next` - // handler. In form (A) that is the Traefik router's own backing - // service; in form (B) Traefik is IN FRONT of this process and there - // is no downstream at all, so the flag cannot mean what it means in - // the plugin. This is a warning rather than a hard error because the - // terminal handler below keeps the behaviour well-defined (a clean - // 404) — an operator carrying a working plugin config across should - // not be blocked, only told. - if cfg.PassthroughUnknown { - log.warn("passthroughUnknown is set, but a standalone binary has no downstream to pass through to: " + - "unknown routes return 404. Route non-gateway paths in Traefik instead.") - } - - if msg, warn := metricsCIDRWarning(cfg); warn { - log.warn(msg) - } - // signal.NotifyContext, not context.Background(): New blocks on the // registry's synchronous warm-fill, which with a large provider set // can run for minutes before the listener ever opens. A SIGTERM @@ -251,9 +245,10 @@ func run() error { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() - handler, err := traefikllmgateway.New(ctx, terminalHandler(), cfg, opts.name) + build := gatewayBuilder(ctx, opts.configPath, opts.name, log) + handler, err := build(raw) if err != nil { - return fmt.Errorf("construct gateway: %w", err) + return err } if ctx.Err() != nil { log.info("signal received during startup; exiting before serving") @@ -261,10 +256,13 @@ func run() error { return nil } + sw := &swapHandler{} + sw.cur.Store(newGeneration(handler, func() { closeGateway(handler, log) })) + var ready atomic.Bool srv := &http.Server{ Addr: opts.listenAddr, - Handler: withHealth(handler, &ready, opts.healthPath, opts.readyPath), + Handler: withHealth(sw, &ready, opts.healthPath, opts.readyPath), // Bounds a Slowloris header trickle (and satisfies gosec G112). ReadHeaderTimeout: defaultReadHeaderWait, // ReadTimeout and WriteTimeout are BOTH deliberately zero. @@ -311,12 +309,21 @@ func run() error { go func() { errCh <- srv.ListenAndServe() }() log.info("listening on %s (health %s, ready %s)", opts.listenAddr, opts.healthPath, opts.readyPath) + hup := make(chan os.Signal, 1) + signal.Notify(hup, syscall.SIGHUP) + defer signal.Stop(hup) + reloadDone := make(chan struct{}) + go func() { + defer close(reloadDone) + newReloader(opts.configPath, raw, build, sw, opts.reloadDrain, log).run(ctx, opts.reloadEvery, hup) + }() + select { case err := <-errCh: // 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) { - closeGateway(handler, log) + sw.closeCurrent() return fmt.Errorf("listen on %s: %w", opts.listenAddr, err) } return nil @@ -347,6 +354,9 @@ func run() error { log.error("shutdown: %v", err) } + // The reloader exits on ctx; waiting for it means no swap lands after the close below. + <-reloadDone + // STRICTLY after Shutdown returns. Close releases the pooled Redis // connections shared by the limiter's store and the response cache; // closing them while requests are still draining would pull Redis out @@ -354,11 +364,31 @@ func run() error { // default those requests would silently fall back to in-process // counters rather than fail — a correctness regression invisible in // the logs. - closeGateway(handler, log) + sw.closeCurrent() log.info("stopped") return nil } +// logConfigWarnings logs the config settings that mean something else, or nothing, in a standalone binary. +func logConfigWarnings(cfg *traefikllmgateway.Config, log *logger) { + // passthroughUnknown routes an unrecognized path to the `next` + // handler. In form (A) that is the Traefik router's own backing + // service; in form (B) Traefik is IN FRONT of this process and there + // is no downstream at all, so the flag cannot mean what it means in + // the plugin. This is a warning rather than a hard error because the + // terminal handler below keeps the behaviour well-defined (a clean + // 404) — an operator carrying a working plugin config across should + // not be blocked, only told. + if cfg.PassthroughUnknown { + log.warn("passthroughUnknown is set, but a standalone binary has no downstream to pass through to: " + + "unknown routes return 404. Route non-gateway paths in Traefik instead.") + } + + if msg, warn := metricsCIDRWarning(cfg); warn { + log.warn(msg) + } +} + // closeGateway releases the Gateway's pooled resources when the handler // New returned exposes Close. // @@ -480,6 +510,12 @@ func loadConfig(path string) (*traefikllmgateway.Config, error) { if err != nil { return nil, fmt.Errorf("read config: %w", err) } + return decodeConfig(path, raw) +} + +// decodeConfig decodes raw the way loadConfig does. path picks the format by its extension and names errors. +func decodeConfig(path string, raw []byte) (*traefikllmgateway.Config, error) { + var err error doc := raw if !strings.EqualFold(filepath.Ext(path), ".json") { if doc, err = yamlToJSON(raw); err != nil { diff --git a/cmd/gateway/reload.go b/cmd/gateway/reload.go new file mode 100644 index 0000000..c40f146 --- /dev/null +++ b/cmd/gateway/reload.go @@ -0,0 +1,179 @@ +package main + +import ( + "context" + "crypto/sha256" + "fmt" + "net/http" + "os" + "sync" + "sync/atomic" + "time" + + traefikllmgateway "github.com/lukaszraczylo/traefik-llmgateway" +) + +// genRetired is the retired flag in a generation's state word. The bits below it count the requests running on it. +// The flag and the count share one atomic so that leave sees both in one operation (formal/Gateway/Reload.lean). +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 +} + +func newGeneration(h http.Handler, closeFn func()) *generation { + return &generation{h: h, closeFn: closeFn} +} + +// enter counts a request in. It returns false when the generation is retired; the caller must not serve on it. +func (g *generation) enter() bool { + if g.state.Add(1)&genRetired != 0 { + g.leave() + return false + } + return true +} + +func (g *generation) leave() { + if g.state.Add(-1) == genRetired { + g.shut() + } +} + +// retire stops new requests. The gateway closes when the last running request leaves, or after maxWait. +func (g *generation) retire(maxWait time.Duration) { + for { + old := g.state.Load() + if old&genRetired != 0 { + return + } + if g.state.CompareAndSwap(old, old|genRetired) { + if old == 0 { + g.shut() + return + } + break + } + } + time.AfterFunc(maxWait, g.shut) +} + +func (g *generation) shut() { g.once.Do(g.closeFn) } + +// swapHandler serves every request on the current generation. +type swapHandler struct { + cur atomic.Pointer[generation] +} + +func (s *swapHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + for { + g := s.cur.Load() + // A false enter means a swap already installed a newer generation, so the next load finds it. + if g.enter() { + defer g.leave() + g.h.ServeHTTP(w, r) + return + } + } +} + +// swap installs next and retires the generation it replaces. +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. +func (s *swapHandler) closeCurrent() { + if g := s.cur.Load(); g != nil { + g.shut() + } +} + +// gatewayBuilder decodes raw as the config at path and constructs a gateway from it. +func gatewayBuilder(ctx context.Context, path, name string, log *logger) func(raw []byte) (http.Handler, error) { + return func(raw []byte) (http.Handler, error) { + cfg, err := decodeConfig(path, raw) + if err != nil { + return nil, err + } + logConfigWarnings(cfg, log) + h, err := traefikllmgateway.New(ctx, terminalHandler(), cfg, name) + if err != nil { + return nil, fmt.Errorf("construct gateway: %w", err) + } + return h, nil + } +} + +// 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 +} + +// newReloader starts from the content the serving gateway was built from. +func newReloader(path string, raw []byte, build func([]byte) (http.Handler, error), swap *swapHandler, drain time.Duration, log *logger) *reloader { + 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. +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)) + return + } + 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) + return + } + 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 + } + r.lastErr = msg + r.log.error("%s", msg) +} + +// run checks the file every interval (never when interval is 0) and on every value from hup, until ctx ends. +func (r *reloader) run(ctx context.Context, interval time.Duration, hup <-chan os.Signal) { + var tick <-chan time.Time + if interval > 0 { + t := time.NewTicker(interval) + defer t.Stop() + tick = t.C + } + for { + select { + case <-ctx.Done(): + return + case <-tick: + r.check(false) + case <-hup: + r.log.info("reload: SIGHUP, rebuilding from %s", r.path) + r.check(true) + } + } +} diff --git a/cmd/gateway/reload_test.go b/cmd/gateway/reload_test.go new file mode 100644 index 0000000..1de6470 --- /dev/null +++ b/cmd/gateway/reload_test.go @@ -0,0 +1,322 @@ +package main + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + traefikllmgateway "github.com/lukaszraczylo/traefik-llmgateway" +) + +// countingGen returns a generation over h whose close increments *closes. +func countingGen(h http.Handler, closes *atomic.Int32) *generation { + return newGeneration(h, func() { closes.Add(1) }) +} + +func okHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }) +} + +func TestGenerationLifecycle(t *testing.T) { + tests := []struct { + run func(g *generation) + name string + wantCloses int32 + }{ + {name: "idle retire closes at once", run: func(g *generation) { g.retire(time.Hour) }, wantCloses: 1}, + {name: "retire waits for the running request", run: func(g *generation) { + g.enter() + g.retire(time.Hour) + }, wantCloses: 0}, + {name: "last leave closes a retired generation", run: func(g *generation) { + g.enter() + g.enter() + g.retire(time.Hour) + g.leave() + g.leave() + }, wantCloses: 1}, + {name: "leave on a live generation keeps it open", run: func(g *generation) { + g.enter() + g.leave() + }, wantCloses: 0}, + {name: "enter after retire is refused and closes nothing twice", run: func(g *generation) { + g.retire(time.Hour) + if g.enter() { + t.Error("enter on a retired generation must return false") + } + }, wantCloses: 1}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var closes atomic.Int32 + g := countingGen(okHandler(), &closes) + tt.run(g) + if got := closes.Load(); got != tt.wantCloses { + t.Errorf("closes = %d, want %d", got, tt.wantCloses) + } + }) + } +} + +func TestGenerationDrainTimeoutForcesClose(t *testing.T) { + var closes atomic.Int32 + g := countingGen(okHandler(), &closes) + g.enter() + g.retire(20 * time.Millisecond) + deadline := time.Now().Add(2 * time.Second) + for closes.Load() == 0 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if closes.Load() != 1 { + t.Fatalf("closes = %d after the drain timeout, want 1", closes.Load()) + } + g.leave() + if closes.Load() != 1 { + t.Errorf("a leave after the forced close closed again: %d", closes.Load()) + } +} + +// TestSwapHandlerKeepsLongRequestOnOldGeneration: a request that started +// before a swap finishes on its own gateway, new requests reach the new +// one, and the old gateway closes only when the long request ends. +func TestSwapHandlerKeepsLongRequestOnOldGeneration(t *testing.T) { + release := make(chan struct{}) + started := make(chan struct{}) + oldH := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + close(started) + <-release + w.Header().Set("X-Gen", "old") + }) + newH := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("X-Gen", "new") }) + + var oldCloses, newCloses atomic.Int32 + sw := &swapHandler{} + sw.cur.Store(countingGen(oldH, &oldCloses)) + + longRec := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + sw.ServeHTTP(longRec, httptest.NewRequest(http.MethodGet, "/", nil)) + close(done) + }() + <-started + + sw.swap(countingGen(newH, &newCloses), time.Hour) + + rec := httptest.NewRecorder() + sw.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + if got := rec.Header().Get("X-Gen"); got != "new" { + t.Errorf("request after swap served by %q, want new", got) + } + if oldCloses.Load() != 0 { + t.Fatal("old gateway closed while its request was still running") + } + close(release) + <-done + if got := longRec.Header().Get("X-Gen"); got != "old" { + t.Errorf("long request served by %q, want old", got) + } + if oldCloses.Load() != 1 || newCloses.Load() != 0 { + t.Errorf("closes old=%d new=%d, want 1 and 0", oldCloses.Load(), newCloses.Load()) + } +} + +// TestSwapHandlerNeverServesOnClosedGeneration races requests against +// swaps under -race. Each handler fails the test if its own gateway is +// already closed when it runs: that is the invariant formal/Gateway/Reload.lean +// proves for the packed state word. +func TestSwapHandlerNeverServesOnClosedGeneration(t *testing.T) { + sw := &swapHandler{} + var bad atomic.Int32 + mk := func() *generation { + var closed atomic.Bool + h := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if closed.Load() { + bad.Add(1) + } + w.WriteHeader(http.StatusNoContent) + }) + return newGeneration(h, func() { closed.Store(true) }) + } + sw.cur.Store(mk()) + + var wg sync.WaitGroup + stop := make(chan struct{}) + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + sw.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + } + }() + } + for i := 0; i < 300; i++ { + sw.swap(mk(), time.Hour) + } + close(stop) + wg.Wait() + if n := bad.Load(); n != 0 { + t.Fatalf("%d requests ran on a closed generation", n) + } +} + +// fakeBuild records each build and fails when the file holds "bad". +type fakeBuild struct { + calls atomic.Int32 +} + +func (f *fakeBuild) build(raw []byte) (http.Handler, error) { + f.calls.Add(1) + if strings.Contains(string(raw), "bad") { + return nil, errors.New("rejected") + } + body := string(raw) + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(body)) }), nil +} + +func serveBody(t *testing.T, h http.Handler) string { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + return rec.Body.String() +} + +func TestReloaderAppliesOnlyChangedValidConfig(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + write := func(s string) { + t.Helper() + if err := os.WriteFile(path, []byte(s), 0o600); err != nil { + t.Fatal(err) + } + } + write("one") + fb := &fakeBuild{} + h0, _ := fb.build([]byte("one")) + sw := &swapHandler{} + sw.cur.Store(newGeneration(h0, func() {})) + r := newReloader(path, []byte("one"), fb.build, sw, time.Hour, newLogger("error")) + fb.calls.Store(0) + + steps := []struct { + name string + content string + wantBody string + wantCalls int32 + force bool + }{ + {"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}, + } + for _, s := range steps { + write(s.content) + r.check(s.force) + if got := serveBody(t, sw); got != s.wantBody { + t.Errorf("%s: served %q, want %q", s.name, got, s.wantBody) + } + if got := fb.calls.Load(); got != s.wantCalls { + t.Errorf("%s: builds = %d, want %d", s.name, got, s.wantCalls) + } + } +} + +func TestReloaderMissingFileKeepsServing(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + fb := &fakeBuild{} + h0, _ := fb.build([]byte("one")) + sw := &swapHandler{} + sw.cur.Store(newGeneration(h0, func() {})) + r := newReloader(path, []byte("one"), fb.build, sw, time.Hour, newLogger("error")) + r.check(false) + if got := serveBody(t, sw); got != "one" { + t.Errorf("served %q after the file vanished, want one", got) + } +} + +// TestReloadRealGateway reloads a real gateway from a config file and +// checks that the model list follows the file. +func TestReloadRealGateway(t *testing.T) { + const tmpl = `providers: + openai: + type: openai + apiKey: test-key + models: + - %s +groups: + default: + providers: [] +users: + inline: + - name: tester + group: default + apiKey: test-user-key +` + path := filepath.Join(t.TempDir(), "config.yaml") + cfgFor := func(model string) []byte { return []byte(strings.Replace(tmpl, "%s", model, 1)) } + if err := os.WriteFile(path, cfgFor("model-a"), 0o600); err != nil { + t.Fatal(err) + } + log := newLogger("error") + build := gatewayBuilder(context.Background(), path, "test", log) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + h, err := build(raw) + if err != nil { + t.Fatalf("build: %v", err) + } + sw := &swapHandler{} + sw.cur.Store(newGeneration(h, func() { closeGateway(h, log) })) + r := newReloader(path, raw, build, sw, time.Hour, log) + t.Cleanup(sw.closeCurrent) + + models := func() string { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/v1/models", nil) + req.Header.Set("Authorization", "Bearer test-user-key") + sw.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("/v1/models = %d: %s", rec.Code, rec.Body.String()) + } + return rec.Body.String() + } + if body := models(); !strings.Contains(body, "model-a") { + t.Fatalf("initial models lack model-a: %s", body) + } + if err := os.WriteFile(path, cfgFor("model-b"), 0o600); err != nil { + t.Fatal(err) + } + r.check(false) + body := models() + if !strings.Contains(body, "model-b") || strings.Contains(body, "model-a") { + t.Fatalf("models after reload = %s, want model-b only", body) + } +} + +// TestGatewayBuilderRejectsUnknownField keeps the strict decode on reload. +func TestGatewayBuilderRejectsUnknownField(t *testing.T) { + build := gatewayBuilder(context.Background(), "config.yaml", "test", newLogger("error")) + if _, err := build([]byte("providers: {}\nnotAField: 1\n")); err == nil { + t.Fatal("unknown field accepted on reload") + } +} + +var _ http.Handler = (*traefikllmgateway.Gateway)(nil)