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).
This commit is contained in:
@@ -3850,6 +3850,24 @@ service's); `--addr host:port` names it by hand, and `magpie status --json`
|
||||
prints the role, pid, version and address for a watchdog. Bind-mounting a folder at `/config` in place of a
|
||||
named volume works too; it has to be writable by uid 65532.
|
||||
|
||||
On SIGTERM (`docker stop`, a Kubernetes rolling update, a service manager),
|
||||
`magpie serve` and `magpie web` drain rather than cut what they serve:
|
||||
`GET /` answers 503 at once, so `magpie healthcheck` fails and a readiness
|
||||
probe takes the pod out of its Service; in a Kubernetes pod the gateway
|
||||
keeps accepting for 5s while that reaches kube-proxy and the ingress; then
|
||||
it stops accepting and gives the requests in flight, streams included, up
|
||||
to `MAGPIE_DRAIN` to finish (seconds or a duration such as `90s`; `0`
|
||||
ends as before, after 2s). Unset, it is 20s in a Kubernetes pod, which
|
||||
fits the default `terminationGracePeriodSeconds` of 30 with room for
|
||||
magpie to save its state after, and 7s elsewhere, inside `docker stop`'s
|
||||
10s; raise it together with the grace the platform gives (`docker stop
|
||||
-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.
|
||||
|
||||
#### NAS with agents on other machines
|
||||
|
||||
Magpie can run on a headless NAS as a shared gateway even when the agents that
|
||||
|
||||
@@ -1793,7 +1793,13 @@ func serve() error {
|
||||
// the models a Remote magpie's agents are on, as the app follows them
|
||||
go agent.KeepFollowingRemote(ctx, 30*time.Second)
|
||||
drained := make(chan struct{})
|
||||
finish := stopGatewayOnSignal(func() { stop(); <-drained })
|
||||
// a SIGTERM (Kubernetes', Docker's, a service manager's) finishes the
|
||||
// requests in flight first (serve_drain.go)
|
||||
finish := stopGatewayOnSignalAs(func(sig os.Signal) {
|
||||
drainOnSignal(s, sig)
|
||||
stop()
|
||||
<-drained
|
||||
})
|
||||
err := s.ListenAndServe(ctx)
|
||||
close(drained)
|
||||
finish()
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
)
|
||||
|
||||
func TestDrainGrace(t *testing.T) {
|
||||
t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1")
|
||||
for v, want := range map[string]time.Duration{
|
||||
"": defaultDrain,
|
||||
"30": 30 * time.Second,
|
||||
"90s": 90 * time.Second,
|
||||
"2m": 2 * time.Minute,
|
||||
"0": 0,
|
||||
"soon": defaultDrain,
|
||||
"-5": defaultDrain,
|
||||
" 45 ": 45 * time.Second,
|
||||
"1.5s": 1500 * time.Millisecond,
|
||||
"-1m": defaultDrain,
|
||||
"10000": 10000 * time.Second,
|
||||
} {
|
||||
t.Setenv("MAGPIE_DRAIN", v)
|
||||
if got := drainGrace(); got != want {
|
||||
t.Errorf("MAGPIE_DRAIN=%q: %s, want %s", v, got, want)
|
||||
}
|
||||
}
|
||||
// outside Kubernetes the default ends inside docker stop's 10s
|
||||
t.Setenv("KUBERNETES_SERVICE_HOST", "")
|
||||
for _, v := range []string{"", "soon"} {
|
||||
t.Setenv("MAGPIE_DRAIN", v)
|
||||
if got := drainGrace(); got != plainDrain || got >= 10*time.Second {
|
||||
t.Errorf("MAGPIE_DRAIN=%q outside Kubernetes: %s, want %s", v, got, plainDrain)
|
||||
}
|
||||
}
|
||||
t.Setenv("MAGPIE_DRAIN", "30")
|
||||
if got := drainGrace(); got != 30*time.Second {
|
||||
t.Errorf("MAGPIE_DRAIN=30 outside Kubernetes: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Only a SIGTERM drains; in a Kubernetes pod the gateway goes on
|
||||
// accepting for kubeLinger first, out of the grace.
|
||||
func TestDrainOnSignal(t *testing.T) {
|
||||
var slept time.Duration
|
||||
old := lingerSleep
|
||||
lingerSleep = func(d time.Duration) { slept += d }
|
||||
t.Cleanup(func() { lingerSleep = old })
|
||||
t.Setenv("MAGPIE_DRAIN", "")
|
||||
|
||||
drainOnSignal(nil, syscall.SIGTERM) // magpie web beside another magpie's gateway
|
||||
|
||||
t.Setenv("KUBERNETES_SERVICE_HOST", "")
|
||||
for _, sig := range []os.Signal{os.Interrupt, syscall.SIGHUP} {
|
||||
g := gateway.New()
|
||||
drainOnSignal(g, sig)
|
||||
if g.Draining() {
|
||||
t.Errorf("%v drained the gateway", sig)
|
||||
}
|
||||
}
|
||||
g := gateway.New()
|
||||
drainOnSignal(g, syscall.SIGTERM)
|
||||
if !g.Draining() || slept != 0 {
|
||||
t.Fatalf("SIGTERM outside Kubernetes: draining %v, lingered %s", g.Draining(), slept)
|
||||
}
|
||||
if g.Grace() != plainDrain {
|
||||
t.Errorf("SIGTERM outside Kubernetes: grace %s, want %s", g.Grace(), plainDrain)
|
||||
}
|
||||
|
||||
t.Setenv("KUBERNETES_SERVICE_HOST", "10.96.0.1")
|
||||
g = gateway.New()
|
||||
drainOnSignal(g, syscall.SIGTERM)
|
||||
if !g.Draining() || slept != kubeLinger {
|
||||
t.Fatalf("SIGTERM in Kubernetes: draining %v, lingered %s, want %s", g.Draining(), slept, kubeLinger)
|
||||
}
|
||||
if g.Grace() != defaultDrain-kubeLinger {
|
||||
t.Errorf("SIGTERM in Kubernetes: grace %s, want %s", g.Grace(), defaultDrain-kubeLinger)
|
||||
}
|
||||
|
||||
t.Setenv("MAGPIE_DRAIN", "0")
|
||||
g = gateway.New()
|
||||
drainOnSignal(g, syscall.SIGTERM)
|
||||
if g.Draining() {
|
||||
t.Fatal("MAGPIE_DRAIN=0 drained")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
@@ -9,13 +10,19 @@ import (
|
||||
// Its return path waits for a signal already handling that drain, so main
|
||||
// cannot exit (or re-exec) before the handler has finished saving state.
|
||||
type signalGateway struct {
|
||||
stop func()
|
||||
stop func(os.Signal)
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
var exitGateway atomic.Pointer[signalGateway]
|
||||
|
||||
func stopGatewayOnSignal(stop func()) func() {
|
||||
return stopGatewayOnSignalAs(func(os.Signal) { stop() })
|
||||
}
|
||||
|
||||
// stopGatewayOnSignalAs is stopGatewayOnSignal for a command whose drain
|
||||
// depends on the signal that ends it (serve's SIGTERM, serve_drain.go).
|
||||
func stopGatewayOnSignalAs(stop func(os.Signal)) func() {
|
||||
g := &signalGateway{stop: stop, done: make(chan struct{})}
|
||||
exitGateway.Store(g)
|
||||
var once sync.Once
|
||||
|
||||
@@ -55,7 +55,7 @@ func finishSignalGateway(s os.Signal) {
|
||||
g := exitGateway.Swap(nil)
|
||||
if g != nil {
|
||||
defer close(g.done)
|
||||
g.stop()
|
||||
g.stop(s)
|
||||
}
|
||||
proc.EndProbes()
|
||||
provider.FlushServed() // a gateway's last answers, noted and not yet written
|
||||
|
||||
+10
-2
@@ -88,7 +88,11 @@ func webCmd(args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stopGatewayOnSignal(w.Close)()
|
||||
// a SIGTERM drains, as serve's (serve_drain.go)
|
||||
defer stopGatewayOnSignalAs(func(sig os.Signal) {
|
||||
drainOnSignal(gui.ServedGateway(), sig)
|
||||
w.Close()
|
||||
})()
|
||||
if !w.ServesGateway() {
|
||||
// another magpie has the gateway (the service, magpie serve, the
|
||||
// app): this page shows its settings and accounts, read from the
|
||||
@@ -249,7 +253,11 @@ func serveCmd(args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer stopGatewayOnSignal(w.Close)()
|
||||
// a SIGTERM drains, as serve's (serve_drain.go)
|
||||
defer stopGatewayOnSignalAs(func(sig os.Signal) {
|
||||
drainOnSignal(gui.ServedGateway(), sig)
|
||||
w.Close()
|
||||
})()
|
||||
public := advertisedURL()
|
||||
fmt.Println(green.Render("●"), "magpie gateway on", bold.Render(gateway.URL()))
|
||||
fmt.Println(muted.Render(" OpenAI "), public+"/v1/chat/completions", muted.Render("·"), public+"/v1/responses")
|
||||
|
||||
@@ -593,6 +593,11 @@ type Server struct {
|
||||
// handedOff: another magpie serves the port now, and this one's end
|
||||
// waits for its requests in flight to finish (handover.go)
|
||||
handedOff atomic.Bool
|
||||
// draining and grace: the gateway was told to end and finish what it
|
||||
// has (Drain): GET / answers 503, and its end waits grace for the
|
||||
// requests in flight
|
||||
draining atomic.Bool
|
||||
grace atomic.Int64
|
||||
// notAccepting: this one let its listener go, for the magpie serving
|
||||
// the port after it to take every connection (stopAccepting); its
|
||||
// Serve ending then waits for the drain
|
||||
@@ -996,6 +1001,11 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
// an agent streaming one reads a reply broken off (Codex:
|
||||
// "error decoding response body")
|
||||
log.Printf("gateway: ending after %s with requests still in flight; they are cut (%v)", s.drainFor(), err)
|
||||
// Shutdown leaves them answering: closing their connections
|
||||
// cancels each one's context, so its upstream call ends too
|
||||
// and holds nothing (provider.Hold) past the gateway's end in
|
||||
// a process that goes on (a restart, a test)
|
||||
srv.Close()
|
||||
}
|
||||
<-sockets
|
||||
// An inline description may still have to save after its request
|
||||
@@ -1240,6 +1250,14 @@ func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
if (local(r) || sharedWith(r)) && hubServes() {
|
||||
out["mcp_hub"] = true
|
||||
}
|
||||
// a gateway ending (Drain) is no longer ready: `magpie healthcheck`,
|
||||
// a container's probe, fails on it, so a load balancer sends new
|
||||
// requests to another while this one finishes its own
|
||||
if s.draining.Load() {
|
||||
out["draining"] = true
|
||||
writeJSON(w, http.StatusServiceUnavailable, out)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// heldStream is a fresh HOME whose provider "plan" streams one chunk, then
|
||||
// holds the rest until release is sent to (or the request ends).
|
||||
func heldStream(t *testing.T) (release chan struct{}) {
|
||||
t.Helper()
|
||||
fresh(t)
|
||||
release = make(chan struct{})
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.ReadAll(r.Body)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
f := w.(http.Flusher)
|
||||
io.WriteString(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"first \"}}]}\n\n")
|
||||
f.Flush()
|
||||
select {
|
||||
case <-release:
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
io.WriteString(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"last\"},\"finish_reason\":\"stop\"}]}\n\n")
|
||||
io.WriteString(w, "data: [DONE]\n\n")
|
||||
f.Flush()
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return release
|
||||
}
|
||||
|
||||
// startStream sends a streamed chat to addr and reads up to its first
|
||||
// chunk.
|
||||
func startStream(t *testing.T, addr string) (*http.Response, *bufio.Reader) {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequest("POST", "http://"+addr+"/v1/chat/completions", strings.NewReader(`{"model":"plan/m1","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { resp.Body.Close() })
|
||||
stream := bufio.NewReader(resp.Body)
|
||||
for {
|
||||
line, err := stream.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("the stream ended before its first chunk: %v", err)
|
||||
}
|
||||
if strings.Contains(line, "first") {
|
||||
return resp, stream
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rootStatus(t *testing.T, addr string) (int, string) {
|
||||
t.Helper()
|
||||
r, err := http.Get("http://" + addr + "/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
return r.StatusCode, string(b)
|
||||
}
|
||||
|
||||
// @justforlxz runs magpie in Kubernetes, and a rolling update's SIGTERM
|
||||
// cut the requests in flight: the gateway's end gave them 2s. Drained
|
||||
// (serve's SIGTERM), it answers GET / 503, so the readiness probe takes it
|
||||
// out of the Service, stops accepting as it ends, and a stream an agent is
|
||||
// reading then runs to its end, well past those 2s.
|
||||
func TestDrainedGatewayFinishesItsStream(t *testing.T) {
|
||||
release := heldStream(t)
|
||||
oldShort := shortDrain
|
||||
shortDrain = 10 * time.Millisecond
|
||||
t.Cleanup(func() { shortDrain = oldShort })
|
||||
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:0")
|
||||
s := New()
|
||||
stop, done := listening(t, s)
|
||||
defer stop()
|
||||
s.lnMu.Lock()
|
||||
addr := s.ln.Addr().String()
|
||||
s.lnMu.Unlock()
|
||||
|
||||
if code, b := rootStatus(t, addr); code != 200 || strings.Contains(b, "draining") {
|
||||
t.Fatalf("GET / before the drain: %d %s", code, b)
|
||||
}
|
||||
_, stream := startStream(t, addr)
|
||||
|
||||
s.Drain(time.Minute)
|
||||
if code, b := rootStatus(t, addr); code != http.StatusServiceUnavailable || !strings.Contains(b, `"draining":true`) || !strings.Contains(b, `"magpie"`) {
|
||||
t.Fatalf("GET / while draining: %d %s, want 503 and draining", code, b)
|
||||
}
|
||||
stop()
|
||||
|
||||
// no new connection is taken once it ends
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
c, err := net.DialTimeout("tcp", addr, time.Second)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
c.Close()
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the ending gateway still accepts connections")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
// and its end waits for the stream, well past shortDrain
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Fatalf("the gateway ended with a stream in flight: %v", err)
|
||||
case <-time.After(50 * shortDrain):
|
||||
}
|
||||
if b := s.Busy(); b.Requests != 1 {
|
||||
t.Fatalf("%d requests in flight, want the stream", b.Requests)
|
||||
}
|
||||
release <- struct{}{}
|
||||
rest, err := io.ReadAll(stream)
|
||||
if err != nil {
|
||||
t.Fatalf("the stream was cut: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(rest), "last") || !strings.Contains(string(rest), "[DONE]") {
|
||||
t.Fatalf("the stream's end didn't arrive: %q", rest)
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("the gateway never ended once its stream had")
|
||||
}
|
||||
}
|
||||
|
||||
// The drain is bounded: a stream past its grace is cut, and the gateway
|
||||
// ends, as Kubernetes would kill it at terminationGracePeriodSeconds.
|
||||
func TestDrainEndsAtItsGrace(t *testing.T) {
|
||||
release := heldStream(t)
|
||||
defer close(release)
|
||||
t.Setenv("MAGPIE_ADDR", "127.0.0.1:0")
|
||||
s := New()
|
||||
stop, done := listening(t, s)
|
||||
defer stop()
|
||||
s.lnMu.Lock()
|
||||
addr := s.ln.Addr().String()
|
||||
s.lnMu.Unlock()
|
||||
startStream(t, addr)
|
||||
s.Drain(100 * time.Millisecond)
|
||||
stop()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(30 * time.Second):
|
||||
t.Fatal("the drain outlived its grace")
|
||||
}
|
||||
// the cut request's handler outlives the gateway's end, holding the
|
||||
// provider catalog (holdCatalog) until it returns: the next test's
|
||||
// catalog would be read through the hold (TestGrokGetsAgentMessageAsUser
|
||||
// found migrations.json unread in a full run)
|
||||
for deadline := time.Now().Add(30 * time.Second); s.Busy().Requests != 0; time.Sleep(5 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("the cut stream is still in flight: %d", s.Busy().Requests)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,33 @@ func (s *Server) drainFor() time.Duration {
|
||||
if s.handingOver() {
|
||||
return handedOffDrain
|
||||
}
|
||||
if g := time.Duration(s.grace.Load()); g > 0 {
|
||||
return g // Drain's
|
||||
}
|
||||
return shortDrain
|
||||
}
|
||||
|
||||
// Drain readies the gateway's end for a stop that should cut nothing: a
|
||||
// SIGTERM to `magpie serve`, which is how Kubernetes, Docker and a service
|
||||
// manager end it (a rolling update's old pod). GET / answers 503 from now
|
||||
// on, so a readiness probe (`magpie healthcheck`) takes this magpie out of
|
||||
// its Service, and once ctx ends the requests in flight, a stream an agent
|
||||
// is reading included, are given grace to finish rather than shortDrain's
|
||||
// 2s. The listener closes as ctx ends, as before: new connections go to
|
||||
// the next magpie, or are refused.
|
||||
func (s *Server) Drain(grace time.Duration) {
|
||||
s.grace.Store(int64(grace))
|
||||
s.draining.Store(true)
|
||||
}
|
||||
|
||||
// Draining: Drain was called.
|
||||
func (s *Server) Draining() bool { return s.draining.Load() }
|
||||
|
||||
// Grace is the grace Drain gave, shortDrain before it was called.
|
||||
func (s *Server) Grace() time.Duration {
|
||||
if g := time.Duration(s.grace.Load()); g > 0 {
|
||||
return g
|
||||
}
|
||||
return shortDrain
|
||||
}
|
||||
|
||||
|
||||
+23
-1
@@ -1,6 +1,7 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
@@ -172,13 +173,34 @@ func (w *Web) Wait() error {
|
||||
|
||||
// Close stops the web page and waits for this process's gateway to save its sessions.
|
||||
func (w *Web) Close() {
|
||||
w.srv.Close()
|
||||
// a gateway draining (a SIGTERM, gateway.Drain) lets the page port's
|
||||
// requests in flight finish too, the /v1 ones an agent sends through it
|
||||
// included, for as long as the gateway gives its own
|
||||
pageDone := make(chan struct{})
|
||||
if gw := served.Load(); gw != nil && gw.Draining() {
|
||||
go func() {
|
||||
defer close(pageDone)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), gw.Grace())
|
||||
defer cancel()
|
||||
if w.srv.Shutdown(ctx) != nil {
|
||||
w.srv.Close()
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
w.srv.Close()
|
||||
close(pageDone)
|
||||
}
|
||||
// The gateway keeps idle Claude sessions as it ends. Wait for that
|
||||
// before returning or replacing this process, or the next turn has
|
||||
// to replay the whole conversation instead of resuming its session.
|
||||
stopServing()
|
||||
<-pageDone
|
||||
}
|
||||
|
||||
// ServedGateway is the gateway this process serves, nil while another
|
||||
// magpie has it.
|
||||
func ServedGateway() *gateway.Server { return served.Load() }
|
||||
|
||||
// webKeyMin is the shortest MAGPIE_WEB_KEY taken: it is all that stands
|
||||
// between the network and the keys behind the page.
|
||||
const webKeyMin = 16
|
||||
|
||||
@@ -29,7 +29,7 @@ e8f03915aaf12c386bd6254ccfacbe6dc7ae1544e0080bde67ce31b048a50ee0 docs/copilot.h
|
||||
c2795244d9df800736d5be9042a45bca9358800b27521723e9a4f0604e7a8c43 docs/crush.html
|
||||
d042047b8d4e480702a6986c52135154ded05388ff82e63f215d652ea55f0c6e docs/cursor-private-inference.html
|
||||
cf2645267d38d072f0467a02f6888b3a8848b27c3b14fa2461cda904ab07b793 docs/deepseek.html
|
||||
2c0344b89bcc3c7a33004261e53e96802618357f8f5b309405ba9f3fb67a1bca docs/docker.html
|
||||
6a7db14989185d62f2a9297cbe4e0f6d2c7811744ee8585f43626243319be2ac 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
|
||||
88f23a4f1639412d41314e18dba803992e004a662cbca01613dbf4729a0d45c5 docs/ja/docker.html
|
||||
1c364af181285b3b3c3e8545f45203dd485996bfadbdf788fe994a474d35f0f4 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
|
||||
8e8ada5cbfa1e6062bb267432afa39fe4b14d7b2bfe6b34a48c23bd1200f45c5 docs/zh/docker.html
|
||||
1158f828c65d9ad0ad2d9792a6bb6b05444fde1ec4909f1b3ea0256133a629fe docs/zh/docker.html
|
||||
d282d59587baab9e6cdd4c1d36b69b9ceea9e2cd0b49d1537642fd529c7816a8 docs/zh/droid.html
|
||||
e8bc868847eede8bcdf157f13e2508f91c790baee914cb3c8f2b1801bf2c5fc1 docs/zh/ds-bot.html
|
||||
2665b5de3bc00d5a7f34ed318dcecc76cd136479ecd239f2623f76134f826850 docs/zh/empryo.html
|
||||
|
||||
@@ -142,6 +142,7 @@
|
||||
<a href="#share">Gateway keys and other machines</a>
|
||||
<a href="#compose">Docker Compose on a NAS</a>
|
||||
<a href="#ops">Health, terminal, updates</a>
|
||||
<a href="#k8s">Kubernetes</a>
|
||||
</aside>
|
||||
|
||||
<article>
|
||||
@@ -235,6 +236,7 @@ docker logs magpie</pre>
|
||||
<tr><td><code>MAGPIE_NAME</code></td><td>what this magpie is called: the browser tab’s title reads <code><name> · magpie</code>, to tell several deployments apart. A name set on the page, in <span class="ui">Settings</span> → <span class="ui">Network and sharing</span> → <span class="ui">Advanced</span> → <span class="ui">Name</span>, comes first.</td></tr>
|
||||
<tr><td><code>MAGPIE_TLS_CERT</code>, <code>MAGPIE_TLS_KEY</code></td><td>a PEM certificate (its chain after it) and its key, mounted into the container: other machines then reach the gateway and the browser UI over <code>https://</code> only, and plain HTTP from them gets 400. The files are read again when they change, so a renewal needs no restart. One without the other, or files that don’t load, stop magpie from starting. Use <code>https://</code> in <code>MAGPIE_PUBLIC_URL</code> too.</td></tr>
|
||||
<tr><td><code>MAGPIE_ALLOW_IPS</code></td><td>the only addresses other machines may reach the gateway and the browser UI from, as IPs and CIDR ranges: <code>203.0.113.7,10.0.0.0/8,2001:db8::/32</code>. Any other address gets 403, even with a gateway key. Unset lets every address in, each with a key. See <a href="#allow">Allowed addresses</a>.</td></tr>
|
||||
<tr><td><code>MAGPIE_DRAIN</code></td><td>how long a stop waits for the requests in flight, streams included: seconds (<code>300</code>) or a duration (<code>5m</code>); 20 seconds in Kubernetes and 7 elsewhere unless set (<code>docker stop</code> waits 10), <code>0</code> for 2. Past 10, give Docker as long: <code>docker stop -t</code>, Compose’s <code>stop_grace_period</code>. See <a href="#k8s">Kubernetes</a>.</td></tr>
|
||||
<tr><td><code>HOME</code>, <code>XDG_CONFIG_HOME</code>, <code>XDG_CACHE_HOME</code>, <code>XDG_DATA_HOME</code>, <code>XDG_STATE_HOME</code></td><td>set by the image to the folders under <code>/config</code> above; leave them</td></tr>
|
||||
</table></div>
|
||||
|
||||
@@ -281,6 +283,49 @@ docker logs magpie</pre>
|
||||
<li><b>Build it yourself.</b> <code>docker build -t magpie .</code> in a checkout of <a href="https://github.com/yetone/magpie">the repository</a> makes the same image.</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="k8s"><a class="anchor" href="#k8s">Kubernetes</a></h2>
|
||||
<p>A restart cuts nothing in flight, with nothing to set. On <code>SIGTERM</code> (a rolling update, <code>kubectl delete pod</code>, <code>docker stop</code>), <code>magpie serve</code> and <code>magpie web</code> fail their readiness check at once, keep accepting for 5 seconds while the Service stops sending them requests, then stop accepting and let the requests in flight finish, streams included, for up to 20 seconds.</p>
|
||||
<div class="code">
|
||||
<span class="lang">deployment.yaml</span>
|
||||
<button class="copy" data-copy="ex-k8s">Copy</button>
|
||||
<pre id="ex-k8s">apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: magpie
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate <span class="c"># one magpie on /config at a time</span>
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: magpie}
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 30 <span class="c"># MAGPIE_DRAIN (20s) plus 10s to save</span>
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
ports:
|
||||
- containerPort: 3425
|
||||
readinessProbe:
|
||||
exec:
|
||||
command: [/magpie, healthcheck]
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- name: config
|
||||
mountPath: /config
|
||||
volumes:
|
||||
- name: config
|
||||
persistentVolumeClaim:
|
||||
claimName: magpie-config <span class="c"># ReadWriteOnce</span></pre>
|
||||
</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 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>
|
||||
</main>
|
||||
|
||||
@@ -142,6 +142,7 @@
|
||||
<a href="#share">ゲートウェイキーとほかのマシン</a>
|
||||
<a href="#compose">NAS で Docker Compose</a>
|
||||
<a href="#ops">ヘルスチェック・ターミナル・更新</a>
|
||||
<a href="#k8s">Kubernetes</a>
|
||||
</aside>
|
||||
|
||||
<article>
|
||||
@@ -235,6 +236,7 @@ docker logs magpie</pre>
|
||||
<tr><td><code>MAGPIE_NAME</code></td><td>この magpie の名前。ブラウザのタブのタイトルが <code><名前> · magpie</code> になり、複数デプロイしたときに見分けられます。ページの <span class="ui">設定</span> → <span class="ui">ネットワークと共有</span> → <span class="ui">詳細設定</span> → <span class="ui">名前</span> で付けた名前が優先されます。</td></tr>
|
||||
<tr><td><code>MAGPIE_TLS_CERT</code>、<code>MAGPIE_TLS_KEY</code></td><td>コンテナにマウントした PEM の証明書(後ろにチェーン)と秘密鍵。ほかのマシンはゲートウェイとブラウザ UI に <code>https://</code> でだけ届き、平文の HTTP は 400 になります。ファイルが変わると読み直すので、更新に再起動はいりません。片方だけ、または読めないファイルでは magpie は起動しません。<code>MAGPIE_PUBLIC_URL</code> も <code>https://</code> にしてください。</td></tr>
|
||||
<tr><td><code>MAGPIE_ALLOW_IPS</code></td><td>ほかのマシンがゲートウェイとブラウザ UI に接続できるアドレス。IP または CIDR 範囲で書きます:<code>203.0.113.7,10.0.0.0/8,2001:db8::/32</code>。ほかのアドレスからは、ゲートウェイキーがあっても 403 になります。設定しなければすべてのアドレスから接続でき、それぞれキーが要ります。<a href="#allow">許可するアドレス</a>を参照。</td></tr>
|
||||
<tr><td><code>MAGPIE_DRAIN</code></td><td>停止時に処理中のリクエスト(ストリームを含む)を待つ時間:秒数(<code>300</code>)または期間(<code>5m</code>)。未設定なら Kubernetes では 20 秒、それ以外では 7 秒(<code>docker stop</code> は 10 秒しか待ちません)、<code>0</code> で 2 秒。10 秒を超える場合は Docker にも同じだけ待たせます:<code>docker stop -t</code>、Compose の <code>stop_grace_period</code>。<a href="#k8s">Kubernetes</a> を参照。</td></tr>
|
||||
<tr><td><code>HOME</code>、<code>XDG_CONFIG_HOME</code>、<code>XDG_CACHE_HOME</code>、<code>XDG_DATA_HOME</code>、<code>XDG_STATE_HOME</code></td><td>イメージが上の <code>/config</code> 配下のフォルダに設定しています。変えないでください</td></tr>
|
||||
</table></div>
|
||||
|
||||
@@ -281,6 +283,49 @@ docker logs magpie</pre>
|
||||
<li><b>自分でビルドする。</b><a href="https://github.com/yetone/magpie">リポジトリ</a>のチェックアウトで <code>docker build -t magpie .</code> を実行すると同じイメージができます。</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="k8s"><a class="anchor" href="#k8s">Kubernetes</a></h2>
|
||||
<p>再起動しても処理中のリクエストは切れません。設定は不要です。<code>SIGTERM</code>(ローリングアップデート、<code>kubectl delete pod</code>、<code>docker stop</code>)を受けると、<code>magpie serve</code> と <code>magpie web</code> はすぐにレディネスチェックを失敗させ、Service が転送を止めるまで 5 秒間受け付けを続け、その後新しい接続の受け付けをやめて、処理中のリクエスト(ストリームを含む)が終わるのを最大 20 秒待ちます。</p>
|
||||
<div class="code">
|
||||
<span class="lang">deployment.yaml</span>
|
||||
<button class="copy" data-copy="ex-k8s">コピー</button>
|
||||
<pre id="ex-k8s">apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: magpie
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate <span class="c"># /config を使う magpie は常に 1 つ</span>
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: magpie}
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 30 <span class="c"># MAGPIE_DRAIN(20 秒)+保存用の 10 秒</span>
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
ports:
|
||||
- containerPort: 3425
|
||||
readinessProbe:
|
||||
exec:
|
||||
command: [/magpie, healthcheck]
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- name: config
|
||||
mountPath: /config
|
||||
volumes:
|
||||
- name: config
|
||||
persistentVolumeClaim:
|
||||
claimName: magpie-config <span class="c"># ReadWriteOnce</span></pre>
|
||||
</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 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>
|
||||
</main>
|
||||
|
||||
@@ -142,6 +142,7 @@
|
||||
<a href="#share">网关密钥与其他机器</a>
|
||||
<a href="#compose">在 NAS 上用 Docker Compose</a>
|
||||
<a href="#ops">健康检查、终端与更新</a>
|
||||
<a href="#k8s">Kubernetes</a>
|
||||
</aside>
|
||||
|
||||
<article>
|
||||
@@ -235,6 +236,7 @@ docker logs magpie</pre>
|
||||
<tr><td><code>MAGPIE_NAME</code></td><td>这个 magpie 的名称:浏览器标签页的标题显示为 <code><名称> · magpie</code>,部署了好几个时用来区分。在页面的 <span class="ui">设置</span> → <span class="ui">网络与共享</span> → <span class="ui">高级</span> → <span class="ui">名称</span> 里设置的名称优先。</td></tr>
|
||||
<tr><td><code>MAGPIE_TLS_CERT</code>、<code>MAGPIE_TLS_KEY</code></td><td>挂载进容器的 PEM 证书(后面跟着证书链)和私钥:其他机器只能用 <code>https://</code> 访问网关和 Web 界面,它们发来的明文 HTTP 返回 400。文件变了会重新读取,续期不用重启。只给一个,或文件读不出来,magpie 不会启动。<code>MAGPIE_PUBLIC_URL</code> 也写成 <code>https://</code>。</td></tr>
|
||||
<tr><td><code>MAGPIE_ALLOW_IPS</code></td><td>其他机器只能从这些地址访问网关和 Web 界面,写 IP 或 CIDR 网段:<code>203.0.113.7,10.0.0.0/8,2001:db8::/32</code>。其他地址即使带着网关密钥也会得到 403。不设置则所有地址都可访问,各自仍需密钥。见<a href="#allow">允许的地址</a>。</td></tr>
|
||||
<tr><td><code>MAGPIE_DRAIN</code></td><td>停止时等待进行中请求(包括流式输出)的时长:秒数(<code>300</code>)或时长(<code>5m</code>);未设置时在 Kubernetes 中为 20 秒,其他环境为 7 秒(<code>docker stop</code> 只等 10 秒),<code>0</code> 为 2 秒。超过 10 秒时,也要让 Docker 等这么久:<code>docker stop -t</code>、Compose 的 <code>stop_grace_period</code>。见 <a href="#k8s">Kubernetes</a>。</td></tr>
|
||||
<tr><td><code>HOME</code>、<code>XDG_CONFIG_HOME</code>、<code>XDG_CACHE_HOME</code>、<code>XDG_DATA_HOME</code>、<code>XDG_STATE_HOME</code></td><td>镜像已设为上面 <code>/config</code> 下的目录,不要改</td></tr>
|
||||
</table></div>
|
||||
|
||||
@@ -281,6 +283,49 @@ docker logs magpie</pre>
|
||||
<li><b>自己构建。</b>在<a href="https://github.com/yetone/magpie">仓库</a>的检出目录里 <code>docker build -t magpie .</code> 得到同样的镜像。</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="k8s"><a class="anchor" href="#k8s">Kubernetes</a></h2>
|
||||
<p>重启不会中断正在进行的请求,无需任何配置。收到 <code>SIGTERM</code>(滚动更新、<code>kubectl delete pod</code>、<code>docker stop</code>)时,<code>magpie serve</code> 和 <code>magpie web</code> 立即让就绪检查失败,在 Service 停止转发期间继续接收 5 秒,然后停止接收新连接,让正在进行的请求(包括流式输出)最多再跑 20 秒完成。</p>
|
||||
<div class="code">
|
||||
<span class="lang">deployment.yaml</span>
|
||||
<button class="copy" data-copy="ex-k8s">复制</button>
|
||||
<pre id="ex-k8s">apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: magpie
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate <span class="c"># 同一时间只有一个 magpie 使用 /config</span>
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: magpie}
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 30 <span class="c"># MAGPIE_DRAIN(20 秒)加 10 秒保存状态</span>
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
ports:
|
||||
- containerPort: 3425
|
||||
readinessProbe:
|
||||
exec:
|
||||
command: [/magpie, healthcheck]
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- name: config
|
||||
mountPath: /config
|
||||
volumes:
|
||||
- name: config
|
||||
persistentVolumeClaim:
|
||||
claimName: magpie-config <span class="c"># ReadWriteOnce</span></pre>
|
||||
</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 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>
|
||||
</main>
|
||||
|
||||
@@ -10874,6 +10874,7 @@ A volume made by an older image keeps working: magpie adds the folders it lacks
|
||||
| `MAGPIE_NAME` | what this magpie is called: the browser tab’s title reads `<name> · magpie`, to tell several deployments apart. A name set on the page, in Settings → Network and sharing → Advanced → Name, comes first. |
|
||||
| `MAGPIE_TLS_CERT`, `MAGPIE_TLS_KEY` | a PEM certificate (its chain after it) and its key, mounted into the container: other machines then reach the gateway and the browser UI over `https://` only, and plain HTTP from them gets 400. The files are read again when they change, so a renewal needs no restart. One without the other, or files that don’t load, stop magpie from starting. Use `https://` in `MAGPIE_PUBLIC_URL` too. |
|
||||
| `MAGPIE_ALLOW_IPS` | the only addresses other machines may reach the gateway and the browser UI from, as IPs and CIDR ranges: `203.0.113.7,10.0.0.0/8,2001:db8::/32`. Any other address gets 403, even with a gateway key. Unset lets every address in, each with a key. See Allowed addresses. |
|
||||
| `MAGPIE_DRAIN` | how long a stop waits for the requests in flight, streams included: seconds (`300`) or a duration (`5m`); 20 seconds in Kubernetes and 7 elsewhere unless set (`docker stop` waits 10), `0` for 2. Past 10, give Docker as long: `docker stop -t`, Compose’s `stop_grace_period`. See Kubernetes. |
|
||||
| `HOME`, `XDG_CONFIG_HOME`, `XDG_CACHE_HOME`, `XDG_DATA_HOME`, `XDG_STATE_HOME` | set by the image to the folders under `/config` above; leave them |
|
||||
|
||||
## Gateway keys and other machines
|
||||
@@ -10923,6 +10924,52 @@ Then: `sudo chown -R 65532:65532 ./config`, `docker compose up -d`, open `http:/
|
||||
- **Updates..** Pull the new image and recreate the container on the same volume: `docker pull ghcr.io/yetone/magpie:latest`, then `docker rm -f magpie` and the same `docker run`, or `docker compose pull && docker compose up -d`. magpie releases several times a day; for one update a day with Renovate or Watchtower, follow `daily` (with Renovate, pin its digest), or `stable` for one a week. When magpie finds an update, Settings › About names that version's own image (`docker pull ghcr.io/yetone/magpie:0.1.1150`): `latest` may hold a newer release than your update channel's; run the container from the tag you pulled.
|
||||
- **Build it yourself..** `docker build -t magpie .` in a checkout of [the repository](https://github.com/yetone/magpie) makes the same image.
|
||||
|
||||
## Kubernetes
|
||||
|
||||
A restart cuts nothing in flight, with nothing to set. On `SIGTERM` (a rolling update, `kubectl delete pod`, `docker stop`), `magpie serve` and `magpie web` fail their readiness check at once, keep accepting for 5 seconds while the Service stops sending them requests, then stop accepting and let the requests in flight finish, streams included, for up to 20 seconds.
|
||||
|
||||
```
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: magpie
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate # one magpie on /config at a time
|
||||
selector:
|
||||
matchLabels: {app: magpie}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: magpie}
|
||||
spec:
|
||||
terminationGracePeriodSeconds: 30 # MAGPIE_DRAIN (20s) plus 10s to save
|
||||
securityContext:
|
||||
fsGroup: 65532
|
||||
containers:
|
||||
- name: magpie
|
||||
image: ghcr.io/yetone/magpie:stable
|
||||
ports:
|
||||
- containerPort: 3425
|
||||
readinessProbe:
|
||||
exec:
|
||||
command: [/magpie, healthcheck]
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- name: config
|
||||
mountPath: /config
|
||||
volumes:
|
||||
- name: config
|
||||
persistentVolumeClaim:
|
||||
claimName: magpie-config # ReadWriteOnce
|
||||
```
|
||||
|
||||
**Readiness.** Probe with `exec` and `magpie healthcheck`, as above: it asks from inside the container, so it needs no key. An `httpGet` probe comes from outside the container and would need a gateway key.
|
||||
|
||||
**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.
|
||||
|
||||
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