Skip to content

An open-source, faster Devin alternative

TypeScript

feat(modelproxy): restart without a gap on SIGUSR2 (tableflip) (#1047)

opencomputer-app[bot]d48045f3ebf3
diff --git a/computer/modelproxy/README.md b/computer/modelproxy/README.md
index f6549181..7b90080a 100644
--- a/computer/modelproxy/README.md
+++ b/computer/modelproxy/README.md
@@ -4,7 +4,7 @@ A small reverse proxy between the model clients in a computer's sessions (Claude
Everything the proxy knows about an upstream is configuration: a **profile** names the upstream, the routes a session may call, the headers that carry the credential, and what to report back. The proxy has no built-in providers.
-Go, standard library only. One static binary.
+Go, the standard library and one dependency ([tableflip](https://github.com/cloudflare/tableflip), for the restart). One static binary.
```
session's client ──HTTP──▶ api socket ─────────┐
@@ -164,14 +164,14 @@ Rules that hold:
| `-identity` | `cgroup` | `cgroup` or `single` |
| `-bindings-file` | `/run/oc-modelproxy/profile-bindings.json` | persisted bindings, without variables (empty: off) |
| `-hold-timeout` | `10s` | how long a request waits for its caller's bind, and then for a free upstream connection |
-| `-drain-timeout` | `630s` | on SIGTERM, how long streams in flight may finish |
+| `-drain-timeout` | `630s` | on SIGTERM or after a handoff, how long streams in flight may finish |
| `-max-inflight-per-caller` | `32` | concurrent requests per caller, held ones included (0: no limit) |
| `-max-conns-per-caller` | `128` | connections a caller may have open on the API socket (0: no limit) |
| `-ws-idle-timeout` | `5m` | close a WebSocket idle this long between responses (0: never) |
| `-max-idle-conns-per-host`, `-max-conns-per-host`, `-idle-conn-timeout` | `96`, `256`, `50s` | upstream connection pool, per profile |
| `-debug`, `-version` | | |
-Profiles are read at start; to change them, restart the proxy. Bindings survive the restart and streams in flight finish first. The garbage collector runs at `GOGC=400` unless the environment sets `GOGC`.
+Profiles are read at start; to change them, or the binary, send `SIGUSR2`. The proxy starts its replacement with the same command line and the listening sockets, and when that is ready stops accepting and exits once its streams end. No connection is refused in between: the replacement holds each caller's requests until the binder, whose connection the old process closes, has re-bound. A replacement that does not start changes nothing; the old process logs `handoff failed; still serving`. Under systemd the unit needs `Type=notify` and `NotifyAccess=all`, since the replacement reports itself as the new main pid. `SIGTERM` stops the proxy: bindings survive, streams in flight finish first, and new connections wait for the next start only if systemd owns the sockets. The garbage collector runs at `GOGC=400` unless the environment sets `GOGC`.
## Build and test
diff --git a/computer/modelproxy/go.mod b/computer/modelproxy/go.mod
index b209af3b..7dc584b0 100644
--- a/computer/modelproxy/go.mod
+++ b/computer/modelproxy/go.mod
@@ -1,3 +1,5 @@
module github.com/diggerhq/opencomputer/computer/modelproxy
go 1.27
+
+require github.com/cloudflare/tableflip v1.2.3
diff --git a/computer/modelproxy/go.sum b/computer/modelproxy/go.sum
new file mode 100644
index 00000000..3184301a
--- /dev/null
+++ b/computer/modelproxy/go.sum
@@ -0,0 +1,4 @@
+github.com/cloudflare/tableflip v1.2.3 h1:8I+B99QnnEWPHOY3fWipwVKxS70LGgUsslG7CSfmHMw=
+github.com/cloudflare/tableflip v1.2.3/go.mod h1:P4gRehmV6Z2bY5ao5ml9Pd8u6kuEnlB37pUFMmv7j2E=
+golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 h1:myAQVi0cGEoqQVR5POX+8RR2mrocKqNN1hmeMqhX27k=
+golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
diff --git a/computer/modelproxy/handoff.go b/computer/modelproxy/handoff.go
new file mode 100644
index 00000000..d350895c
--- /dev/null
+++ b/computer/modelproxy/handoff.go
@@ -0,0 +1,83 @@
+// A restart without a gap, by github.com/cloudflare/tableflip. On SIGUSR2
+// the proxy starts its replacement, the same command line and so the binary
+// and the profiles now on disk, and passes it the two listening sockets.
+// When the replacement is ready, this process stops accepting and exits once
+// its streams end (main.go); new connections are the replacement's, which
+// holds each caller's requests until the binder re-binds, as after any start.
+//
+// Invariants:
+// - A replacement that does not become ready (profiles that do not load, a
+// crash, a minute without a word) changes nothing: this process goes on
+// serving, and says so in its log.
+// - One replacement at a time, and none while the process this one replaced
+// is still draining: such a SIGUSR2 is logged and otherwise ignored.
+// - A socket is found by name, not by path: the replaced process's, else
+// systemd's (activation.go), else a new one.
+// - The service manager is told the replacement's pid (MAINPID) before the
+// replaced process is told to go, so it never sees its main process exit.
+// A unit that uses the handoff needs NotifyAccess=all: the replacement
+// is not the main process when it says so.
+// - The socket files are never unlinked: systemd's are its own, and a new
+// one replaces a stale one (listenUnix).
+package main
+
+import (
+ "fmt"
+ "net"
+ "os"
+
+ "github.com/cloudflare/tableflip"
+)
+
+type handoff struct{ upg *tableflip.Upgrader }
+
+// newHandoff is called once, before any socket is opened.
+func newHandoff() (*handoff, error) {
+ upg, err := tableflip.New(tableflip.Options{})
+ if err != nil {
+ return nil, err
+ }
+ return &handoff{upg: upg}, nil
+}
+
+// listener is the socket called name: the replaced process's, else the
+// activated one, else a new one at path. Whichever it is goes to the next
+// replacement.
+func (h *handoff) listener(name, path string, activated map[string]net.Listener) (net.Listener, error) {
+ l, err := h.upg.Listener("unix", name)
+ if err != nil || l != nil {
+ return l, err
+ }
+ if l = activated[name]; l == nil {
+ if l, err = listenUnix(path); err != nil {
+ return nil, err
+ }
+ }
+ tl, ok := l.(tableflip.Listener)
+ if !ok {
+ return nil, fmt.Errorf("%s socket: a %T cannot be handed off", name, l)
+ }
+ if err := h.upg.AddListener("unix", name, tl); err != nil {
+ return nil, err
+ }
+ return l, nil
+}
+
+// ready tells the service manager, then the replaced process if there is
+// one, that this process serves.
+func (h *handoff) ready() error {
+ sdNotify(fmt.Sprintf("MAINPID=%d\nREADY=1", os.Getpid()))
+ return h.upg.Ready()
+}
+
+// replace starts the replacement; it returns at once.
+func (h *handoff) replace() {
+ go func() {
+ if err := h.upg.Upgrade(); err != nil {
+ logError("handoff failed; still serving", "error", err.Error())
+ }
+ }()
+}
+
+// replaced is closed when the replacement is ready.
+func (h *handoff) replaced() <-chan struct{} { return h.upg.Exit() }
diff --git a/computer/modelproxy/handoff_test.go b/computer/modelproxy/handoff_test.go
new file mode 100644
index 00000000..d66db43b
--- /dev/null
+++ b/computer/modelproxy/handoff_test.go
@@ -0,0 +1,290 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "encoding/pem"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// logFile is the processes' shared log: a file, not a pipe, which a
+// replacement would hold open past the exit of the process it replaced.
+type logFile string
+
+func (l logFile) String() string {
+ b, _ := os.ReadFile(string(l))
+ return string(b)
+}
+
+// handoffProxy is a proxy run as a real process (this test binary, running
+// run), its replacements included: what it tells the service manager, and
+// its two sockets.
+type handoffProxy struct {
+ t *testing.T
+ dir string
+ notify chan string
+ log logFile
+}
+
+var mainPID = regexp.MustCompile(`MAINPID=(\d+)`)
+
+// ready waits for a process to report itself ready and returns its pid.
+func (p *handoffProxy) ready() int {
+ p.t.Helper()
+ select {
+ case m := <-p.notify:
+ pid, _ := strconv.Atoi(string(mainPID.FindSubmatch([]byte(m))[1]))
+ if pid == 0 || !strings.Contains(m, "READY=1") {
+ p.t.Fatalf("notified %q", m)
+ }
+ return pid
+ case <-time.After(20 * time.Second):
+ p.t.Fatalf("no process became ready; log:\n%s", p.log)
+ return 0
+ }
+}
+
+// binder connects to the control socket and waits for the hello.
+func (p *handoffProxy) binder() (*ctl, map[string]any) {
+ p.t.Helper()
+ h := &harness{t: p.t, ctlPath: filepath.Join(p.dir, "control.sock")}
+ k := h.dialControl()
+ return k, k.waitFor(isT("hello"))
+}
+
+func (p *handoffProxy) bind(k *ctl) {
+ p.t.Helper()
+ k.send(map[string]any{"t": "bind", "caller": singleCaller, "sessionKey": "s1", "profile": "p", "vars": map[string]string{"token": "sk-test"}, "key": "k1"})
+ k.send(map[string]any{"t": "synced"})
+ k.waitFor(isBound(singleCaller, "k1"))
+}
+
+// post sends one request on a connection of its own.
+func (p *handoffProxy) post(ctx context.Context, path string) (*http.Response, error) {
+ tr := &http.Transport{DisableKeepAlives: true, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", filepath.Join(p.dir, "api.sock"))
+ }}
+ req, _ := http.NewRequestWithContext(ctx, http.MethodPost, "http://proxy"+path, strings.NewReader(`{}`))
+ req.Header.Set("X-Api-Key", testPlaceholder)
+ return (&http.Client{Transport: tr}).Do(req)
+}
+
+func (p *handoffProxy) logged(msg string) {
+ p.t.Helper()
+ for range 2000 {
+ if strings.Contains(p.log.String(), msg) {
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ p.t.Fatalf("never logged %q; log:\n%s", msg, p.log)
+}
+
+// TestHandoff: a SIGUSR2 replaces the proxy under a live stream. The stream
+// finishes on the process it started on, the replacement holds a new
+// request until the binder has re-bound and then serves it, and a
+// replacement that cannot start leaves the old process serving.
+func TestHandoff(t *testing.T) {
+ if dir := os.Getenv("MP_HANDOFF_DIR"); dir != "" {
+ initLogger("test", slog.LevelInfo)
+ cfg, _, err := parseFlags([]string{"-identity=single", "-hold-timeout=20s", "-drain-timeout=30s",
+ "-api-socket", filepath.Join(dir, "api.sock"), "-control-socket", filepath.Join(dir, "control.sock"),
+ "-profiles", filepath.Join(dir, "profiles"), "-bindings-file", filepath.Join(dir, "bindings.json")})
+ if err == nil {
+ err = run(cfg)
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ return
+ }
+ if runtime.GOOS != "linux" {
+ t.Skip("the replacement trusts the fake upstream through SSL_CERT_FILE")
+ }
+
+ release := make(chan struct{})
+ up := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("X-Api-Key") != "sk-test" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ io.WriteString(w, "a")
+ if r.URL.Path == "/v1/stream" {
+ w.(http.Flusher).Flush()
+ <-release
+ io.WriteString(w, "b")
+ }
+ }))
+ up.EnableHTTP2 = false
+ up.StartTLS()
+ defer up.Close()
+
+ dir, err := os.MkdirTemp("", "mp") // short: sun_path is 108 bytes
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.RemoveAll(dir)
+ write := func(name, content string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ write("ca.pem", string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: up.Certificate().Raw})))
+ if err := os.Mkdir(filepath.Join(dir, "profiles"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ profile := toJSON(map[string]any{"p": map[string]any{"upstream": up.URL,
+ "routes": map[string]any{"POST /v1/stream": map[string]any{}, "POST /v1/quick": map[string]any{}},
+ "set": map[string]string{"X-Api-Key": "{token}"}}})
+ write("profiles/p.json", profile)
+
+ nc, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: filepath.Join(dir, "notify.sock"), Net: "unixgram"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer nc.Close()
+ p := &handoffProxy{t: t, dir: dir, notify: make(chan string, 16), log: logFile(filepath.Join(dir, "log"))}
+ go func() {
+ b := make([]byte, 512)
+ for {
+ n, err := nc.Read(b)
+ if err != nil {
+ return
+ }
+ p.notify <- string(b[:n])
+ }
+ }()
+
+ cmd := exec.Command(os.Args[0], "-test.run=^TestHandoff$", "-test.count=1", "-test.timeout=120s")
+ cmd.Env = append(os.Environ(), "MP_HANDOFF_DIR="+dir, "SSL_CERT_FILE="+filepath.Join(dir, "ca.pem"), "NOTIFY_SOCKET="+filepath.Join(dir, "notify.sock"))
+ out, err := os.Create(string(p.log))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer out.Close()
+ cmd.Stdout, cmd.Stderr = out, out
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ first := p.ready()
+ if first != cmd.Process.Pid {
+ t.Fatalf("the first process reported pid %d, is %d", first, cmd.Process.Pid)
+ }
+ second := 0
+ defer func() {
+ cmd.Process.Kill()
+ if second != 0 {
+ syscall.Kill(second, syscall.SIGKILL)
+ }
+ }()
+ k, _ := p.binder()
+ p.bind(k)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ defer cancel()
+ stream, err := p.post(ctx, "/v1/stream")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer stream.Body.Close()
+ body := bufio.NewReader(stream.Body)
+ if c, err := body.ReadByte(); err != nil || c != 'a' {
+ t.Fatalf("stream start: %q %v", c, err)
+ }
+
+ // A replacement that cannot start: the old process goes on serving.
+ write("profiles/p.json", `{"p":{"upstream":"http://not-https.example"}}`)
+ cmd.Process.Signal(syscall.SIGUSR2)
+ p.logged("handoff failed; still serving")
+ if res, err := p.post(ctx, "/v1/quick"); err != nil || res.StatusCode != http.StatusOK {
+ t.Fatalf("after a failed handoff: %v %v", res, err)
+ }
+
+ // One that can.
+ write("profiles/p.json", profile)
+ cmd.Process.Signal(syscall.SIGUSR2)
+ if second = p.ready(); second == first {
+ t.Fatal("the replacement reported the old pid")
+ }
+ // The old process drops the binder, which finds the replacement holding
+ // the caller it knew from the bindings file.
+ for range k.msgs {
+ }
+ k2, hello := p.binder()
+ if bs, _ := json.Marshal(hello["bindings"]); !strings.Contains(string(bs), `"caller":"single"`) {
+ t.Fatalf("the replacement's hello has no binding for the caller: %s", bs)
+ }
+ quick := make(chan error, 1)
+ go func() {
+ res, err := p.post(ctx, "/v1/quick")
+ if err == nil && res.StatusCode != http.StatusOK {
+ err = fmt.Errorf("status %d", res.StatusCode)
+ }
+ quick <- err
+ }()
+ select {
+ case err := <-quick:
+ t.Fatalf("a request was answered before the binder re-bound: %v", err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ p.bind(k2)
+ if err := <-quick; err != nil {
+ t.Fatalf("the held request: %v", err)
+ }
+
+ // The stream is still the old process's, which exits when it ends.
+ exited := make(chan error, 1)
+ go func() { exited <- cmd.Wait() }()
+ select {
+ case err := <-exited:
+ t.Fatalf("the old process exited under its stream: %v", err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ close(release)
+ if rest, err := io.ReadAll(body); err != nil || string(rest) != "b" {
+ t.Fatalf("stream end: %q %v", rest, err)
+ }
+ select {
+ case err := <-exited:
+ if err != nil {
+ t.Fatalf("the old process: %v; log:\n%s", err, p.log)
+ }
+ case <-time.After(20 * time.Second):
+ t.Fatalf("the old process did not exit; log:\n%s", p.log)
+ }
+ if res, err := p.post(ctx, "/v1/quick"); err != nil || res.StatusCode != http.StatusOK {
+ t.Fatalf("after the old process exited: %v %v", res, err)
+ }
+
+ // The replacement stops as any proxy does.
+ syscall.Kill(second, syscall.SIGTERM)
+ select {
+ case m := <-p.notify:
+ if m != "STOPPING=1" {
+ t.Fatalf("notified %q", m)
+ }
+ case <-time.After(20 * time.Second):
+ t.Fatal("the replacement did not stop")
+ }
+ if strings.Contains(p.log.String(), "sk-test") {
+ t.Fatal("the log carries the binding's variable")
+ }
+}
diff --git a/computer/modelproxy/main.go b/computer/modelproxy/main.go
index 3f780e45..c2065807 100644
--- a/computer/modelproxy/main.go
+++ b/computer/modelproxy/main.go
@@ -8,8 +8,9 @@
// is never in the session's process, files or environment.
//
// Profiles are JSON files (-profiles), read at start: a change takes a
-// restart, which keeps bindings (persist.go); -check validates them without
-// starting. Everything else is flags. Standard library only.
+// restart, which keeps bindings (persist.go) and, on SIGUSR2, leaves no gap
+// (handoff.go); -check validates them without starting. Everything else is
+// flags. One dependency beyond the standard library, for that handoff.
package main
import (
@@ -123,7 +124,7 @@ func parseFlags(args []string) (config, runMode, error) {
fs.StringVar(&cfg.identity, "identity", "cgroup", "how a caller is named: cgroup (<id> of its sp-runner-<id>.service unit) or single (every caller is "+singleCaller+")")
fs.StringVar(&cfg.bindingsFile, "bindings-file", "/run/oc-modelproxy/profile-bindings.json", "persisted bindings, without their variables (empty: do not persist)")
fs.DurationVar(&cfg.hold, "hold-timeout", 10*time.Second, "how long a request waits for its caller's credential, and then for a free upstream connection")
- fs.DurationVar(&cfg.drain, "drain-timeout", 630*time.Second, "on SIGTERM, how long in-flight streams may finish")
+ fs.DurationVar(&cfg.drain, "drain-timeout", 630*time.Second, "on SIGTERM or after a handoff, how long in-flight streams may finish")
fs.IntVar(&cfg.maxInflightPerCaller, "max-inflight-per-caller", 32, "concurrent requests (held ones included) one caller may have; more get 429 (0: no limit)")
fs.IntVar(&cfg.maxConnsPerCaller, "max-conns-per-caller", 128, "connections one caller may have open on the API socket; more are closed as accepted (0: no limit)")
fs.DurationVar(&cfg.wsIdle, "ws-idle-timeout", 5*time.Minute, "close a WebSocket idle this long between responses; it holds a caller's in-flight slot while open (0: never)")
@@ -163,30 +164,30 @@ func run(cfg config) error {
return err
}
+ h, err := newHandoff()
+ if err != nil {
+ return err
+ }
ls, err := activatedListeners()
if err != nil {
return err
}
- apiL, ctlL := ls["api"], ls["control"]
- if apiL == nil {
- if apiL, err = listenUnix(cfg.apiSocket); err != nil {
- return err
- }
+ apiL, err := h.listener("api", cfg.apiSocket, ls)
+ if err != nil {
+ return err
}
- if ctlL == nil {
- if ctlL, err = listenUnix(cfg.controlSocket); err != nil {
- return err
- }
+ ctlL, err := h.listener("control", cfg.controlSocket, ls)
+ if err != nil {
+ return err
}
srv.start(apiL, ctlL)
- sdNotify("READY=1")
+ if err := h.ready(); err != nil {
+ return err
+ }
logInfo("ready", "activated", len(ls) > 0, "profiles", len(ps.sorted), "bindings", srv.bindings.Len(), "startup_ms", ms(time.Since(started)))
- sig := make(chan os.Signal, 1)
- signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
- <-sig
- sdNotify("STOPPING=1")
- logInfo("draining", "streams", srv.proxy.activeStreams())
+ handedOff := waitToStop(h)
+ logInfo("draining", "streams", srv.proxy.activeStreams(), "handed_off", handedOff)
ctx, cancel := context.WithTimeout(context.Background(), cfg.drain)
defer cancel()
err = srv.shutdown(ctx)
@@ -194,6 +195,26 @@ func run(cfg config) error {
return err
}
+// waitToStop returns when the process is to drain and exit: on SIGTERM or
+// SIGINT, or once the replacement a SIGUSR2 asked for is ready (handoff.go).
+func waitToStop(h *handoff) (handedOff bool) {
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR2)
+ for {
+ select {
+ case s := <-sig:
+ if s == syscall.SIGUSR2 {
+ h.replace()
+ continue
+ }
+ sdNotify("STOPPING=1")
+ return false
+ case <-h.replaced():
+ return true
+ }
+ }
+}
+
// server wires the parts; tests build it with their own resolver and roots.
type server struct {
cfg config
@@ -320,12 +341,12 @@ func (s *server) poolEvent(p *profile, first bool) (eventMsg, bool) {
return e, true
}
-// shutdown: drop the binder's connection first (it reconnects to the next
-// instance at once), stop accepting, let in-flight streams and WebSocket
-// responses finish.
+// shutdown: leave the control socket to the next instance and drop the
+// binder's connection (it reconnects at once), stop accepting, let in-flight
+// streams and WebSocket responses finish.
func (s *server) shutdown(ctx context.Context) error {
- s.control.Close()
s.ctlL.Close()
+ s.control.Close()
s.proxy.drainWS(ctx, false) // tunnels close between responses while HTTP streams finish
err := s.http.Shutdown(ctx)
s.proxy.drainWS(ctx, true)