diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index e773d2004..f1c680063 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -283,6 +283,8 @@ The host is told where magpie's gateway is as `MAGPIE_ADDR` (`hostAddr` in [`hos What a plugin writes with `console.log`, `console.warn` and the rest goes to the host's stderr, which magpie logs a line at a time (`drainStderr` in [`host.go`](../../internal/plugin/host.go)). A line over 4 MiB ends the logging: magpie logs that it did, and reads and drops the rest, so the host never blocks on a full pipe. Before, nothing read the pipe after such a line: on Windows the host hung on its next write, and on Linux Bun kept everything written after it in memory. +The host is waited for the moment it ends, not when its stdout reaches EOF (`reap` in [`host.go`](../../internal/plugin/host.go), `proc.Output` in [`output.go`](../../internal/proc/output.go)). A program a plugin started that kept a copy of the host's stdout (a `Bun.spawn` given `Bun.stdout`, a daemon it left running) held that pipe open past the host's end, so the reader never saw EOF, the only `cmd.Wait` never ran, and every host stopped (a restart, a moved proxy) stayed a `` magpie-bun under magpie until it quit (acezan on Discord, a Linux systemd service). Once the host has ended, the reader has `proc.OutputGrace` (2s) to read its last lines; then its stdout and stderr are closed under their readers and the host fails as one that quit. Every command magpie starts elsewhere is waited for too: one it leaves running goes through `proc.StartReaped`, never `Process.Release`, which doesn't reap on Unix (`TestEveryStartedCommandIsWaited` in [`reap_test.go`](../../internal/proc/reap_test.go)). `TestHostReapedWhileItsChildHoldsStdout` (Linux) runs a real host whose plugin holds its stdout that way and counts this process's `` children after each Restart. + A plugin's account whose sign-in its vendor refused (`lapsed`, or an allowance read saying so) keeps Sign in again and Remove on its row, whether it is in use or the agent's own (`signedOut` in `renderAccounts`, `app.js`). A plugin sign-in's page is opened once. An `authorize` result may say `opened: true` (not OpenCode's field): the plugin's own CLI opened the page already. Grok's `grok login --device-auth` does this on macOS and Windows, where nothing turns it off, and magpie's opening it too showed two pages (andyfmyth on X; plugin 0.1.17, which on other systems gives grok a `BROWSER` that opens nothing instead). `host.js` passes it on as `Authorization.Opened`, then `SignInState.Opened`, and the desktop's `/api/plugin-signin`, `magpie plugin login` and the window in a browser tab (`startPluginSignIn`, and `followSignIn` after an install) then open nothing; the page's link is still shown (`TestPluginSignInPageOpensOnce`, `plugin-signin-opened.test.cjs`). diff --git a/internal/codexrelay/relay.go b/internal/codexrelay/relay.go index f64888198..527155dfe 100644 --- a/internal/codexrelay/relay.go +++ b/internal/codexrelay/relay.go @@ -84,10 +84,9 @@ func Start(addr string, pids []int) error { } cmd := proc.Command(exe, Command, "--addr", addr, "--pids", strings.Join(ids, ",")) detach(cmd) - if err := cmd.Start(); err != nil { - return err - } - return cmd.Process.Release() + // reaped when it ends while magpie runs: a released one stayed + // until magpie quit + return proc.StartReaped(cmd) } // Main is `magpie codex-relay --addr host:port --pids 1,2`, serving h. diff --git a/internal/plugin/host.go b/internal/plugin/host.go index aa2abac66..acd20571f 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -29,6 +29,7 @@ import ( "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/lastgood" "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/settings" ) @@ -491,6 +492,40 @@ type host struct { proxyAt time.Time // addr is the gateway's address the host was told (hostAddr) addr string + // output is the child's stdout and stderr, read apart from its Wait, + // and waited gives what that Wait said; both are nil in the tests' + // fake hosts, which have no child + output *proc.Output + waited func() error +} + +// wait is the child's end: what Wait said, once it has ended and the +// reader is done with its stdout. +func (h *host) wait() error { + if h.waited == nil { + return h.cmd.Wait() + } + return h.waited() +} + +// reap ends the host the moment its child ends, not once its stdout +// does. A program the host started that kept the host's stdout (a +// plugin's Bun.spawn given a copy of fd 1, a daemon it left behind) held +// the pipe open past the host's end, so the reader never reached EOF, +// the child was never waited for, and every host stopped left a +// magpie-bun behind until magpie quit (acezan on Discord: 57 +// after 47 hours as a systemd service). proc.Output waits for the child +// at once and closes the pipe a moment later, which ends the reader too. +func (h *host) reap() { + h.fail(quitErr(h.wait())) +} + +// quitErr is the error of a host whose child ended with err. +func quitErr(err error) error { + if err == nil { + err = errors.New("the plugin host quit") + } + return fmt.Errorf("the plugin host quit: %v", err) } // lineLimit is the longest line this host reads from the child. @@ -999,17 +1034,16 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { if err != nil { return nil, false, err } - out, err := cmd.StdoutPipe() + // stdout and stderr are read apart from Wait (proc.Output), so the + // child is reaped when it ends, whatever holds a copy of them + output, err := proc.NewOutput(cmd) if err != nil { return nil, false, err } - stderr, err := cmd.StderrPipe() + waited, err := output.Start(cmd) if err != nil { return nil, false, err } - if err := cmd.Start(); err != nil { - return nil, false, err - } hctx, hcancel := context.WithCancel(context.Background()) h := &host{ cmd: cmd, in: in, @@ -1025,10 +1059,16 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { proxy: proxy, proxyAt: time.Now(), addr: addr, + output: output, + waited: waited, } - go drainStderr(stderr) + go func() { + drainStderr(output.Err) + output.ErrRead() + }() - go h.read(out) + go h.read(output.Out) + go h.reap() go h.writerLoop() go h.ctrlLoop() generation.Add(1) @@ -1132,11 +1172,10 @@ func (h *host) read(out io.Reader) { break } } - err := h.cmd.Wait() - if err == nil { - err = errors.New("the plugin host quit") + if h.output != nil { + h.output.OutRead() } - h.fail(fmt.Errorf("the plugin host quit: %v", err)) + h.fail(quitErr(h.wait())) } var ( diff --git a/internal/plugin/reap_linux_test.go b/internal/plugin/reap_linux_test.go new file mode 100644 index 000000000..24e235459 --- /dev/null +++ b/internal/plugin/reap_linux_test.go @@ -0,0 +1,117 @@ +package plugin + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +// A plugin host is reaped when it ends, while a program the plugin started +// still holds its stdout. The host was waited for only once its stdout +// reached EOF, which such a program put off for its whole life, so every +// host stopped (a Restart, a proxy change) left a magpie-bun +// under magpie until magpie quit (acezan on Discord: 57 after 47 hours as +// a systemd service on Linux). +func TestHostReapedWhileItsChildHoldsStdout(t *testing.T) { + sandbox(t) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + // a sleep of a length no other test uses, to find and end it after + const hold = "61.25" + t.Cleanup(func() { killSleeps(hold) }) + + b, err := os.ReadFile("testdata/fake/index.js") + if err != nil { + t.Fatal(err) + } + js := filepath.Join(t.TempDir(), "index.js") + start := `Bun.spawn({ cmd: ["sleep", "` + hold + `"], stdout: Bun.stdout })` + "\n" + if err := os.WriteFile(js, append([]byte(start), b...), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Add(ctx, js); err != nil { + t.Fatal(err) + } + for i := range 3 { + if _, err := Providers(ctx); err != nil { + t.Fatalf("round %d: %v", i, err) + } + hostMu.Lock() + h := current + hostMu.Unlock() + if h == nil { + t.Fatalf("round %d: no host", i) + } + Restart() + select { + case <-h.dead: + case <-time.After(15 * time.Second): + t.Fatalf("round %d: the host isn't marked ended 15s after Restart", i) + } + // the host is waited for as soon as it ends, not when the sleep + // lets go of its stdout + until := time.Now().Add(15 * time.Second) + for { + z := defunctChildren() + if len(z) == 0 { + break + } + if time.Now().After(until) { + t.Fatalf("round %d: %d defunct children 15s after Restart: %v", i, len(z), z) + } + time.Sleep(50 * time.Millisecond) + } + } +} + +// defunctChildren lists this process's children that have ended and not +// been waited for. +func defunctChildren() []string { + me := strconv.Itoa(os.Getpid()) + ents, _ := os.ReadDir("/proc") + var z []string + for _, e := range ents { + if _, err := strconv.Atoi(e.Name()); err != nil { + continue + } + b, err := os.ReadFile("/proc/" + e.Name() + "/stat") + if err != nil { + continue + } + s := string(b) + i := strings.LastIndexByte(s, ')') + if i < 0 || i+2 > len(s) { + continue + } + f := strings.Fields(s[i+2:]) + if len(f) > 1 && f[0] == "Z" && f[1] == me { + z = append(z, e.Name()+" "+s[strings.IndexByte(s, '(')+1:i]) + } + } + return z +} + +// killSleeps ends every `sleep secs` running. +func killSleeps(secs string) { + ents, _ := os.ReadDir("/proc") + for _, e := range ents { + pid, err := strconv.Atoi(e.Name()) + if err != nil { + continue + } + b, err := os.ReadFile("/proc/" + e.Name() + "/cmdline") + if err != nil { + continue + } + args := bytes.Split(bytes.TrimRight(b, "\x00"), []byte{0}) + if len(args) == 2 && filepath.Base(string(args[0])) == "sleep" && string(args[1]) == secs { + _ = syscall.Kill(pid, syscall.SIGKILL) + } + } +} diff --git a/internal/proc/output.go b/internal/proc/output.go new file mode 100644 index 000000000..ce8e366fd --- /dev/null +++ b/internal/proc/output.go @@ -0,0 +1,117 @@ +package proc + +import ( + "os" + "os/exec" + "sync" + "time" +) + +// Output is a command's stdout and stderr, as pipes read apart from its +// Wait. cmd.StdoutPipe's end is closed by Wait, so a command whose output +// is read through it can only be waited for once that output has been +// read to the end, and the end is not the command's own: whatever it +// started kept a copy of its stdout (a program a plugin started, a daemon +// it left behind), so the reader never reached EOF after the command +// ended, the command was never waited for, and it stayed a +// child of magpie until magpie quit (acezan on Discord: 57 magpie-bun +// after 47 hours). Output's command is waited for the moment it ends; +// its readers then have OutputGrace to read what it wrote last, and the +// pipes are closed, which ends their reads. +type Output struct { + // Out and Err are the ends magpie reads. + Out, Err *os.File + ws []*os.File + outDone chan struct{} + errDone chan struct{} + outOnce sync.Once + errOnce sync.Once +} + +// OutputGrace is how long the readers of a command that has ended have to +// read what it wrote last, before its Output is closed under them. +var OutputGrace = 2 * time.Second + +// NewOutput gives cmd's stdout and stderr each a pipe of an Output. +func NewOutput(cmd *exec.Cmd) (*Output, error) { + or, ow, err := os.Pipe() + if err != nil { + return nil, err + } + er, ew, err := os.Pipe() + if err != nil { + or.Close() + ow.Close() + return nil, err + } + cmd.Stdout, cmd.Stderr = ow, ew + return &Output{Out: or, Err: er, ws: []*os.File{ow, ew}, + outDone: make(chan struct{}), errDone: make(chan struct{})}, nil +} + +// OutRead says Out's reader has read to its end. +func (o *Output) OutRead() { o.outOnce.Do(func() { close(o.outDone) }) } + +// ErrRead says Err's reader has read to its end. +func (o *Output) ErrRead() { o.errOnce.Do(func() { close(o.errDone) }) } + +// Close closes the ends magpie reads, for an Output whose command +// isn't started. +func (o *Output) Close() { + for _, f := range append(o.ws, o.Out, o.Err) { + f.Close() + } +} + +// Start starts cmd, whose output o is, and waits for it the moment it +// ends. wait gives what Wait said once the command has ended and its +// output has been read or closed; any number of goroutines can call it, +// any number of times. When cmd doesn't start, o is closed. +func (o *Output) Start(cmd *exec.Cmd) (wait func() error, err error) { + err = cmd.Start() + for _, w := range o.ws { + w.Close() // the command has its own copies + } + if err != nil { + o.Out.Close() + o.Err.Close() + return nil, err + } + ended := make(chan struct{}) + var werr error + go func() { + werr = cmd.Wait() + grace := time.NewTimer(OutputGrace) + defer grace.Stop() + for _, s := range []struct { + done chan struct{} + f *os.File + }{{o.outDone, o.Out}, {o.errDone, o.Err}} { + select { + case <-s.done: + case <-grace.C: + // something the command started still holds this + // pipe: its reader is stopped rather than left waiting + grace.Reset(0) + } + s.f.Close() + } + close(ended) + }() + return func() error { + <-ended + return werr + }, nil +} + +// StartReaped starts cmd, which magpie leaves running (it outlives magpie +// or ends on its own), and waits for it in the background, so it is +// reaped whenever it ends. Process.Release doesn't reap on Unix: a child +// released and ended stays until magpie quits. +func StartReaped(cmd *exec.Cmd) error { + if err := cmd.Start(); err != nil { + return err + } + go cmd.Wait() + return nil +} diff --git a/internal/proc/output_unix_test.go b/internal/proc/output_unix_test.go new file mode 100644 index 000000000..6aed12b3b --- /dev/null +++ b/internal/proc/output_unix_test.go @@ -0,0 +1,86 @@ +//go:build !windows + +package proc + +import ( + "io" + "syscall" + "testing" + "time" +) + +// A command is waited for when it ends, while what it started still holds +// its output: read to EOF first, its Wait waited for the program it left +// behind, and it stayed all that time. +func TestOutputWaitsPastWhatHoldsIt(t *testing.T) { + old := OutputGrace + OutputGrace = 200 * time.Millisecond + t.Cleanup(func() { OutputGrace = old }) + + cmd := Command("sh", "-c", "sleep 30 & sleep 30 >&2 & echo hi") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + o, err := NewOutput(cmd) + if err != nil { + t.Fatal(err) + } + wait, err := o.Start(cmd) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }) + got := make(chan string, 1) + go func() { + b, _ := io.ReadAll(o.Out) + o.OutRead() + got <- string(b) + }() + go func() { + _, _ = io.Copy(io.Discard, o.Err) + o.ErrRead() + }() + waited := make(chan error, 1) + go func() { waited <- wait() }() + select { + case err := <-waited: + if err != nil { + t.Fatalf("wait: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("the command wasn't waited for in 10s while what it started held its output") + } + // waited, so reaped: the process is gone, not a zombie + if err := syscall.Kill(cmd.Process.Pid, 0); err != syscall.ESRCH { + t.Fatalf("the shell is still there after wait: %v", err) + } + select { + case s := <-got: + if s != "hi\n" { + t.Fatalf("read %q, want what it wrote", s) + } + case <-time.After(5 * time.Second): + t.Fatal("the read didn't end once its pipe was closed") + } +} + +// What a command writes as it ends is read whole before its pipe is closed. +func TestOutputKeepsTheLastLines(t *testing.T) { + cmd := Command("sh", "-c", "i=0; while [ $i -lt 2000 ]; do echo line $i; i=$((i+1)); done") + o, err := NewOutput(cmd) + if err != nil { + t.Fatal(err) + } + wait, err := o.Start(cmd) + if err != nil { + t.Fatal(err) + } + go func() { _, _ = io.Copy(io.Discard, o.Err); o.ErrRead() }() + time.Sleep(200 * time.Millisecond) // it has ended, its output still unread + b, _ := io.ReadAll(o.Out) + o.OutRead() + if err := wait(); err != nil { + t.Fatal(err) + } + if n := len(b); n < 2000*len("line 0\n") { + t.Fatalf("read %d bytes of what it wrote", n) + } +} diff --git a/internal/proc/reap_test.go b/internal/proc/reap_test.go new file mode 100644 index 000000000..2ab2f468a --- /dev/null +++ b/internal/proc/reap_test.go @@ -0,0 +1,138 @@ +package proc + +import ( + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "strings" + "testing" +) + +// TestEveryStartedCommandIsWaited: a command magpie starts is waited for, +// in the function that starts it: Wait is what reaps it on Unix, and +// one not waited for stays a child of magpie until magpie quits +// (acezan on Discord: 57 magpie-bun after 47 hours). Process.Release +// doesn't reap on Unix, so it is no way out: a command magpie leaves +// running goes through StartReaped. The check is by name: in each +// function, every x.Start() needs an x.Wait() (or x handed to a waiter, +// as Output's Start is, or kept in a struct whose stop waits) beside it. +func TestEveryStartedCommandIsWaited(t *testing.T) { + root, _ := filepath.Abs(filepath.Join("..", "..")) + fset := token.NewFileSet() + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if path != root && (strings.HasPrefix(d.Name(), ".") || d.Name() == "node_modules" || d.Name() == "testdata") { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + b, err := os.ReadFile(path) + if err != nil { + return err + } + if !strings.Contains(string(b), ".Start()") && !strings.Contains(string(b), ".Release()") { + return nil + } + f, err := parser.ParseFile(fset, path, b, 0) + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + for _, decl := range f.Decls { + name := "?" + switch d := decl.(type) { + case *ast.FuncDecl: + name = d.Name.Name + case *ast.GenDecl: + // a var holding a func, as tests swap in a fake + if vs, ok := d.Specs[0].(*ast.ValueSpec); ok && len(vs.Names) > 0 { + name = vs.Names[0].Name + } + } + starts := map[string]token.Pos{} + waited := map[string]bool{} + ast.Inspect(decl, func(n ast.Node) bool { + // handed to what owns it from here: a struct's field (whose + // stop waits), a waiter's argument (Output's Start, + // StartReaped) + switch n := n.(type) { + case *ast.KeyValueExpr: + waited[exprName(n.Value)] = true + case *ast.AssignStmt: + for _, r := range n.Rhs { + waited[exprName(r)] = true + } + } + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + recv := exprName(sel.X) + switch { + case sel.Sel.Name == "Start" && len(call.Args) == 0 && isCmd(recv): + if _, ok := starts[recv]; !ok { + starts[recv] = call.Pos() + } + case sel.Sel.Name == "Wait" && len(call.Args) == 0: + waited[recv] = true + case sel.Sel.Name == "Release" && len(call.Args) == 0 && strings.HasSuffix(recv, ".Process"): + t.Errorf("%s:%d: %s releases %s rather than waiting for it; use proc.StartReaped", rel, fset.Position(call.Pos()).Line, name, recv) + } + for _, a := range call.Args { + // handed to a waiter: Output's Start, StartReaped, a + // helper that owns the command from here + waited[exprName(a)] = true + } + return true + }) + for recv, pos := range starts { + if !waited[recv] { + p := fset.Position(pos) + t.Errorf("%s:%d: %s starts %s and never waits for it", rel, p.Line, name, recv) + } + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +// exprName is an expression as written: a name, or a selector of names. +func exprName(e ast.Expr) string { + switch e := e.(type) { + case *ast.Ident: + return e.Name + case *ast.SelectorExpr: + return exprName(e.X) + "." + e.Sel.Name + case *ast.StarExpr: + return exprName(e.X) + case *ast.UnaryExpr: + return exprName(e.X) + case *ast.ParenExpr: + return exprName(e.X) + } + return "" +} + +// isCmd says whether a receiver's name is a command's: Start is also a +// timer's, a server's and a span's, which this check isn't about. +func isCmd(recv string) bool { + last := recv[strings.LastIndex(recv, ".")+1:] + l := strings.ToLower(last) + return l == "cmd" || strings.HasSuffix(l, "cmd") || l == "c" || l == "proc" || l == "command" +} diff --git a/internal/tui/keep.go b/internal/tui/keep.go index da7cb4c4c..5df1c809f 100644 --- a/internal/tui/keep.go +++ b/internal/tui/keep.go @@ -106,12 +106,12 @@ func serveInBackground() (int, string, error) { cmd := proc.Command(exe, "serve") cmd.Stdout, cmd.Stderr = f, f detach(cmd) - if err := cmd.Start(); err != nil { + // reaped if it ends while this process runs: a released one stayed + // until it quit + if err := proc.StartReaped(cmd); err != nil { return 0, "", err } - pid := cmd.Process.Pid - cmd.Process.Release() - return pid, log, nil + return cmd.Process.Pid, log, nil } // wslHere: this Linux is a WSL distro. diff --git a/internal/uninstall/uninstall.go b/internal/uninstall/uninstall.go index 21b801576..65aced3fa 100644 --- a/internal/uninstall/uninstall.go +++ b/internal/uninstall/uninstall.go @@ -299,10 +299,7 @@ func AfterExit(pid int, wait time.Duration) *Report { var startAfter = func(cmd *exec.Cmd) error { cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil detach(cmd) - if err := cmd.Start(); err != nil { - return err - } - return cmd.Process.Release() + return proc.StartReaped(cmd) } // DataAfterExit starts `magpie uninstall --data-after `, which diff --git a/internal/update/proc_windows.go b/internal/update/proc_windows.go index 97592366a..20a0ce26d 100644 --- a/internal/update/proc_windows.go +++ b/internal/update/proc_windows.go @@ -45,10 +45,7 @@ func Reexec(exe string, args, env []string) error { cmd := proc.Command(exe, args...) cmd.Env = env cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr - if err := cmd.Start(); err != nil { - return err - } - return cmd.Process.Release() + return proc.StartReaped(cmd) } // trialStart starts path suspended and ends it at once: Windows checks a diff --git a/internal/update/update.go b/internal/update/update.go index 8bf9b709d..5d6f6f52d 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -490,7 +490,7 @@ func runAfterExit(pid int, command string) error { cmd := proc.Command("/bin/sh", "-c", script) cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil detach(cmd) - return cmd.Start() + return proc.StartReaped(cmd) } // relaunchOpen is the open command Relaunch runs for bundle. -n asks @@ -1287,7 +1287,7 @@ func OpenBeside(bundle string, window, quiet bool) error { cmd := proc.Command("/bin/sh", "-c", retried(openBeside(bundle, window, quiet), openWaits)) cmd.Stdin, cmd.Stdout, cmd.Stderr = nil, nil, nil detach(cmd) - return cmd.Start() + return proc.StartReaped(cmd) } // openBeside is the open command OpenBeside runs for bundle.