diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 0f183ea45..95bfb5644 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -297,7 +297,7 @@ 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. Before `magpie web` puts a new version in its own place (`Web.Wait`, `update.Reexec`), `plugin.EndHosts` stops every host, waits until each has been waited for, and starts none after: a host still running at the exec is a child nothing waits for after it, one `` magpie-bun per restart to update (#3285; `TestEndHostsLeavesNoChild`). +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. Before `magpie web` puts a new version in its own place (`Web.Wait`, `update.Reexec`), `plugin.EndHosts` stops every host, waits until each has been waited for, and starts none after: a host still running at the exec is a child nothing waits for after it, one `` magpie-bun per restart to update (#3285; `TestEndHostsLeavesNoChild`). The host is started as a `proc.Tree` (`Output.StartTree`): a session of its own on Unix, a job on Windows. Every way a host ends (`stop` after `stopWait`, a line too long, the host ending by itself) ends what its plugins started with it, at any depth: `host.kill` kills the tree, and the wait sweeps what a host that ended by itself left. A host killed alone left a plugin's headless Edge processes running with no parent (Bun's own job lets a child's children out of it on Windows), 620 msedge.exe in an hour on one machine (#5402, baijiu666). Nothing outside the host's session or job is reached, magpie's own process group included. `TestHostEndedEndsWhatItsPluginStarted` runs a real host whose plugin starts a child that starts another, on each of the three ends. 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`). diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 45a18176d..65e704e47 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -498,6 +498,9 @@ type host struct { // fake hosts, which have no child output *proc.Output waited func() error + // tree is the child with what it starts (Output.StartTree), ended + // together; nil in the fake hosts + tree *proc.Tree } // wait is the child's end: what Wait said, once it has ended and the @@ -923,8 +926,21 @@ func (h *host) stop() { case <-tick.C: } } + h.kill() +} + +// kill ends the host's child and every process it started: a plugin's +// headless browser or daemon outlived a host killed alone, with no parent +// to end it (620 msedge.exe and 57GB of temp profiles in an hour on one +// Windows machine, #5402). The tree is the host's session on Unix and its +// job on Windows (proc.StartTree), so nothing outside it is reached. +func (h *host) kill() { + if h.tree != nil { + h.tree.Kill() + return + } if h.cmd.Process != nil { - h.cmd.Process.Kill() + _ = h.cmd.Process.Kill() } } @@ -1094,7 +1110,8 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { output.Close() return nil, false, errHostsEnded } - waited, err := output.Start(cmd) + // in a tree of its own: what its plugins start is ended with it + tree, waited, err := output.StartTree(cmd) if err != nil { live.Unlock() return nil, false, err @@ -1116,6 +1133,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { addr: addr, output: output, waited: waited, + tree: tree, } live.hosts[h] = true live.Unlock() @@ -1265,9 +1283,7 @@ func (h *host) read(out io.Reader) { if errors.Is(err, errLineTooLong) { // a child that never ends a line: stop it rather than allocate h.fail(fmt.Errorf("the plugin host sent a line longer than %d bytes", h.lineLimit())) - if h.cmd.Process != nil { - _ = h.cmd.Process.Kill() - } + h.kill() break } if err != nil { diff --git a/internal/plugin/host_tree_test.go b/internal/plugin/host_tree_test.go new file mode 100644 index 000000000..1be2ab6d6 --- /dev/null +++ b/internal/plugin/host_tree_test.go @@ -0,0 +1,125 @@ +package plugin + +import ( + "context" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// The test binary stands in for a program a plugin starts (a headless +// browser, a daemon) when MAGPIE_HOST_TREE_CHILD names a file: it starts +// one of its own, as a browser starts its GPU and renderer processes, and +// sits; that one writes its pid to the file and sits too. +func init() { + if f := os.Getenv("MAGPIE_HOST_TREE_CHILD"); f != "" { + kid := exec.Command(os.Args[0]) + kid.Env = append(os.Environ(), "MAGPIE_HOST_TREE_CHILD=", "MAGPIE_HOST_TREE_GRANDCHILD="+f) + if kid.Start() != nil { + os.Exit(1) + } + time.Sleep(90 * time.Second) + os.Exit(0) + } + if f := os.Getenv("MAGPIE_HOST_TREE_GRANDCHILD"); f != "" { + _ = os.WriteFile(f+".tmp", []byte(strconv.Itoa(os.Getpid())), 0o600) + _ = os.Rename(f+".tmp", f) + time.Sleep(90 * time.Second) + os.Exit(0) + } +} + +// A plugin host ended ends what its plugin started, at any depth: a host +// killed alone left a plugin's headless Edge's processes running with no +// parent (Bun ends its own children with it on Windows, through a job they +// can start others out of, but not theirs), one more set for +// every host ended (620 msedge.exe and 57GB of temp profiles in an hour on +// one Windows machine, #5402, found and first fixed by baijiu666). Each way +// a host ends is tried: stopped (Restart, as a proxy change or an update +// does) and leaving as its input closes, stopped and killed once stopWait +// has passed (a line too long kills it the same way, host.kill), and the +// host ending by itself. +func TestHostEndedEndsWhatItsPluginStarted(t *testing.T) { + for _, how := range []string{"stop", "killed", "own end"} { + t.Run(how, func(t *testing.T) { + sandbox(t) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + pidFile := filepath.Join(t.TempDir(), "child.pid") + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + q := func(s string) string { b, _ := json.Marshal(s); return string(b) } + spawn := "Bun.spawn({ cmd: [" + q(self) + "], env: { ...process.env, MAGPIE_HOST_TREE_CHILD: " + q(pidFile) + " }, stdout: \"ignore\", stderr: \"ignore\" })\n" + if how == "killed" { + // a host that doesn't leave when its input closes, so + // stop kills it once stopWait has passed + spawn += "process.exit = () => {}\nsetInterval(() => {}, 1000)\n" + } + if how == "own end" { + spawn += "setTimeout(() => process.exit(3), 500)\n" + } + b, err := os.ReadFile("testdata/fake/index.js") + if err != nil { + t.Fatal(err) + } + js := filepath.Join(t.TempDir(), "index.js") + if err := os.WriteFile(js, append([]byte(spawn), b...), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Add(ctx, js); err != nil { + t.Fatal(err) + } + _, _ = Providers(ctx) // the host may end under it ("own end") + kid := readPID(t, pidFile) + t.Cleanup(func() { endPID(kid) }) + + hostMu.Lock() + h := current + hostMu.Unlock() + switch how { + case "stop", "killed": + if h == nil { + t.Fatal("no host") + } + Restart() + } + if h != nil { + select { + case <-h.dead: + case <-time.After(30 * time.Second): + t.Fatal("the host isn't ended 30s on") + } + } + until := time.Now().Add(15 * time.Second) + for living(kid) { + if time.Now().After(until) { + t.Fatalf("the process %d the plugin's child started outlived the host (%s)", kid, how) + } + time.Sleep(50 * time.Millisecond) + } + }) + } +} + +// readPID waits for the plugin's child to write its pid down. +func readPID(t *testing.T, file string) int { + t.Helper() + until := time.Now().Add(30 * time.Second) + for time.Now().Before(until) { + if b, err := os.ReadFile(file); err == nil { + if pid, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && pid > 0 { + return pid + } + } + time.Sleep(50 * time.Millisecond) + } + t.Fatal("the plugin never started its child") + return 0 +} diff --git a/internal/plugin/host_tree_unix_test.go b/internal/plugin/host_tree_unix_test.go new file mode 100644 index 000000000..035e92207 --- /dev/null +++ b/internal/plugin/host_tree_unix_test.go @@ -0,0 +1,26 @@ +//go:build !windows + +package plugin + +import ( + "os/exec" + "strconv" + "strings" + "syscall" +) + +// living says whether pid runs: one ended and not yet reaped by whoever +// took it in counts as gone. +func living(pid int) bool { + if syscall.Kill(pid, 0) != nil { + return false + } + out, err := exec.Command("ps", "-o", "stat=", "-p", strconv.Itoa(pid)).Output() + if err != nil { + return false + } + s := strings.TrimSpace(string(out)) + return s != "" && !strings.HasPrefix(s, "Z") +} + +func endPID(pid int) { _ = syscall.Kill(pid, syscall.SIGKILL) } diff --git a/internal/plugin/host_tree_windows_test.go b/internal/plugin/host_tree_windows_test.go new file mode 100644 index 000000000..6eabd2e1a --- /dev/null +++ b/internal/plugin/host_tree_windows_test.go @@ -0,0 +1,27 @@ +//go:build windows + +package plugin + +import "golang.org/x/sys/windows" + +// living says whether pid is still running. +func living(pid int) bool { + const stillActive = 259 // STILL_ACTIVE + h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid)) + if err != nil { + return false + } + defer windows.CloseHandle(h) + var code uint32 + if err := windows.GetExitCodeProcess(h, &code); err != nil { + return false + } + return code == stillActive +} + +func endPID(pid int) { + if h, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, uint32(pid)); err == nil { + _ = windows.TerminateProcess(h, 1) + _ = windows.CloseHandle(h) + } +} diff --git a/internal/proc/output.go b/internal/proc/output.go index ce8e366fd..860a1382f 100644 --- a/internal/proc/output.go +++ b/internal/proc/output.go @@ -68,7 +68,29 @@ func (o *Output) Close() { // 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() + return o.start(cmd, cmd.Start, cmd.Wait) +} + +// StartTree is Start for a command started as a Tree (StartTree): what +// it starts in turn is ended with it by the Tree's Kill, and, once it has +// ended on its own, by the wait. A plugin host ended alone left the +// headless browser its plugin had started running with no parent, one +// more for every host ended (620 msedge.exe on one Windows machine, +// #5402). +func (o *Output) StartTree(cmd *exec.Cmd) (*Tree, func() error, error) { + var t *Tree + wait, err := o.start(cmd, func() (err error) { + t, err = StartTree(cmd) + return err + }, func() error { return t.Wait() }) + if err != nil { + return nil, nil, err + } + return t, wait, nil +} + +func (o *Output) start(cmd *exec.Cmd, start, waitFor func() error) (wait func() error, err error) { + err = start() for _, w := range o.ws { w.Close() // the command has its own copies } @@ -80,7 +102,7 @@ func (o *Output) Start(cmd *exec.Cmd) (wait func() error, err error) { ended := make(chan struct{}) var werr error go func() { - werr = cmd.Wait() + werr = waitFor() grace := time.NewTimer(OutputGrace) defer grace.Stop() for _, s := range []struct {