diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index f1c680063..d99cf2e06 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -283,7 +283,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. +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`). 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/gui/web.go b/internal/gui/web.go index 25081367f..12ff3c8fd 100644 --- a/internal/gui/web.go +++ b/internal/gui/web.go @@ -21,6 +21,7 @@ import ( "github.com/klauspost/compress/gzhttp" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/plugin" "github.com/yetone/magpie/internal/update" ) @@ -141,6 +142,10 @@ func (w *Web) Wait() error { if err != nil { return err } + // the plugin hosts end, waited for, first: one still running at the + // exec is a child nothing waits for after it, under this + // pid from then on (#3285) + plugin.EndHosts() return update.Reexec(exe, os.Args[1:], append(os.Environ(), webRunKey+"="+w.key)) } diff --git a/internal/plugin/host.go b/internal/plugin/host.go index acd20571f..e13d0ad15 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -518,6 +518,49 @@ func (h *host) wait() error { // at once and closes the pipe a moment later, which ends the reader too. func (h *host) reap() { h.fail(quitErr(h.wait())) + live.Lock() + delete(live.hosts, h) + live.Unlock() +} + +// live are the hosts started and not yet reaped, the retired ones on their +// way out among them. +var live = struct { + sync.Mutex + hosts map[*host]bool + // ended is set by EndHosts: no host starts after it + ended bool +}{hosts: map[*host]bool{}} + +// errHostsEnded is a host asked for once EndHosts has run. +var errHostsEnded = errors.New("magpie is restarting; the plugins are back in a moment") + +// EndHosts stops every plugin host, waits until each has been waited for, +// and starts none after: what magpie runs before it puts a new version in +// its own place (update.Reexec). A host still running at the exec was one +// nothing waited for after it, so each restart to update (magpie web's +// AutoRestart) left one magpie-bun under magpie's pid for as long +// as it ran (#3285, found by skygunner and AAEE86; acezan on Discord saw +// 57 after 47 hours as a systemd service). +func EndHosts() { + live.Lock() + live.ended = true + hs := make([]*host, 0, len(live.hosts)) + for h := range live.hosts { + hs = append(hs, h) + } + live.Unlock() + hostMu.Lock() + current = nil + hostMu.Unlock() + var wg sync.WaitGroup + for _, h := range hs { + wg.Go(func() { + h.stop() + _ = h.wait() + }) + } + wg.Wait() } // quitErr is the error of a host whose child ended with err. @@ -1040,8 +1083,16 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { if err != nil { return nil, false, err } + // started and counted live under one lock, so EndHosts misses none + live.Lock() + if live.ended { + live.Unlock() + output.Close() + return nil, false, errHostsEnded + } waited, err := output.Start(cmd) if err != nil { + live.Unlock() return nil, false, err } hctx, hcancel := context.WithCancel(context.Background()) @@ -1062,6 +1113,8 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { output: output, waited: waited, } + live.hosts[h] = true + live.Unlock() go func() { drainStderr(output.Err) output.ErrRead() diff --git a/internal/plugin/reap_linux_test.go b/internal/plugin/reap_linux_test.go index 24e235459..53d93ad72 100644 --- a/internal/plugin/reap_linux_test.go +++ b/internal/plugin/reap_linux_test.go @@ -115,3 +115,70 @@ func killSleeps(secs string) { } } } + +// EndHosts, which magpie runs before it puts a new version in its place, +// returns with every host ended and waited for, and starts none after: a +// host left running +// at the exec was a magpie-bun under magpie's pid from then on +// (#3285). +func TestEndHostsLeavesNoChild(t *testing.T) { + sandbox(t) + t.Cleanup(func() { + live.Lock() + live.ended = false + live.Unlock() + }) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := Providers(ctx); err != nil { + t.Fatal(err) + } + if len(childrenNamed("bun")) == 0 { + t.Fatal("no host running to end") + } + EndHosts() + if c := childrenNamed("bun"); len(c) > 0 { + t.Fatalf("children left once EndHosts returned: %v", c) + } + hostMu.Lock() + _, err := getLocked(ctx) + hostMu.Unlock() + if err == nil { + t.Fatal("a host started after EndHosts") + } + if c := childrenNamed("bun"); len(c) > 0 { + t.Fatalf("children after a host was asked for: %v", c) + } +} + +// childrenNamed lists this process's children, running or , +// whose name holds name. +func childrenNamed(name string) []string { + me := strconv.Itoa(os.Getpid()) + ents, _ := os.ReadDir("/proc") + var c []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:]) + comm := s[strings.IndexByte(s, '(')+1 : i] + if len(f) > 1 && f[1] == me && strings.Contains(comm, name) { + c = append(c, e.Name()+" "+f[0]+" "+comm) + } + } + return c +}