Files
magpie/internal/cli/serve_drain.go
T
yetone ef997d186c serve: a SIGTERM finishes the requests in flight, for Kubernetes rolling updates
@justforlxz on X runs magpie in Kubernetes and every update cut the
requests in flight. A SIGTERM ended the gateway like Ctrl+C: the
listener closed at once and Shutdown cut what was left after 2s, an
agent's stream included, with no unready phase for the Service to see.

Now a SIGTERM to `magpie serve`, `magpie web` or `serve --web`:
- GET / answers 503 {"draining":true} at once, so `magpie healthcheck`
  (the image's HEALTHCHECK, and the readiness probe the docs give) fails
  and the pod leaves its Service's endpoints;
- in a pod (KUBERNETES_SERVICE_HOST) it keeps accepting for 5s while
  that reaches kube-proxy and the ingress, then stops accepting;
- the requests in flight, streams included, get up to MAGPIE_DRAIN to
  finish: unset, 20s in a pod (k8s' default grace is 30s, with room to
  save after) and 7s elsewhere (docker stop and Compose kill at 10s,
  and a drain past that would lose the state saved at the end);
  seconds or a Go duration; 0 ends after 2s as before; an unreadable
  value logs and uses the default. magpie web's page port (which
  serves /v1 too) shuts down within the same grace.
Ctrl+C and SIGHUP end as before. Nothing to configure.

A request still answering at the end of any drain was logged as "cut"
but kept running, its upstream call too, until the process exited:
Shutdown doesn't close active connections. The gateway now closes them
after a failed Shutdown, so a gateway restarted in-process (the GUI's
restart, a test) leaves nothing holding the provider catalog
(holdCatalog). TestDrainEndsAtItsGrace's cut request, still in flight
after it returned, made the next test, TestGrokGetsAgentMessageAsUser,
read migrations.json through that hold and fail in a full gateway run
on WSL; the test now waits for it to end, and without the Close that
wait fails at 30s.

PID 1: the image's ENTRYPOINT is exec form, so magpie is PID 1 and gets
the SIGTERM itself (it calls signal.Notify). As PID 1 it exits 2 rather
than 143 after the drain, the same on the old code.

/config shared by two pods (a RollingUpdate overlap) is not verified
safe: files are flock'd and written by rename, but the serving magpie's
sign-in renewal, plugin sign-in renewal and check-ins would run in both.
The docs say one pod per volume with strategy: Recreate (an RWO volume
on another node also stalls a RollingUpdate). Requests sent between the
old pod's end and the new one's start are refused; the drain covers what
was in flight.

Docs: a Kubernetes section (Deployment with an exec readiness probe,
terminationGracePeriodSeconds, Recreate, the RWO note) and a
MAGPIE_DRAIN row on docker.html in en, zh and ja; docs/reference.md's
Docker section; site index regenerated.

Run:
- TestDrainedGatewayFinishesItsStream, TestDrainEndsAtItsGrace,
  TestHandedOverGatewayFinishesItsStream, TestReadOnlyKeyEveryRoute,
  TestDrainGrace, TestDrainOnSignal and the cli Signal tests: ok (mica).
- Broken by hand: without Drain's grace in drainFor,
  TestDrainedGatewayFinishesItsStream fails "the gateway ended with a
  stream in flight".
- Real binary (before the 7s default, which applies outside a pod
  only, and the Close), sandbox HOME, fake SSE upstream streaming 10s, SIGTERM
  at +2s, KUBERNETES_SERVICE_HOST set, magpie as PID 1 in its own pid
  namespace (unshare) on Linux (WSL magpie-desktop), serve and web:
  new: healthcheck fails while draining, a new request 1s after SIGTERM
  200, the stream completes at +10s, exit at +11s. origin/main: the new
  request is refused, the stream is cut at +4s after 4 chunks. Also
  serve on macOS (mica): same, exit status 143.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build: ok (mica), before the 7s default
  and the Close.
- Full suite, go test -count=1 -timeout 45m ./..., on Linux (WSL
  magpie-desktop; mote and mica were each running another session's
  suite) at the first version of this change on 2051dfc23: every
  package ok except root, internal/cli and internal/gui, which can't
  build there (no gtk4/webkitgtk-6.0 dev packages), and
  internal/gateway, red on TestGrokGetsAgentMessageAsUser (the hold
  above, fixed here). The doneHold "close of closed channel" panic in
  the log is #6339/#6505/#6690, not this change.
- After the fixes: internal/gateway and internal/provider whole on WSL
  ok (1075s, 156s); root, internal/cli, internal/gui on mote ok.
- At this head, rebased on 1c9c359f9: internal/cli whole and the drain,
  handover, Codex tool and Grok gateway tests ok (mote); go vet of
  gateway/cli/gui, GOOS=windows the same, GOOS=linux -tags nogui of
  gateway/cli ok (mote).

Not tried: the real Docker image build and a real Kubernetes cluster
(no Docker daemon on mote, mica or WSL; Docker Desktop on xiaomi-gpu is
not running).
2026-11-19 13:04:38 +08:00

91 lines
3.0 KiB
Go

package cli
import (
"log"
"os"
"strconv"
"strings"
"syscall"
"time"
"github.com/yetone/magpie/internal/gateway"
)
// A SIGTERM to `magpie serve` is how Kubernetes, Docker and a service
// manager end it, a rolling update's old pod included (@justforlxz on X:
// "直接重启更新会中断请求"). Before, the gateway's end gave the requests
// in flight 2s and cut the rest, a stream an agent was reading too. Now a
// SIGTERM drains: GET / answers 503 at once (so `magpie healthcheck`, the
// readiness probe, fails), the gateway keeps answering for a moment where
// Kubernetes is still sending it requests, then stops accepting and gives
// what is in flight the rest of MAGPIE_DRAIN to finish. Ctrl+C (SIGINT)
// and SIGHUP still end it at once.
// defaultDrain is MAGPIE_DRAIN unset in a Kubernetes pod: within its
// default 30s terminationGracePeriodSeconds, with room for the session
// index and the plugin hosts after it. Elsewhere it is plainDrain:
// `docker stop` and Compose kill after 10s, and a drain past that would
// lose the state magpie saves as it ends.
const (
defaultDrain = 20 * time.Second
plainDrain = 7 * time.Second
)
// unsetDrain is the drain with MAGPIE_DRAIN unset (defaultDrain).
func unsetDrain() time.Duration {
if os.Getenv("KUBERNETES_SERVICE_HOST") != "" {
return defaultDrain
}
return plainDrain
}
// kubeLinger is how long a gateway in a Kubernetes pod keeps accepting
// after a SIGTERM: the pod leaves its Service's endpoints as the SIGTERM
// is sent, and kube-proxy and an ingress take a few seconds to stop
// sending it new connections, which a closed port would refuse. A var
// so tests can shorten it.
var kubeLinger = 5 * time.Second
// lingerSleep is time.Sleep; a var so tests can see the linger.
var lingerSleep = time.Sleep
// drainOnSignal readies g's end for sig: a SIGTERM drains (gateway.Drain),
// any other signal ends it as before. g is nil for a `magpie web` whose
// gateway another magpie serves: nothing here to drain.
func drainOnSignal(g *gateway.Server, sig os.Signal) {
if g == nil || sig != syscall.SIGTERM {
return
}
grace := drainGrace()
if grace <= 0 {
return
}
var linger time.Duration
if os.Getenv("KUBERNETES_SERVICE_HOST") != "" {
linger = min(kubeLinger, grace/2)
}
g.Drain(grace - linger)
log.Printf("magpie: SIGTERM, finishing the requests in flight (up to %s; MAGPIE_DRAIN sets it)", grace)
if linger > 0 {
lingerSleep(linger)
}
}
// drainGrace is MAGPIE_DRAIN: seconds ("30") or a duration ("90s",
// "2m"), unsetDrain when unset or unreadable, and "0" for the old 2s
// end.
func drainGrace() time.Duration {
v := strings.TrimSpace(os.Getenv("MAGPIE_DRAIN"))
if v == "" {
return unsetDrain()
}
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
return time.Duration(n) * time.Second
}
if d, err := time.ParseDuration(v); err == nil && d >= 0 {
return d
}
log.Printf("magpie: MAGPIE_DRAIN=%q is neither seconds nor a duration (30, 90s); draining for %s", v, unsetDrain())
return unsetDrain()
}