Files
magpie/internal/gateway/serving.go
T
yetone 9bf5848c1f gateway: a Kubernetes rolling update runs two pods on one volume safely
@justforlxz on X asked for a RollingUpdate (maxSurge 1, maxUnavailable
0) with no request dropped. The docs said strategy: Recreate, because
the work only the serving magpie may do (renewing sign-ins, check-ins,
moves, plugin updates, WhileServing) was kept to one magpie only by the
gateway's port: a second couldn't bind it. Two pods each bind their own
network namespace, so in an overlap both did it, and two renewals of
one refresh token can spend it (a single-use token rotates).

Design: both pods answer requests at once (each refresh and file write
is already locked across processes: filelock, host.js lockRenew); the
serving work is held to whichever gateway holds gateway.serving.lock
(flock on the config folder, serving.go). The new pod retries every
second and takes the work over as the old pod's gateway ends (its drain
lets go first). A file system without locks is read as no other magpie,
as before.

Pods share the volume but not a pid namespace (both run magpie as pid
1), so the locks that judged a holder by its pid now judge it by host:
- host.js lockRenew records host (hostname + pid namespace); a lock of
  another host is stale by age only, never by "pid 1 is alive here".
- lockMoves (migrate.go) the same.
- gateway.json records Host; forgetListening removes only its own, so
  the old pod's end no longer removes the new pod's file (same pid,
  same Started second was enough before).
- temp and run-mark names get a random part (writeDurable, Claude run
  marks, gateway.json's temp file).

While draining (SIGTERM), every reply says Connection: close, on the
gateway and on magpie web's page port, so an agent that kept its
connection to the old pod alive dials the Service again for its next
request. Without it, the real rollout below had one broken pipe per
kept-alive connection, ~5.8s after each SIGTERM, when the drain's end
closed them.

Docs (en/zh/ja docker, reference.md): RollingUpdate maxSurge 1 /
maxUnavailable 0, the readiness probe, a required podAffinity on
kubernetes.io/hostname (a ReadWriteOnce volume mounts on one node), and
one Recreate update from a version before this one, whose old pod
doesn't take the lock.

Run:
- Real overlap, podman 4.9.3 in WSL magpie-desktop: three pods
  (pa -> pb -> pc) on one volume, each its own container (pid 1, own
  hostname and network), a Service proxy over a readiness-probed
  endpoint list (1s probe, endpoint removed 1s after SIGTERM as
  kube-proxy does), 12 agents streaming 3s SSE turns through it, half
  keeping connections alive, no retries. Before Connection: close: 226
  ok, 10 failed (broken pipe, kept-alive). After: 209 ok, 0 failed;
  second run 207 ok, 0 failed. Each new pod logged "another magpie serves", then
  "let go" as the old pod's gateway ended; gateway.json named the last
  pod.
- Broken by hand, each red then green: TestServingWorkWaitsForTheOther-
  Magpie, TestServingWaitEndsWithItsGateway, TestForgetListeningKeeps-
  AnotherPods, TestMoveLockOfAnotherPod, TestRenewLockOfAnotherPodIs-
  WaitedFor, TestDrainingRepliesCloseTheirConnection,
  TestPagePortClosesWhileDraining.
- Full suite, go test -count=1 -timeout 45m ./..., at 85305a82d (this
  change on 2926b7bef): macOS on mote, 102 packages ok; Linux
  (-tags nogui) in WSL magpie-desktop, 101 ok. Reds:
  - TestAuthLockWaitDoesNotFreezeTheHost, both: this change's
    writeDurable called randomUUID, which the test's sandbox of host.js
    doesn't give. It now names the temp file with Math.random; plugin
    then ok on mote and on Linux.
  - Not this change, filed: TestCappedIsSmall (Linux, #5975),
    TestRequestStateKeptAcrossACatalogFetchedAgain (Linux, #6572),
    TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes (macOS, #7117).
  - Not a red, filed: the macOS log has a recovered "http: panic
    serving ...: close of closed channel" in the doneHold test fake
    (continuation_test.go:781); no test failed on it. It is #6505
    (also filed as #6339 and #6690).
- go vet ./..., GOOS=linux -tags nogui and GOOS=windows go vet ./... ok
  on mote; go vet -tags nogui ./... ok on Linux; gofmt -l clean.
- At the pushed head (rebased on 6e5882109), on mote: go vet (macOS,
  GOOS=linux -tags nogui, GOOS=windows) of gateway, gui, plugin and
  provider ok; go test -count=1 of gui, plugin, provider ok, gateway
  ok but #7117's TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes;
  site node --test 135 pass, 0 fail.
- New tests on Windows (win-run): gateway, provider, plugin, gui ok.

Not tried: a real Kubernetes cluster and kube-proxy (the podman harness
stands in for both); a real OAuth plugin's renewal across two pods (the
plugin test uses a fake vendor); an RWX/NFS volume's locks. A stream
that began before SIGTERM and outlasts the drain's 20s still ends with
the old pod. Pods exit 2 on SIGTERM as pid 1 (before this change too).
2026-11-19 16:20:34 +08:00

138 lines
4.3 KiB
Go

package gateway
import (
"context"
"errors"
"io/fs"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/filelock"
)
// The magpie serving the gateway does work no other magpie on its config
// folder may do at the same time: it renews the saved sign-ins as they
// come due, checks accounts in, moves retiring subscriptions, updates the
// plugins and the rest of what ListenAndServe starts after binding
// (servingWork, WhileServing). On one computer the gateway's port made
// that one magpie: a second couldn't bind it, and a handover (handover.go)
// ends the first one's work before the next serves. Two Kubernetes pods
// on one volume each bind a port of their own, so in a rolling update the
// new pod and the old one both served, and both did that work
// (@justforlxz on X asked for a RollingUpdate with no request dropped).
//
// So the work is held to whichever magpie holds servingLock, a lock the
// system keeps on a file in the config folder: a gateway that finds it
// held answers requests at once, as any magpie may (each refresh and each
// file change is locked across processes: filelock, host.js lockRenew),
// and starts the work once the other lets go, as its context ends (a
// SIGTERM's drain, a quit, a handover) or the process does. A file system
// that has no locks is read as no other magpie, as before there was one.
// servingLockFile is the lock's file in the config folder.
const servingLockFile = "gateway.serving.lock"
// servingRetry is how often a gateway waiting for the lock asks again; a
// var so tests can shorten it.
var servingRetry = time.Second
func servingLockPath() string { return filepath.Join(appdir.Config(), servingLockFile) }
// serving is a gateway's hold on the lock: release lets it go, once.
type serving struct {
mu sync.Mutex
f *os.File
released bool
}
// release lets the lock go; a gateway still waiting for it stops.
func (h *serving) release() {
h.mu.Lock()
defer h.mu.Unlock()
h.released = true
if h.f != nil {
filelock.Unlock(h.f)
h.f.Close()
h.f = nil
}
}
// take tries the lock once: held says this gateway may do the work now
// (it holds the lock, or the file system has none), done that it never
// will (released already, or no file to lock: a config folder that can't
// be made has nothing to do the work on either).
func (h *serving) take(path string) (held, done bool) {
h.mu.Lock()
defer h.mu.Unlock()
if h.released {
return false, true
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
if errors.Is(err, fs.ErrNotExist) {
os.MkdirAll(filepath.Dir(path), 0o700)
f, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
}
if err != nil {
log.Printf("gateway: can't open %s (%v): doing the serving magpie's work without it", path, err)
return true, false
}
got, err := filelock.TryLock(f)
if err != nil {
// a file system without locks (an NFS volume with no lockd): as
// before there was a lock
f.Close()
log.Printf("gateway: %s can't be locked here (%v): doing the serving magpie's work without it; run one magpie on this folder at a time", path, err)
return true, false
}
if !got {
f.Close()
return false, false
}
h.f = f
return true, false
}
// holdServing runs work once this gateway holds the serving lock: at once
// when no other magpie holds it, else when that one lets go, never once
// ctx has ended. The lock is let go by the returned release, which the
// gateway calls as its context ends.
func holdServing(ctx context.Context, path string, work func()) (release func()) {
h := &serving{}
if held, done := h.take(path); held || done {
if held {
work()
}
return h.release
}
log.Printf("gateway: another magpie serves from %s (a rolling update's old pod, or another instance): this one answers requests now, and renews sign-ins, checks in and updates plugins once that one ends", filepath.Dir(path))
go func() {
t := time.NewTicker(servingRetry)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
held, done := h.take(path)
if done {
return
}
if held {
if ctx.Err() != nil {
h.release()
return
}
log.Printf("gateway: the other magpie on %s let go: this one does its work now", filepath.Dir(path))
work()
return
}
}
}()
return h.release
}