Files
magpie/internal/proc/output.go
T
yetoneandbaijiu666 5055349922 plugin: a host ended ends what its plugin started, at any depth (#5402)
A plugin host was ended with cmd.Process.Kill(), the host alone. A
plugin that starts a browser or a daemon (magpie-magicrew-auth's
headless Edge behind a WAF) left it running with no parent: 620
msedge.exe (6.8GB) and 382 temp profiles (57GB) in an hour on one
Windows machine. Bun's own job ends its direct children with it on
Windows, but lets their children out, so Edge's gpu/renderer processes
lived on. On macOS and Linux nothing ended them at all.

The host now starts as a proc.Tree (new Output.StartTree): a session of
its own on Unix, a job (kill on close) on Windows. host.kill kills the
tree; stop (after stopWait, so EndHosts, Restart, a moved proxy, an
update) and the line-too-long path both use it. A host that ends by
itself is swept by the tree's Wait: the Unix group is killed, the
Windows job closed. Nothing outside the host's own session or job is
signalled, so magpie's own process group is never reached.

Ported from baijiu666's fix/plugin-host-tree (a8172a1), which called
proc.End then Process.Kill. Reviewed against it:
- macOS/Linux: proc.End is SIGTERM to the host pid alone, followed at
  once by SIGKILL; host.js has no SIGTERM handler and the host was in
  magpie's own process group with no session of its own, so nothing it
  started was ended. Red on mote and WSL, same as main.
- Windows: endTree walks living parents, so it covers the killed host
  but not a host that ends on its own (crash, process.exit) or one that
  leaves when its input closes; those were red on Windows too.
- Its test was Windows-only and checked a direct child, which Bun's job
  already ends: the new test checks a grandchild, through a real host.

Run (TestHostEndedEndsWhatItsPluginStarted: a real Bun host whose
plugin starts a child that starts another; subtests stop / killed /
own end):
- origin/main 125fd93ec: red 3/3 on macOS (mote), Windows (win-run) and
  Linux (wsl-run).
- baijiu666's host.go: red 3/3 on macOS and Linux; on Windows red on
  stop and own end, green on killed.
- this change: green 3/3 on all three; -race green on mote and WSL with
  TestEndHostsLeavesNoChild, TestHostReapedWhileItsChildHoldsStdout and
  TestHostRunsAsMagpieBun.
- go test ./internal/plugin ./internal/proc: ok on macOS and Linux; on
  Windows ok except TestPiPackage, red the same at 125fd93ec (no `sh`
  on PATH there; #4115).
- go vet: darwin, linux, windows (./internal/... for windows). gofmt -l
  clean.
Broken by hand: the old and baijiu666 trees above are the fix taken out.
Not tried: a real headless Edge plugin (magpie-magicrew-auth) on
Windows; a plugin reading /dev/tty (the host has no controlling
terminal now, as every proc.Tree child).

Co-authored-by: baijiu666 <198813975+baijiu666@users.noreply.github.com>
2026-11-06 00:34:42 +08:00

140 lines
4.2 KiB
Go

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 <defunct>
// 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) {
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
}
if err != nil {
o.Out.Close()
o.Err.Close()
return nil, err
}
ended := make(chan struct{})
var werr error
go func() {
werr = waitFor()
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 <defunct> until magpie quits.
func StartReaped(cmd *exec.Cmd) error {
if err := cmd.Start(); err != nil {
return err
}
go cmd.Wait()
return nil
}