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 on2926b7bef): 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 on6e5882109), 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).
This commit is contained in:
+16
-3
@@ -3870,9 +3870,22 @@ magpie to save its state after, and 7s elsewhere, inside `docker stop`'s
|
||||
-t`, Compose's `stop_grace_period`) for longer turns. Ctrl+C and SIGHUP still
|
||||
end it at once. In Kubernetes, probe readiness with
|
||||
`exec: {command: [/magpie, healthcheck]}`: an `httpGet` probe comes from
|
||||
outside the container and would need a gateway key. Run one magpie per
|
||||
`/config` volume, with `strategy: Recreate`: the magpie serving keeps the
|
||||
saved sign-ins renewed, and two pods on one volume would both renew them.
|
||||
outside the container and would need a gateway key.
|
||||
|
||||
A rolling update (`maxSurge: 1`, `maxUnavailable: 0`) overlaps the new pod
|
||||
with the old one on one `/config` volume and drops nothing: both answer
|
||||
requests, and each sign-in renewal and saved file is locked across them
|
||||
(flock, and host.js's renewal locks, which name the pod beside the pid since
|
||||
pods share pid numbers). The work only one magpie may do, what
|
||||
`ListenAndServe` starts after binding (renewing saved sign-ins, check-ins,
|
||||
retiring moves, plugin and Bun updates, `WhileServing`), runs only in the
|
||||
magpie holding `gateway.serving.lock` in the config folder: the old pod
|
||||
until its gateway ends, then the new one, which asks each second. A
|
||||
ReadWriteOnce volume needs the new pod on the old one's node, so the
|
||||
example Deployment in the Docker page has a required `podAffinity` on its
|
||||
own label with `topologyKey: kubernetes.io/hostname`. A pod on a version
|
||||
before v0.1.4526 doesn't take the lock: update from it once with
|
||||
`strategy: Recreate`.
|
||||
|
||||
#### NAS with agents on other machines
|
||||
|
||||
|
||||
+59
-50
@@ -813,8 +813,9 @@ func keepRecent(ring []Call, c Call) []Call {
|
||||
}
|
||||
|
||||
// WhileServing is work only the magpie serving the gateway does, begun
|
||||
// once it is bound and ended with it: one of the magpies running, never
|
||||
// two at once.
|
||||
// once it is bound and holds the serving lock (serving.go), and ended with
|
||||
// it: one of the magpies on a config folder, never two at once, two
|
||||
// Kubernetes pods on one volume included.
|
||||
var WhileServing []func(context.Context)
|
||||
|
||||
// ListenAndServe runs the gateway until ctx ends, and returns once the
|
||||
@@ -908,51 +909,60 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
go func() { defer close(pruned); keepHubPruned(freshCtx) }()
|
||||
defer func() { stopFresh(); <-pruned }()
|
||||
srv := &http.Server{Handler: s.closesWhenHandedOff(s.Front()), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute, ConnState: s.unread.note}
|
||||
// the magpie serving the gateway, and only it, keeps the saved accounts
|
||||
// signed in, so two never refresh one sign-in at once
|
||||
go provider.KeepLoginsAlive(ctx)
|
||||
// and tells the request hooks of an account to sign in again
|
||||
go keepHooksToldOfSignIns(ctx)
|
||||
// and signs Codex and Claude Code in to their next account when the
|
||||
// one they are on is spent
|
||||
go provider.KeepOnAnAccountWithRoom(ctx)
|
||||
// and has the Codex app read its provider again as magpie becomes it
|
||||
// for a used-up ChatGPT account, and after (its Send greys otherwise)
|
||||
go provider.KeepCodexAppOnItsProvider(ctx, s.CodexBusy)
|
||||
// and, when settings say to, starts its accounts' next windows as the last reset
|
||||
go provider.KeepCodexWindowsWarm(ctx)
|
||||
go provider.KeepClaudeWindowsWarm(ctx, warmClaude)
|
||||
// and spends a Codex reset about to run out unused, for the accounts
|
||||
// that let it
|
||||
go provider.KeepResetsFromRunningOut(ctx)
|
||||
// and checks the WorkBuddy accounts in for the day's credits
|
||||
go provider.KeepWorkBuddyCheckedIn(ctx)
|
||||
// and the Trae CN accounts (#694), and the MiniMax Code ones (#811)
|
||||
go provider.KeepTraeCheckedIn(ctx)
|
||||
go provider.KeepMiniMaxCheckedIn(ctx)
|
||||
// and the Qoder ones' daily credits
|
||||
go provider.KeepQoderCheckedIn(ctx)
|
||||
// and the accounts of the plugins that check in themselves
|
||||
go provider.KeepPluginsCheckedIn(ctx)
|
||||
// and counts the calls those plugins' accounts made outside magpie
|
||||
// (Cursor's editor and cursor-agent) on the Usage page
|
||||
go usage.KeepOutsideCallsRead(ctx)
|
||||
// and moves the built-in subscriptions being retired onto their plugins
|
||||
go provider.KeepRetiringMoved(ctx)
|
||||
// and fetches the partner list every hour, asked for or not
|
||||
go provider.KeepPartnersFresh(ctx)
|
||||
go provider.KeepPluginsListed(ctx) // models a plugin's vendor drops or adds, while magpie runs
|
||||
// and renews the plugins' sign-ins as they come due, used or not (#5080)
|
||||
go provider.KeepPluginsSignedIn(ctx)
|
||||
// and those a signed-in account's vendor adds (a ChatGPT plan's new GPT)
|
||||
go provider.KeepAccountsListed(ctx)
|
||||
// and fetches the lists of the providers the user asked to keep fresh (#2135)
|
||||
go provider.KeepListsFresh(ctx)
|
||||
// and follows a Remote magpie's list as it changes there (KaCli)
|
||||
go provider.KeepRemoteListsFollowed(ctx)
|
||||
// and keeps the community's plugins up to date, noting others' updates, and the Bun they run on
|
||||
go plugin.KeepUpdated(ctx)
|
||||
go plugin.KeepBunUpdated(ctx)
|
||||
// what the magpie serving the gateway does, and only it: at once, or
|
||||
// once another magpie on this config folder lets go of it (serving.go:
|
||||
// a Kubernetes rolling update's old pod, draining)
|
||||
releaseServing := holdServing(ctx, servingLockPath(), func() {
|
||||
// the magpie serving the gateway, and only it, keeps the saved accounts
|
||||
// signed in, so two never refresh one sign-in at once
|
||||
go provider.KeepLoginsAlive(ctx)
|
||||
// and tells the request hooks of an account to sign in again
|
||||
go keepHooksToldOfSignIns(ctx)
|
||||
// and signs Codex and Claude Code in to their next account when the
|
||||
// one they are on is spent
|
||||
go provider.KeepOnAnAccountWithRoom(ctx)
|
||||
// and has the Codex app read its provider again as magpie becomes it
|
||||
// for a used-up ChatGPT account, and after (its Send greys otherwise)
|
||||
go provider.KeepCodexAppOnItsProvider(ctx, s.CodexBusy)
|
||||
// and, when settings say to, starts its accounts' next windows as the last reset
|
||||
go provider.KeepCodexWindowsWarm(ctx)
|
||||
go provider.KeepClaudeWindowsWarm(ctx, warmClaude)
|
||||
// and spends a Codex reset about to run out unused, for the accounts
|
||||
// that let it
|
||||
go provider.KeepResetsFromRunningOut(ctx)
|
||||
// and checks the WorkBuddy accounts in for the day's credits
|
||||
go provider.KeepWorkBuddyCheckedIn(ctx)
|
||||
// and the Trae CN accounts (#694), and the MiniMax Code ones (#811)
|
||||
go provider.KeepTraeCheckedIn(ctx)
|
||||
go provider.KeepMiniMaxCheckedIn(ctx)
|
||||
// and the Qoder ones' daily credits
|
||||
go provider.KeepQoderCheckedIn(ctx)
|
||||
// and the accounts of the plugins that check in themselves
|
||||
go provider.KeepPluginsCheckedIn(ctx)
|
||||
// and counts the calls those plugins' accounts made outside magpie
|
||||
// (Cursor's editor and cursor-agent) on the Usage page
|
||||
go usage.KeepOutsideCallsRead(ctx)
|
||||
// and moves the built-in subscriptions being retired onto their plugins
|
||||
go provider.KeepRetiringMoved(ctx)
|
||||
// and fetches the partner list every hour, asked for or not
|
||||
go provider.KeepPartnersFresh(ctx)
|
||||
go provider.KeepPluginsListed(ctx) // models a plugin's vendor drops or adds, while magpie runs
|
||||
// and renews the plugins' sign-ins as they come due, used or not (#5080)
|
||||
go provider.KeepPluginsSignedIn(ctx)
|
||||
// and those a signed-in account's vendor adds (a ChatGPT plan's new GPT)
|
||||
go provider.KeepAccountsListed(ctx)
|
||||
// and fetches the lists of the providers the user asked to keep fresh (#2135)
|
||||
go provider.KeepListsFresh(ctx)
|
||||
// and follows a Remote magpie's list as it changes there (KaCli)
|
||||
go provider.KeepRemoteListsFollowed(ctx)
|
||||
// and keeps the community's plugins up to date, noting others' updates, and the Bun they run on
|
||||
go plugin.KeepUpdated(ctx)
|
||||
go plugin.KeepBunUpdated(ctx)
|
||||
for _, f := range WhileServing {
|
||||
go f(ctx)
|
||||
}
|
||||
})
|
||||
defer releaseServing()
|
||||
// and keeps macOS from App Napping the process the agents wait on (#6261)
|
||||
defer awake.NoNap()()
|
||||
// and, when settings say to, keeps the computer awake while agents work
|
||||
@@ -968,9 +978,6 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
b := s.Busy()
|
||||
return awake.State{Busy: b.Any(), Last: b.Last}
|
||||
})
|
||||
for _, f := range WhileServing {
|
||||
go f(ctx)
|
||||
}
|
||||
// and, on Windows, serves WSL distros under NAT at Windows' address on
|
||||
// their network (wsl.go)
|
||||
go s.serveWSL(ctx, srv)
|
||||
@@ -978,6 +985,8 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
go func() {
|
||||
defer close(drained)
|
||||
<-ctx.Done()
|
||||
// the work only it does ended with ctx: the next magpie takes it
|
||||
releaseServing()
|
||||
s.endStreams()
|
||||
c, cancel := context.WithTimeout(context.Background(), s.drainFor())
|
||||
defer cancel()
|
||||
|
||||
@@ -178,3 +178,37 @@ func TestDrainEndsAtItsGrace(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A rolling update's old pod keeps the connections agents kept alive to
|
||||
// it after the Service sends new ones elsewhere, and its end closed each
|
||||
// one after its reply with no word of it, so an agent's next request on it
|
||||
// went out on a closed connection: a broken pipe, once for each, in a real
|
||||
// rollout of three pods. Once draining, every reply says Connection:
|
||||
// close, so that next request dials the Service again.
|
||||
func TestDrainingRepliesCloseTheirConnection(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:0")
|
||||
s := New()
|
||||
stop, done := listening(t, s)
|
||||
defer func() { stop(); <-done }()
|
||||
s.lnMu.Lock()
|
||||
addr := s.ln.Addr().String()
|
||||
s.lnMu.Unlock()
|
||||
get := func() *http.Response {
|
||||
t.Helper()
|
||||
r, err := http.Get("http://" + addr + "/v1/models")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
return r
|
||||
}
|
||||
if r := get(); r.Close {
|
||||
t.Fatal("a reply before the drain closed its connection")
|
||||
}
|
||||
s.Drain(time.Minute)
|
||||
if r := get(); !r.Close {
|
||||
t.Fatalf("a draining gateway's reply (%d) kept its connection alive", r.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,12 +182,16 @@ func (s *Server) stopAccepting() {
|
||||
}
|
||||
|
||||
// closesWhenHandedOff has each reply the gateway gives once it takes no
|
||||
// connection (stopAccepting) close its connection, so the agent's next
|
||||
// request dials the magpie serving the port after this one rather than
|
||||
// waiting on a connection this one's end closes (unreadConns).
|
||||
// connection (stopAccepting), or once it drains (a SIGTERM, Drain), close
|
||||
// its connection, so the agent's next request dials the magpie serving the
|
||||
// port after this one (the Service's next pod) rather than going out on a
|
||||
// connection this one's end closes. A rolling update's old pod keeps the
|
||||
// connections agents kept alive to it, and its end closed each one after
|
||||
// the reply under way, which said nothing of it: the agent's next request
|
||||
// on it was refused (a broken pipe), once for each such connection.
|
||||
func (s *Server) closesWhenHandedOff(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.notAccepting.Load() {
|
||||
if s.notAccepting.Load() || s.draining.Load() {
|
||||
w.Header().Set("Connection", "close")
|
||||
}
|
||||
h.ServeHTTP(w, r)
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
@@ -30,8 +29,15 @@ type Listening struct {
|
||||
Serves string `json:"serves"`
|
||||
Version string `json:"version"`
|
||||
Started string `json:"started"`
|
||||
// Host is the machine's name, a pod's in Kubernetes: two pods on one
|
||||
// volume (a rolling update) each run magpie as pid 1, so the pid alone
|
||||
// doesn't say the file is this process's
|
||||
Host string `json:"host,omitempty"`
|
||||
}
|
||||
|
||||
// podName is this machine's (or pod's) name, "" when it can't be read.
|
||||
var podName = func() string { h, _ := os.Hostname(); return h }()
|
||||
|
||||
// ListeningPath is where the file is.
|
||||
func ListeningPath() string { return filepath.Join(appdir.Config(), ListeningFile) }
|
||||
|
||||
@@ -44,7 +50,7 @@ func recordListening(addr net.Addr) {
|
||||
if addr == nil {
|
||||
return
|
||||
}
|
||||
b, err := json.Marshal(Listening{Addr: addr.String(), Pid: os.Getpid(), Serves: Serves, Version: Version, Started: processStart.UTC().Format(time.RFC3339)})
|
||||
b, err := json.Marshal(ownListening(addr.String()))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -52,19 +58,35 @@ func recordListening(addr net.Addr) {
|
||||
if os.MkdirAll(filepath.Dir(p), 0o700) != nil {
|
||||
return
|
||||
}
|
||||
tmp := p + "." + strconv.Itoa(os.Getpid()) + ".tmp"
|
||||
if os.WriteFile(tmp, b, 0o600) != nil {
|
||||
// a temp file of its own: named by the pid, another pod's magpie, pid
|
||||
// 1 too, wrote the same one meanwhile
|
||||
f, err := os.CreateTemp(filepath.Dir(p), ListeningFile+".*.tmp")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if os.Rename(tmp, p) != nil {
|
||||
tmp := f.Name()
|
||||
_, werr := f.Write(b)
|
||||
if cerr := f.Close(); werr != nil || cerr != nil || os.Chmod(tmp, 0o600) != nil || os.Rename(tmp, p) != nil {
|
||||
os.Remove(tmp)
|
||||
}
|
||||
}
|
||||
|
||||
// ownListening is the file's content for this process listening on addr.
|
||||
func ownListening(addr string) Listening {
|
||||
return Listening{Addr: addr, Pid: os.Getpid(), Serves: Serves, Version: Version, Started: processStart.UTC().Format(time.RFC3339), Host: podName}
|
||||
}
|
||||
|
||||
// mine says l was written by this process: its pid, start and machine.
|
||||
// One from before Host was written has none, and is judged by the rest.
|
||||
func (l Listening) mine() bool {
|
||||
return l.Pid == os.Getpid() && l.Started == processStart.UTC().Format(time.RFC3339) && (l.Host == "" || l.Host == podName)
|
||||
}
|
||||
|
||||
// forgetListening removes the file when it is this process's: one that took
|
||||
// the gateway over (handover.go) has written its own by then.
|
||||
// the gateway over (handover.go), or a pod on the same volume, has written
|
||||
// its own by then.
|
||||
func forgetListening() {
|
||||
if l, ok := ReadListening(); ok && l.Pid == os.Getpid() {
|
||||
if l, ok := ReadListening(); ok && l.mine() {
|
||||
os.Remove(ListeningPath())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -108,3 +110,35 @@ func TestRelistenMovesTheNote(t *testing.T) {
|
||||
t.Errorf("after moving: %+v %v, want %s", l, ok, to)
|
||||
}
|
||||
}
|
||||
|
||||
// Two pods on one volume (a rolling update) both run magpie as pid 1, so
|
||||
// the old pod's end removed the gateway.json the new pod had written over
|
||||
// its own. Only this process's own file, by pid, start and machine, is
|
||||
// removed.
|
||||
func TestForgetListeningKeepsAnotherPods(t *testing.T) {
|
||||
fresh(t)
|
||||
other := ownListening("10.0.0.7:3425")
|
||||
other.Host = "magpie-7d9f-new"
|
||||
b, _ := json.Marshal(other)
|
||||
os.MkdirAll(filepath.Dir(ListeningPath()), 0o700)
|
||||
if err := os.WriteFile(ListeningPath(), b, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forgetListening()
|
||||
if _, ok := ReadListening(); !ok {
|
||||
t.Fatal("another pod's gateway.json, with this pid, was removed")
|
||||
}
|
||||
other.Host, other.Started = podName, "2001-01-01T00:00:00Z"
|
||||
b, _ = json.Marshal(other)
|
||||
os.WriteFile(ListeningPath(), b, 0o600)
|
||||
forgetListening()
|
||||
if _, ok := ReadListening(); !ok {
|
||||
t.Fatal("a gateway.json of another start, with this pid, was removed")
|
||||
}
|
||||
b, _ = json.Marshal(ownListening("127.0.0.1:3425"))
|
||||
os.WriteFile(ListeningPath(), b, 0o600)
|
||||
forgetListening()
|
||||
if _, ok := ReadListening(); ok {
|
||||
t.Fatal("this process's own gateway.json was kept")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
)
|
||||
|
||||
// A Kubernetes rolling update runs the new pod beside the old one on one
|
||||
// volume, each gateway on a port of its own. The new one answers requests
|
||||
// at once, but the work only the serving magpie does (renewing sign-ins,
|
||||
// check-ins, WhileServing) waits until the old one's gateway ends: two
|
||||
// never do it at once. Without the serving lock both did.
|
||||
func TestServingWorkWaitsForTheOtherMagpie(t *testing.T) {
|
||||
fresh(t)
|
||||
oldRetry := servingRetry
|
||||
servingRetry = 10 * time.Millisecond
|
||||
t.Cleanup(func() { servingRetry = oldRetry })
|
||||
var working atomic.Int32
|
||||
var most atomic.Int32
|
||||
var began atomic.Int32
|
||||
oldWork := WhileServing
|
||||
WhileServing = append([]func(context.Context){func(ctx context.Context) {
|
||||
began.Add(1)
|
||||
n := working.Add(1)
|
||||
for m := most.Load(); n > m && !most.CompareAndSwap(m, n); m = most.Load() {
|
||||
}
|
||||
<-ctx.Done()
|
||||
working.Add(-1)
|
||||
}}, oldWork...)
|
||||
t.Cleanup(func() { WhileServing = oldWork })
|
||||
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:0")
|
||||
old := New()
|
||||
stopOld, oldDone := listening(t, old)
|
||||
defer stopOld()
|
||||
waitFor(t, "the first gateway's work to begin", func() bool { return began.Load() == 1 })
|
||||
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:0")
|
||||
next := New()
|
||||
stopNext, nextDone := listening(t, next)
|
||||
defer stopNext()
|
||||
next.lnMu.Lock()
|
||||
addr := next.ln.Addr().String()
|
||||
next.lnMu.Unlock()
|
||||
// the new one answers while the old one serves
|
||||
resp, err := http.Get("http://" + addr + "/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
t.Fatalf("the second gateway answered %d while the first served", resp.StatusCode)
|
||||
}
|
||||
// many retries' worth: its work hasn't begun
|
||||
time.Sleep(30 * servingRetry)
|
||||
if n := began.Load(); n != 1 {
|
||||
t.Fatalf("the serving work began %d times with the first gateway still serving", n)
|
||||
}
|
||||
|
||||
stopOld()
|
||||
if err := <-oldDone; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, "the second gateway's work to begin once the first ended", func() bool { return began.Load() == 2 })
|
||||
if m := most.Load(); m != 1 {
|
||||
t.Fatalf("the serving work ran in %d gateways at once", m)
|
||||
}
|
||||
stopNext()
|
||||
if err := <-nextDone; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A gateway that ends while it waits for the lock never does the work,
|
||||
// and lets go of nothing it doesn't hold.
|
||||
func TestServingWaitEndsWithItsGateway(t *testing.T) {
|
||||
fresh(t)
|
||||
oldRetry := servingRetry
|
||||
servingRetry = 10 * time.Millisecond
|
||||
t.Cleanup(func() { servingRetry = oldRetry })
|
||||
unlock, held := filelock.Lock(servingLockPath(), 0)
|
||||
if !held {
|
||||
t.Skip("no file locks here")
|
||||
}
|
||||
var began atomic.Int32
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
release := holdServing(ctx, servingLockPath(), func() { began.Add(1) })
|
||||
time.Sleep(10 * servingRetry)
|
||||
cancel()
|
||||
release()
|
||||
unlock()
|
||||
time.Sleep(10 * servingRetry)
|
||||
if n := began.Load(); n != 0 {
|
||||
t.Fatalf("the work began %d times in a gateway that ended waiting", n)
|
||||
}
|
||||
// and the lock is free for the next
|
||||
again := holdServing(context.Background(), servingLockPath(), func() { began.Add(1) })
|
||||
defer again()
|
||||
if n := began.Load(); n != 1 {
|
||||
t.Fatalf("a free lock: the work began %d times, want at once", n)
|
||||
}
|
||||
}
|
||||
+15
-1
@@ -407,7 +407,21 @@ func LANAddrs() []string {
|
||||
// routes, judged by the gateway (onePort) and never by box, and the page
|
||||
// and its API behind the allow list and the key, or box's sign-in.
|
||||
func webServed(port, key string, keep time.Duration, box boxSignIn, page http.Handler) http.Handler {
|
||||
return onePort(gateway.AllowGuard(gateway.ClientCertGuard(webHandler(port, key, keep, box, page))))
|
||||
return closesWhenDraining(onePort(gateway.AllowGuard(gateway.ClientCertGuard(webHandler(port, key, keep, box, page)))))
|
||||
}
|
||||
|
||||
// closesWhenDraining has each reply the page port gives while this
|
||||
// process's gateway drains (a SIGTERM) close its connection, as the
|
||||
// gateway's own do: an agent that sends /v1 here and kept its connection
|
||||
// alive then dials the Service's next pod for its next request, rather
|
||||
// than sending it on a connection the drain's end closes.
|
||||
func closesWhenDraining(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if gw := served.Load(); gw != nil && gw.Draining() {
|
||||
w.Header().Set("Connection", "close")
|
||||
}
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// webHandler is what `magpie web` on port serves: the page and its API
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
// magpie web's page port serves /v1 too, and a rolling update's old pod
|
||||
// kept the connections agents kept alive to it: once its gateway drains,
|
||||
// each of the page port's replies closes its connection, as the gateway's
|
||||
// own do, so the agent's next request dials the Service's next pod.
|
||||
func TestPagePortClosesWhileDraining(t *testing.T) {
|
||||
prev := served.Load()
|
||||
t.Cleanup(func() { served.Store(prev) })
|
||||
gw := gateway.New()
|
||||
served.Store(gw)
|
||||
h := closesWhenDraining(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
||||
ask := func() string {
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", nil))
|
||||
return rec.Header().Get("Connection")
|
||||
}
|
||||
if c := ask(); c != "" {
|
||||
t.Fatalf("before the drain: Connection %q", c)
|
||||
}
|
||||
gw.Drain(time.Minute)
|
||||
if c := ask(); c != "close" {
|
||||
t.Fatalf("draining: Connection %q, want close", c)
|
||||
}
|
||||
}
|
||||
+26
-5
@@ -31,6 +31,7 @@ import dns from "node:dns"
|
||||
import fs from "node:fs"
|
||||
import http2 from "node:http2"
|
||||
import net from "node:net"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import readline from "node:readline"
|
||||
import { Duplex } from "node:stream"
|
||||
@@ -1033,7 +1034,8 @@ function authCopy(key) {
|
||||
// the two left plugin-auth.json all zero (#1505). A write or flush that
|
||||
// fails leaves p as it was.
|
||||
async function writeDurable(p, data) {
|
||||
const tmp = p + ".tmp-" + process.pid
|
||||
// named past the pid: another pod's host on the volume can have this one's
|
||||
const tmp = p + ".tmp-" + process.pid + "-" + Math.random().toString(36).slice(2, 10)
|
||||
try {
|
||||
const f = fs.openSync(tmp, "w", 0o600)
|
||||
try {
|
||||
@@ -3119,9 +3121,25 @@ function keepsAlive(a) {
|
||||
// account's beside plugin-auth.json, held across the plugin's refresh,
|
||||
// and the sign-in is read again under it. The lock names its holder's pid:
|
||||
// one whose holder is gone is taken over at once, and one held longer
|
||||
// than RENEW_LOCK_STALE by anyone.
|
||||
// than RENEW_LOCK_STALE by anyone. A pid is this host's to ask about only
|
||||
// in its own pid namespace: two Kubernetes pods on one volume (a rolling
|
||||
// update's old pod and new one) each run magpie as pid 1 and a host as a
|
||||
// low pid of their own, and a pod asking after the other's pid asked after
|
||||
// a process of its own, found none, and took a lock the other held: both
|
||||
// spent one refresh token. So a lock names where its pid is (renewHost), and
|
||||
// one from elsewhere is judged by its age alone.
|
||||
const RENEW_LOCK_STALE = 60 * 1000
|
||||
|
||||
// renewHost is where this host's pid means something: the machine's (or
|
||||
// pod's) name and, on Linux, its pid namespace.
|
||||
const renewHost = (() => {
|
||||
let ns = ""
|
||||
try {
|
||||
ns = fs.readlinkSync("/proc/self/ns/pid")
|
||||
} catch {}
|
||||
return `${os.hostname()} ${ns}`.trim()
|
||||
})()
|
||||
|
||||
function alive(pid) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
@@ -3133,7 +3151,7 @@ function alive(pid) {
|
||||
|
||||
async function lockRenew(key) {
|
||||
const lock = `${authPath}.renew-${createHash("sha256").update(key).digest("hex").slice(0, 16)}.lock`
|
||||
const me = JSON.stringify({ pid: process.pid, at: Date.now(), n: randomUUID() })
|
||||
const me = JSON.stringify({ pid: process.pid, host: renewHost, at: Date.now(), n: randomUUID() })
|
||||
fs.mkdirSync(path.dirname(authPath), { recursive: true })
|
||||
for (let start = Date.now(), wait = 10; ; wait = Math.min(wait * 2, 500)) {
|
||||
try {
|
||||
@@ -3155,8 +3173,11 @@ async function lockRenew(key) {
|
||||
h = JSON.parse(raw)
|
||||
} catch {}
|
||||
// a holder gone, or one too long at it; a file not written yet is
|
||||
// judged by its age
|
||||
const stale = Number.isInteger(h?.pid) ? !alive(h.pid) || Date.now() - h.at > RENEW_LOCK_STALE : age > RENEW_LOCK_STALE
|
||||
// judged by its age, and one whose pid is another pod's or machine's
|
||||
// by its own time (a host before renewHost names none: its pid is asked
|
||||
// after here, as it was)
|
||||
const here = h?.host === undefined || h.host === renewHost
|
||||
const stale = Number.isInteger(h?.pid) ? (here && !alive(h.pid)) || Date.now() - h.at > RENEW_LOCK_STALE : age > RENEW_LOCK_STALE
|
||||
if (raw !== null && (stale || Date.now() - start > 2 * RENEW_LOCK_STALE)) {
|
||||
try {
|
||||
if (fs.readFileSync(lock, "utf8") === raw) fs.unlinkSync(lock)
|
||||
|
||||
@@ -337,3 +337,60 @@ func TestRenewLockOfDeadHostAndRefusal(t *testing.T) {
|
||||
t.Fatalf("requests went with %v, want the other magpie's token last", auths)
|
||||
}
|
||||
}
|
||||
|
||||
// Two Kubernetes pods on one volume (a rolling update's old pod and new
|
||||
// one) each have pids of their own namespace, so a renewal lock the other
|
||||
// pod's host holds names a pid that is no process here. It was taken over
|
||||
// as a dead host's, and both pods spent one refresh token. A lock from
|
||||
// another host is waited for (up to its age) instead: no exchange is made
|
||||
// while it is held, and once the other pod saved its renewal and let go,
|
||||
// this one sends that token without spending its own.
|
||||
func TestRenewLockOfAnotherPodIsWaitedFor(t *testing.T) {
|
||||
sandbox(t)
|
||||
v := newRaceVendor(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
defer cancel()
|
||||
key := raceAccount(t, ctx, "r1")
|
||||
|
||||
dead := exec.Command(os.Args[0], "-test.run=^$")
|
||||
if err := dead.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
lock := AuthPath() + ".renew-" + hex.EncodeToString(sum[:])[:16] + ".lock"
|
||||
held := fmt.Sprintf(`{"pid":%d,"host":"magpie-7d9f-old pid:[4026532001]","at":%d}`, dead.Process.Pid, time.Now().UnixMilli())
|
||||
if err := os.WriteFile(lock, []byte(held), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sent := make(chan error, 1)
|
||||
go func() { sent <- raceSend(ctx, key) }()
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
if exchanges, _ := v.seen(); len(exchanges) != 0 {
|
||||
t.Fatalf("exchanged %v while another pod's host held the renewal lock", exchanges)
|
||||
}
|
||||
// the other pod's renewal: saved, then the lock let go
|
||||
var all map[string]map[string]any
|
||||
raw, err := os.ReadFile(AuthPath())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
json.Unmarshal(raw, &all)
|
||||
all[key]["access"], all[key]["refresh"] = "a-other-pod", "r-other-pod"
|
||||
all[key]["expires"] = time.Now().Add(time.Hour).UnixMilli()
|
||||
raw, _ = json.Marshal(all)
|
||||
if err := os.WriteFile(AuthPath(), raw, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.Remove(lock)
|
||||
if err := <-sent; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
Told()
|
||||
exchanges, auths := v.seen()
|
||||
if len(exchanges) != 0 {
|
||||
t.Errorf("exchanged %v: the other pod's renewal was spent again", exchanges)
|
||||
}
|
||||
if len(auths) != 1 || auths[0] != "Bearer a-other-pod" {
|
||||
t.Errorf("requests went with %v, want the other pod's token", auths)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ package provider
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
@@ -145,12 +146,22 @@ var claudeRunWait = 90 * time.Second
|
||||
|
||||
var claudeRunSeq atomic.Int64
|
||||
|
||||
// runMarkTag tells this process's run marks from another's with its pid.
|
||||
var runMarkTag = func() string {
|
||||
b := make([]byte, 4)
|
||||
rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}()
|
||||
|
||||
// claudeRunMarks matches the lock files of the runs in user's directory.
|
||||
func claudeRunMarks(user string) string { return claudeAccountDir(user) + ".run-*.lock" }
|
||||
|
||||
// markClaudeRun holds a lock file of this run's own, released as it ends.
|
||||
func markClaudeRun(user string) (release func()) {
|
||||
path := fmt.Sprintf("%s.run-%d-%d.lock", claudeAccountDir(user), os.Getpid(), claudeRunSeq.Add(1))
|
||||
// named past the pid and the count: another pod's magpie on the same
|
||||
// volume has pid 1 too, and would take this one's name, fail its lock
|
||||
// and remove the file this run holds
|
||||
path := fmt.Sprintf("%s.run-%d-%d-%s.lock", claudeAccountDir(user), os.Getpid(), claudeRunSeq.Add(1), runMarkTag)
|
||||
unlock, held := filelock.Lock(path, 0)
|
||||
if !held {
|
||||
_ = os.Remove(path)
|
||||
|
||||
@@ -512,6 +512,16 @@ func setMigration(id string, f func(m *Migration)) error {
|
||||
return writePrivate(migrationsPath(), append(b, '\n'))
|
||||
}
|
||||
|
||||
// movesHost is the machine's (or pod's) name, which a moves lock names
|
||||
// beside its pid.
|
||||
var movesHost = func() string {
|
||||
h, _ := os.Hostname()
|
||||
if h == "" || strings.ContainsAny(h, " \t\n") {
|
||||
return "-"
|
||||
}
|
||||
return h
|
||||
}()
|
||||
|
||||
// lockMoves keeps two magpies (the app and a CLI, a dev build beside a
|
||||
// release) from moving at once.
|
||||
func lockMoves() (func(), error) {
|
||||
@@ -522,14 +532,18 @@ func lockMoves() (func(), error) {
|
||||
for range 2 {
|
||||
f, err := os.OpenFile(p, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
||||
if err == nil {
|
||||
fmt.Fprint(f, os.Getpid())
|
||||
fmt.Fprint(f, os.Getpid(), " ", movesHost)
|
||||
f.Close()
|
||||
return func() { os.Remove(p) }, nil
|
||||
}
|
||||
// one left by a magpie that died moving (killed, or stopped
|
||||
// mid-move) holds nothing
|
||||
// mid-move) holds nothing. Its pid is asked after only where it
|
||||
// is one: another pod's magpie on the same volume has pids of
|
||||
// its own namespace, so its lock is judged by its age alone.
|
||||
if b, rerr := os.ReadFile(p); rerr == nil {
|
||||
if pid, perr := strconv.Atoi(strings.TrimSpace(string(b))); perr == nil && pid != os.Getpid() && !update.Alive(pid) {
|
||||
f := strings.Fields(string(b))
|
||||
here := len(f) == 1 || len(f) == 2 && f[1] == movesHost
|
||||
if pid, perr := strconv.Atoi(strings.Join(f[:min(len(f), 1)], "")); perr == nil && here && pid != os.Getpid() && !update.Alive(pid) {
|
||||
os.Remove(p)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -122,3 +122,32 @@ func TestMoveLockOfDeadMagpie(t *testing.T) {
|
||||
}
|
||||
unlock()
|
||||
}
|
||||
|
||||
// A move's lock written by another pod's magpie on the same volume (a
|
||||
// Kubernetes rolling update) names a pid of that pod's namespace, one no
|
||||
// process here has: it is held while it is fresh, not taken as a dead
|
||||
// magpie's, and a stale one (a quarter of an hour) is taken.
|
||||
func TestMoveLockOfAnotherPod(t *testing.T) {
|
||||
claudeHome(t)
|
||||
gone := exec.Command("true")
|
||||
if err := gone.Run(); err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
p := migrationsPath() + ".lock"
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(p, []byte(strconv.Itoa(gone.Process.Pid)+" magpie-7d9f-old"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := lockMoves(); err == nil {
|
||||
t.Fatal("another pod's lock was taken as a dead magpie's")
|
||||
}
|
||||
old := time.Now().Add(-16 * time.Minute)
|
||||
os.Chtimes(p, old, old)
|
||||
unlock, err := lockMoves()
|
||||
if err != nil {
|
||||
t.Fatalf("a stale lock of another pod: %v", err)
|
||||
}
|
||||
unlock()
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ e8f03915aaf12c386bd6254ccfacbe6dc7ae1544e0080bde67ce31b048a50ee0 docs/copilot.h
|
||||
c2795244d9df800736d5be9042a45bca9358800b27521723e9a4f0604e7a8c43 docs/crush.html
|
||||
d042047b8d4e480702a6986c52135154ded05388ff82e63f215d652ea55f0c6e docs/cursor-private-inference.html
|
||||
cf2645267d38d072f0467a02f6888b3a8848b27c3b14fa2461cda904ab07b793 docs/deepseek.html
|
||||
6a7db14989185d62f2a9297cbe4e0f6d2c7811744ee8585f43626243319be2ac docs/docker.html
|
||||
f792584f36b69f91df81db8b7509400cb6277258473581c11638c15ef2c3eacf docs/docker.html
|
||||
0df2e589a2a8d2f0a91344d79ba15eff4a63dbd4d26e9a24601fec9c61a1d90e docs/droid.html
|
||||
4ea324a67bf788a62585120a5685a66c977f1fccd7bf2ca39a4f5f6dae63fa04 docs/ds-bot.html
|
||||
1e11349a9456e75797816776f8f420de351683df7d2aaf09c18688aaf5d781b5 docs/empryo.html
|
||||
@@ -80,7 +80,7 @@ f3b062404993ee53684e2282e28c21af93f13003e7d09a13e0a06efcf36d1634 docs/ja/craft-
|
||||
07f679f11a97fa7e75130c5defef055b1abc142dbd15510b6ae9b67845817944 docs/ja/crush.html
|
||||
478cf1f70d9a9d9730931c785aee1f72e38bc27b62b3c429fed5ef6e97b8b406 docs/ja/cursor-private-inference.html
|
||||
1dce97081a8170168bc329f4f6c5cf555a207a8a90d375cb19de4c7ec9aba488 docs/ja/deepseek.html
|
||||
1c364af181285b3b3c3e8545f45203dd485996bfadbdf788fe994a474d35f0f4 docs/ja/docker.html
|
||||
7525e8f57a909cf2f35bfef871d5b61f3f64c870b63663ddd4af7e3e33e532c8 docs/ja/docker.html
|
||||
e1b20bd4d38845588252a3b083f13517309bea5fbc4c1961f1a9a0291a870a44 docs/ja/droid.html
|
||||
82360502ec915c659a80d388eeb3fe359e68d65a86b5e4dcb46fbbdeefc488c7 docs/ja/ds-bot.html
|
||||
aa1c027a828a9f7cae0297aeb86e8d91759bf2cacb10875e56c1fe49f162a40c docs/ja/empryo.html
|
||||
@@ -279,7 +279,7 @@ abf1ef4b505f95b1b1cb32c79ae311f236c8c67c3474e00fe779359a650238d4 docs/zh/copilo
|
||||
a5b7151d7c21e4bb3f601c0c399d0e5a8de051ec7e342c552fd3883f589b66f4 docs/zh/crush.html
|
||||
939171a143b339969019c6fa2cba7f983cb83220b21e08fcb2e49f958fcb7fd3 docs/zh/cursor-private-inference.html
|
||||
69752603509b92a8c0dcda461b71b1e02e669de2f790f6e1ad50922090971dd2 docs/zh/deepseek.html
|
||||
1158f828c65d9ad0ad2d9792a6bb6b05444fde1ec4909f1b3ea0256133a629fe docs/zh/docker.html
|
||||
c6054685a8cd97ad99e27a200d438a1305a87a1d2bc9b18e2465333a68a542fe docs/zh/docker.html
|
||||
d282d59587baab9e6cdd4c1d36b69b9ceea9e2cd0b49d1537642fd529c7816a8 docs/zh/droid.html
|
||||
e8bc868847eede8bcdf157f13e2508f91c790baee914cb3c8f2b1801bf2c5fc1 docs/zh/ds-bot.html
|
||||
2665b5de3bc00d5a7f34ed318dcecc76cd136479ecd239f2623f76134f826850 docs/zh/empryo.html
|
||||
|
||||
@@ -295,7 +295,10 @@ metadata:
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate <span class="c"># one magpie on /config at a time</span>
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxSurge: 1 <span class="c"># the new pod starts beside the old one</span>
|
||||
maxUnavailable: 0 <span class="c"># the old one ends once the new one is ready</span>
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
@@ -305,6 +308,12 @@ spec:
|
||||
terminationGracePeriodSeconds: 30 <span class="c"># MAGPIE_DRAIN (20s) plus 10s to save</span>
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
affinity:
|
||||
podAffinity: <span class="c"># the new pod on the old one's node, where the ReadWriteOnce volume is</span>
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchLabels: {app: magpie}
|
||||
topologyKey: kubernetes.io/hostname
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
@@ -324,7 +333,8 @@ spec:
|
||||
</div>
|
||||
<p><b>Readiness.</b> Probe with <code>exec</code> and <code>magpie healthcheck</code>, as above: it asks from inside the container, so it needs no key. An <code>httpGet</code> probe comes from outside the container and would need a gateway key.</p>
|
||||
<p><b>Longer turns.</b> An agent’s turn can stream for minutes. Raise <code>MAGPIE_DRAIN</code> and <code>terminationGracePeriodSeconds</code> together, the second 10 seconds above the first: <code>MAGPIE_DRAIN: "300"</code> with <code>terminationGracePeriodSeconds: 310</code>.</p>
|
||||
<p><b>One pod per volume.</b> The magpie serving the gateway keeps the saved sign-ins renewed, and two pods on one <code>/config</code> would both renew them, which can sign an account out. Keep <code>strategy: Recreate</code> (or <code>maxSurge: 0</code>): the old pod finishes its requests and ends before the new one starts, and requests sent in between wait for the new one. A default RollingUpdate with a ReadWriteOnce volume doesn’t overlap safely either: on another node the new pod can’t mount the volume, and the rollout stalls.</p>
|
||||
<p><b>Rolling updates.</b> The new pod serves beside the old one on the same <code>/config</code>, and the Service sends it requests once it is ready; the old pod then drains as above, so no request is dropped. Each sign-in renewal and each saved file is locked across the pods. What only one magpie may do (renewing the saved sign-ins in the background, check-ins, plugin updates) the old pod keeps doing until it ends, and the new pod takes it over within a second. A ReadWriteOnce volume mounts on one node only, so the <code>podAffinity</code> above starts the new pod on the old one's node; with a ReadWriteMany volume, leave it out.</p>
|
||||
<p><b>Updating from a version before v0.1.4526.</b> The old pod doesn't take part in that handover, so the two would both renew sign-ins for the length of the update. Make that one update with <code>strategy: Recreate</code>, then switch to the rolling update above.</p>
|
||||
|
||||
<p style="margin-top:48px">Questions or a setup worth sharing? Ask on <a href="https://discord.gg/vGSnD3ZKQF">Discord</a>. The <a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#docker">reference</a> has the details.</p>
|
||||
</article>
|
||||
|
||||
@@ -295,7 +295,10 @@ metadata:
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate <span class="c"># /config を使う magpie は常に 1 つ</span>
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxSurge: 1 <span class="c"># 新しい Pod を古い Pod の横で起動</span>
|
||||
maxUnavailable: 0 <span class="c"># 新しい Pod の準備後に古い Pod が終了</span>
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
@@ -305,6 +308,12 @@ spec:
|
||||
terminationGracePeriodSeconds: 30 <span class="c"># MAGPIE_DRAIN(20 秒)+保存用の 10 秒</span>
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
affinity:
|
||||
podAffinity: <span class="c"># 新しい Pod を古い Pod と同じノード(ReadWriteOnce ボリュームのある所)に</span>
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchLabels: {app: magpie}
|
||||
topologyKey: kubernetes.io/hostname
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
@@ -324,7 +333,8 @@ spec:
|
||||
</div>
|
||||
<p><b>レディネス。</b>上のように <code>exec</code> で <code>magpie healthcheck</code> を実行します。コンテナ内から問い合わせるのでキーは不要です。<code>httpGet</code> プローブはコンテナの外から来るため、ゲートウェイキーが必要になります。</p>
|
||||
<p><b>長いターン。</b>エージェントのターンは数分間ストリームすることがあります。<code>MAGPIE_DRAIN</code> と <code>terminationGracePeriodSeconds</code> を一緒に上げ、後者を前者より 10 秒長くします:<code>MAGPIE_DRAIN: "300"</code> と <code>terminationGracePeriodSeconds: 310</code>。</p>
|
||||
<p><b>1 つのボリュームに 1 つの Pod。</b>ゲートウェイを提供する magpie が保存済みのサインインを更新し続けます。2 つの Pod が同じ <code>/config</code> を使うと両方が更新し、アカウントがサインアウトされることがあります。<code>strategy: Recreate</code>(または <code>maxSurge: 0</code>)にしてください。古い Pod が処理中のリクエストを終えて終了してから新しい Pod が起動し、その間のリクエストは新しい Pod の準備を待ちます。ReadWriteOnce ボリュームでの既定の RollingUpdate も安全には重なりません。新しい Pod が別ノードだとボリュームをマウントできず、ロールアウトが止まります。</p>
|
||||
<p><b>ローリングアップデート。</b>新しい Pod は古い Pod と同じ <code>/config</code> で並んで動き、準備ができると Service がリクエストを送り始めます。その後古い Pod は上のとおりドレインするので、リクエストは落ちません。サインインの更新と保存されるファイルは、Pod 間でロックされます。1 つの magpie だけが行う処理(保存済みサインインのバックグラウンド更新、チェックイン、プラグインの更新)は古い Pod が終了するまで続け、新しい Pod が 1 秒以内に引き継ぎます。ReadWriteOnce ボリュームは 1 つのノードにしかマウントできないため、上の <code>podAffinity</code> で新しい Pod を古い Pod のノードで起動します。ReadWriteMany ボリュームなら不要です。</p>
|
||||
<p><b>v0.1.4526 より前のバージョンからの更新。</b>古い Pod はこの引き継ぎに加わらないため、更新の間は両方がサインインを更新します。この 1 回だけは <code>strategy: Recreate</code> で更新し、その後で上のローリングアップデートに切り替えてください。</p>
|
||||
|
||||
<p style="margin-top:48px">質問や共有したいセットアップがあれば <a href="https://discord.gg/vGSnD3ZKQF">Discord</a> へどうぞ。詳細は<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#docker">リファレンス</a>(英語)にあります。</p>
|
||||
</article>
|
||||
|
||||
@@ -295,7 +295,10 @@ metadata:
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate <span class="c"># 同一时间只有一个 magpie 使用 /config</span>
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxSurge: 1 <span class="c"># 新 Pod 在旧 Pod 旁边启动</span>
|
||||
maxUnavailable: 0 <span class="c"># 新 Pod 就绪后旧 Pod 才退出</span>
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
@@ -305,6 +308,12 @@ spec:
|
||||
terminationGracePeriodSeconds: 30 <span class="c"># MAGPIE_DRAIN(20 秒)加 10 秒保存状态</span>
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
affinity:
|
||||
podAffinity: <span class="c"># 新 Pod 和旧 Pod 在同一节点,ReadWriteOnce 卷在那里</span>
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchLabels: {app: magpie}
|
||||
topologyKey: kubernetes.io/hostname
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
@@ -324,7 +333,8 @@ spec:
|
||||
</div>
|
||||
<p><b>就绪探针。</b>如上用 <code>exec</code> 执行 <code>magpie healthcheck</code>:它在容器内部发起请求,不需要密钥。<code>httpGet</code> 探针来自容器外部,需要网关密钥。</p>
|
||||
<p><b>更长的回合。</b>智能体的一个回合可能流式输出好几分钟。同时调大 <code>MAGPIE_DRAIN</code> 和 <code>terminationGracePeriodSeconds</code>,后者比前者多 10 秒:<code>MAGPIE_DRAIN: "300"</code> 配 <code>terminationGracePeriodSeconds: 310</code>。</p>
|
||||
<p><b>一个卷只跑一个 Pod。</b>提供网关的 magpie 负责续期已保存的登录,两个 Pod 共用一个 <code>/config</code> 会各自续期,可能让账号掉线。请保持 <code>strategy: Recreate</code>(或 <code>maxSurge: 0</code>):旧 Pod 先完成手上的请求并退出,新 Pod 再启动,其间发来的请求要等新 Pod 就绪。默认的 RollingUpdate 配 ReadWriteOnce 卷也无法安全重叠:新 Pod 若在另一个节点上就挂载不了卷,滚动更新会卡住。</p>
|
||||
<p><b>滚动更新。</b>新 Pod 和旧 Pod 共用同一个 <code>/config</code> 同时提供服务,新 Pod 就绪后 Service 开始向它转发请求;旧 Pod 随后按上文排空,不会丢请求。每次登录续期和每个保存的文件都在两个 Pod 之间加锁。只能由一个 magpie 做的事(后台续期已保存的登录、签到、更新插件)由旧 Pod 继续做到它退出,新 Pod 在一秒内接手。ReadWriteOnce 卷只能挂载在一个节点上,所以上面的 <code>podAffinity</code> 让新 Pod 在旧 Pod 所在的节点启动;用 ReadWriteMany 卷时可以去掉它。</p>
|
||||
<p><b>从 v0.1.4526 之前的版本更新。</b>旧 Pod 不参与这次交接,更新期间两个 Pod 会同时续期登录。这一次请用 <code>strategy: Recreate</code> 更新,之后再换成上面的滚动更新。</p>
|
||||
|
||||
<p style="margin-top:48px">遇到问题,或者有值得分享的配置?来 <a href="https://discord.gg/vGSnD3ZKQF">Discord</a> 聊。细节见<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#docker">参考文档</a>(英文)。</p>
|
||||
</article>
|
||||
|
||||
@@ -10936,7 +10936,10 @@ metadata:
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate # one magpie on /config at a time
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxSurge: 1 # the new pod starts beside the old one
|
||||
maxUnavailable: 0 # the old one ends once the new one is ready
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
@@ -10946,6 +10949,12 @@ spec:
|
||||
terminationGracePeriodSeconds: 30 # MAGPIE_DRAIN (20s) plus 10s to save
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
affinity:
|
||||
podAffinity: # the new pod on the old one's node, where the ReadWriteOnce volume is
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchLabels: {app: magpie}
|
||||
topologyKey: kubernetes.io/hostname
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
@@ -10968,7 +10977,9 @@ spec:
|
||||
|
||||
**Longer turns.** An agent’s turn can stream for minutes. Raise `MAGPIE_DRAIN` and `terminationGracePeriodSeconds` together, the second 10 seconds above the first: `MAGPIE_DRAIN: "300"` with `terminationGracePeriodSeconds: 310`.
|
||||
|
||||
**One pod per volume.** The magpie serving the gateway keeps the saved sign-ins renewed, and two pods on one `/config` would both renew them, which can sign an account out. Keep `strategy: Recreate` (or `maxSurge: 0`): the old pod finishes its requests and ends before the new one starts, and requests sent in between wait for the new one. A default RollingUpdate with a ReadWriteOnce volume doesn’t overlap safely either: on another node the new pod can’t mount the volume, and the rollout stalls.
|
||||
**Rolling updates.** The new pod serves beside the old one on the same `/config`, and the Service sends it requests once it is ready; the old pod then drains as above, so no request is dropped. Each sign-in renewal and each saved file is locked across the pods. What only one magpie may do (renewing the saved sign-ins in the background, check-ins, plugin updates) the old pod keeps doing until it ends, and the new pod takes it over within a second. A ReadWriteOnce volume mounts on one node only, so the `podAffinity` above starts the new pod on the old one's node; with a ReadWriteMany volume, leave it out.
|
||||
|
||||
**Updating from a version before v0.1.4526.** The old pod doesn't take part in that handover, so the two would both renew sign-ins for the length of the update. Make that one update with `strategy: Recreate`, then switch to the rolling update above.
|
||||
|
||||
Questions or a setup worth sharing? Ask on [Discord](https://discord.gg/vGSnD3ZKQF). The [reference](https://github.com/yetone/magpie/blob/main/docs/reference.md#docker) has the details.
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user