diff --git a/internal/cli/web_cli.go b/internal/cli/web_cli.go index 10a6b485d..24281079b 100644 --- a/internal/cli/web_cli.go +++ b/internal/cli/web_cli.go @@ -1,6 +1,7 @@ package cli import ( + "context" "fmt" "net" "net/url" @@ -230,6 +231,7 @@ func serveCmd(args []string) error { } } proc.UserPath() // as magpie web's (#3803) + proc.KeepReaping(context.Background()) if web == "" { return serve() } diff --git a/internal/proc/orphans_linux.go b/internal/proc/orphans_linux.go new file mode 100644 index 000000000..835f4f4a1 --- /dev/null +++ b/internal/proc/orphans_linux.go @@ -0,0 +1,114 @@ +package proc + +import ( + "bytes" + "context" + "os" + "strconv" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/unix" +) + +// Where magpie is PID 1 (a container running `magpie serve`), or a child +// subreaper, the processes its children leave behind are adopted by it: +// an agent's CLI that ends with its MCP servers (uv, node, npm, a graph +// indexer) still running or just ended leaves them to magpie, and nothing +// in magpie waits for a process it never started. They stayed +// children of `magpie serve` until it restarted (254 after 7 days, +// Kling__Lab on X). cmd.Wait reaps the ones magpie starts; this reaps the +// rest. + +// OrphanEvery is how often the zombies adopted by magpie are looked for. +// One that was already a zombie at the previous look is nobody's to wait +// for: every command magpie starts is waited for the moment it ends. +var OrphanEvery = 5 * time.Second + +// adopts says whether processes whose parent ends become magpie's. +func adopts() bool { + if os.Getpid() == 1 { + return true + } + // the answer is written through the pointer, not returned + var v int32 + _, _, e := syscall.RawSyscall6(syscall.SYS_PRCTL, unix.PR_GET_CHILD_SUBREAPER, uintptr(unsafe.Pointer(&v)), 0, 0, 0, 0) + return e == 0 && v != 0 +} + +// KeepReaping reaps the zombies magpie has adopted, until ctx ends. It +// does nothing where magpie adopts none. +func KeepReaping(ctx context.Context) { + if !adopts() { + return + } + go func() { + tick := time.NewTicker(OrphanEvery) + defer tick.Stop() + seen := map[int]uint64{} + for { + select { + case <-ctx.Done(): + return + case <-tick.C: + seen = reapOrphans(seen) + } + } + }() +} + +// reapOrphans reaps the zombie children that were zombies at the last +// look too (seen: pid and start time), and answers those that are now. +func reapOrphans(seen map[int]uint64) map[int]uint64 { + now := map[int]uint64{} + me := os.Getpid() + ents, err := os.ReadDir("/proc") + if err != nil { + return seen + } + for _, e := range ents { + pid, err := strconv.Atoi(e.Name()) + if err != nil { + continue + } + b, err := os.ReadFile("/proc/" + e.Name() + "/stat") + if err != nil { + continue + } + state, ppid, start, ok := zombieStat(b) + if !ok || state != 'Z' || ppid != me { + continue + } + if seen[pid] == start { + var ws syscall.WaitStatus + if _, err := syscall.Wait4(pid, &ws, syscall.WNOHANG, nil); err == nil { + continue + } + } + now[pid] = start + } + return now +} + +// zombieStat is the state, parent and start time of a /proc//stat +// line, counted after the command's closing parenthesis. +func zombieStat(b []byte) (state byte, ppid int, start uint64, ok bool) { + i := bytes.LastIndexByte(b, ')') + if i < 0 { + return 0, 0, 0, false + } + f := bytes.Fields(b[i+1:]) + if len(f) < 20 || len(f[0]) == 0 { + return 0, 0, 0, false + } + pp, err := strconv.Atoi(string(f[1])) + if err != nil { + return 0, 0, 0, false + } + st, err := strconv.ParseUint(string(f[19]), 10, 64) + if err != nil { + return 0, 0, 0, false + } + return f[0][0], pp, st, true +} diff --git a/internal/proc/orphans_linux_test.go b/internal/proc/orphans_linux_test.go new file mode 100644 index 000000000..aa4993420 --- /dev/null +++ b/internal/proc/orphans_linux_test.go @@ -0,0 +1,80 @@ +package proc + +import ( + "context" + "os" + "os/exec" + "strconv" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +// zombieChildren counts this process's children. +func zombieChildren(t *testing.T) int { + t.Helper() + ents, err := os.ReadDir("/proc") + if err != nil { + t.Fatal(err) + } + n := 0 + 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 + } + if st, pp, _, ok := zombieStat(b); ok && st == 'Z' && pp == os.Getpid() { + n++ + } + } + return n +} + +// TestAdoptedOrphansAreReaped: magpie as a container's PID 1 (here a +// subreaper, which adopts the same way) is left the processes of its +// children's children, and they stayed until it restarted (254 +// after 7 days, Kling__Lab on X). +func TestAdoptedOrphansAreReaped(t *testing.T) { + if err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0); err != nil { + t.Skip("no subreaper:", err) + } + defer unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 0, 0, 0, 0) + old := OrphanEvery + OrphanEvery = 20 * time.Millisecond + defer func() { OrphanEvery = old }() + + // the shell ends at once; the two it started end a moment later and + // are adopted by this process, which never started them + for range 3 { + cmd := exec.Command("sh", "-c", "(sleep 0.2 &) ; (sleep 0.2 &) ; exit 0") + if err := cmd.Run(); err != nil { + t.Fatal(err) + } + } + // a command that is started and waited for is no orphan + if err := exec.Command("true").Run(); err != nil { + t.Fatal(err) + } + + // they end, and stay zombies of this process + for end := time.Now().Add(10 * time.Second); zombieChildren(t) < 6; time.Sleep(20 * time.Millisecond) { + if time.Now().After(end) { + t.Fatalf("only %d of the 6 orphans ended", zombieChildren(t)) + } + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + KeepReaping(ctx) + + for end := time.Now().Add(10 * time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) { + if zombieChildren(t) == 0 { + return + } + } + t.Fatalf("%d adopted zombies left", zombieChildren(t)) +} diff --git a/internal/proc/orphans_other.go b/internal/proc/orphans_other.go new file mode 100644 index 000000000..f3ce37ace --- /dev/null +++ b/internal/proc/orphans_other.go @@ -0,0 +1,9 @@ +//go:build !linux + +package proc + +import "context" + +// KeepReaping does nothing off Linux: only there are the orphans of a +// container's PID 1 left to it. +func KeepReaping(context.Context) {}