diff --git a/internal/proc/probe.go b/internal/proc/probe.go index c757fed90..1a23c7f04 100644 --- a/internal/proc/probe.go +++ b/internal/proc/probe.go @@ -18,7 +18,7 @@ import ( // exits. ctx must end (a timeout): the probe is forgotten when it does. func ProbeContext(ctx context.Context, name string, args ...string) *exec.Cmd { ctx, cancel := context.WithCancel(ctx) - p := &probe{cancel: cancel, ended: make(chan struct{})} + p := &probe{cancel: cancel, killing: make(chan struct{}), ended: make(chan struct{})} cmd := CommandContext(ctx, name, args...) probeGroup(cmd, p) probes.Lock() @@ -33,24 +33,29 @@ func ProbeContext(ctx context.Context, name string, args ...string) *exec.Cmd { } type probe struct { - cancel context.CancelFunc - once sync.Once - ended chan struct{} // closed once it was killed + cancel context.CancelFunc + killOnce, once sync.Once + killing, ended chan struct{} // closed once its kill began, and once it was over } -func (p *probe) end() { p.once.Do(func() { close(p.ended) }) } +func (p *probe) kill() { p.killOnce.Do(func() { close(p.killing) }) } +func (p *probe) end() { p.once.Do(func() { close(p.ended) }) } var probes = struct { sync.Mutex m map[*probe]struct{} }{m: map[*probe]struct{}{}} -// endWait is how long EndProbes waits for the probes to be killed. +// endWait is how long EndProbes waits for a probe's kill to begin: one that +// had answered, or never started, has none. var endWait = time.Second // EndProbes kills every probe still running, with what it started, and -// waits a moment for that: magpie is exiting or putting a new version in its -// place, and nothing would end them after. +// waits until none of that is left: magpie is exiting or putting a new +// version in its place, and nothing would end them after. A kill that missed +// a process being forked signals the group again until it is empty, and an +// exit before that left the missed one running, adopted by init (#1278); the +// wait is bounded by how long a kill goes on (killFor on Unix). func EndProbes() { probes.Lock() ps := make([]*probe, 0, len(probes.m)) @@ -61,12 +66,18 @@ func EndProbes() { for _, p := range ps { p.cancel() } - deadline := time.After(endWait) + begun := time.Now().Add(endWait) + over := begun.Add(killWait()) for _, p := range ps { + select { + case <-p.killing: + case <-time.After(time.Until(begun)): + continue // one that had answered already, or never started + } select { case <-p.ended: - case <-deadline: - return // one that had answered already, or never started + case <-time.After(time.Until(over)): + return } } } diff --git a/internal/proc/probe_other.go b/internal/proc/probe_other.go index 5bfd5c985..76f15c92d 100644 --- a/internal/proc/probe_other.go +++ b/internal/proc/probe_other.go @@ -2,16 +2,26 @@ package proc -import "os/exec" +import ( + "os/exec" + "time" +) // probeGroup has the probe lead a session, and its context ending kill the -// session's group: the script at its head and what that started. +// session's group: the script at its head and what that started. The probe +// counts as ended once none of the group is left, not once the first signal +// went out (#1278). func probeGroup(cmd *exec.Cmd, p *probe) { ownGroup(cmd) cmd.Cancel = func() error { - defer p.end() + p.kill() var g group - g.kill(cmd) + gone := g.kill(cmd) + go func() { <-gone; p.end() }() return cmd.Process.Kill() } } + +// killWait is how long EndProbes waits, past a kill's start, for the group +// to be empty: as long as the kill goes on signalling it, and a moment more. +func killWait() time.Duration { return killFor + time.Second } diff --git a/internal/proc/probe_test.go b/internal/proc/probe_test.go index 23a178556..26682f9d3 100644 --- a/internal/proc/probe_test.go +++ b/internal/proc/probe_test.go @@ -163,3 +163,67 @@ func TestProbeKillEndsWhatTheSignalMissed(t *testing.T) { t.Fatalf("what the probe started (pid %d) outlived a kill that missed it once", pid) } } + +// missFor has the group's signal reach nobody for d from its first call, as +// signals racing a launcher's forks do, and puts the real one back after. +func missFor(t *testing.T, d time.Duration) { + old := signalGroup + var mu sync.Mutex + var first time.Time + signalGroup = func(pgid int) error { + mu.Lock() + if first.IsZero() { + first = time.Now() + } + missing := time.Since(first) < d + mu.Unlock() + if missing { + return nil // sent, and reached nobody + } + return old(pgid) + } + t.Cleanup(func() { signalGroup = old }) +} + +// magpie exiting right after EndProbes leaves nothing of a probe running, +// even when the kill missed some of it at first (JJ-Lin's case on #1278): +// EndProbes returned after the first signal, the exit ended the loop that +// signals the group again, and the missed child lived on, adopted by init. +// The exit is a real one: the test runs itself as a magpie that ends its +// probes and exits at once. +func TestEndProbesThenExitLeavesNothing(t *testing.T) { + if os.Getenv("MAGPIE_PROC_EXIT_HELPER") == "1" { + missFor(t, 300*time.Millisecond) + sh, pidFile := probeScript(t) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + done := runProbe(ProbeContext(ctx, sh)) + pid := childPid(t, pidFile, done) + os.Stdout.WriteString("child " + strconv.Itoa(pid) + "\n") + EndProbes() + os.Exit(0) + } + self, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(self, "-test.run=^TestEndProbesThenExitLeavesNothing$") + cmd.Env = append(os.Environ(), "MAGPIE_PROC_EXIT_HELPER=1") + out, err := cmd.Output() + if err != nil { + t.Fatalf("the exiting magpie: %v\n%s", err, out) + } + var pid int + for _, l := range strings.Split(string(out), "\n") { + if s, ok := strings.CutPrefix(l, "child "); ok { + pid, _ = strconv.Atoi(s) + } + } + if pid == 0 { + t.Fatalf("the exiting magpie named no child:\n%s", out) + } + t.Cleanup(func() { _ = syscall.Kill(pid, syscall.SIGKILL) }) + if !gone(pid) { + t.Fatalf("what the probe started (pid %d) outlived magpie's exit after EndProbes", pid) + } +} diff --git a/internal/proc/probe_windows.go b/internal/proc/probe_windows.go index 878f4c08a..2ad745959 100644 --- a/internal/proc/probe_windows.go +++ b/internal/proc/probe_windows.go @@ -1,6 +1,9 @@ package proc -import "os/exec" +import ( + "os/exec" + "time" +) // probeGroup kills the probe alone, as CommandContext does: a job, as // StartTree gives a command, is joined only once it has started, and Output @@ -8,7 +11,12 @@ import "os/exec" // so what a shim started (npm's .cmd running node) is still left running. func probeGroup(cmd *exec.Cmd, p *probe) { cmd.Cancel = func() error { + p.kill() defer p.end() return cmd.Process.Kill() } } + +// killWait is how long EndProbes waits, past a kill's start, for it to be +// over: the probe is killed alone, and nothing is signalled again. +func killWait() time.Duration { return time.Second } diff --git a/internal/proc/proc_windows_test.go b/internal/proc/proc_windows_test.go index 1b077bc48..61c482a6e 100644 --- a/internal/proc/proc_windows_test.go +++ b/internal/proc/proc_windows_test.go @@ -4,12 +4,14 @@ import ( "context" "encoding/json" "fmt" + "io" "os" "os/exec" "path/filepath" "slices" "strings" "testing" + "time" ) func TestHideWithoutConsole(t *testing.T) { @@ -84,3 +86,34 @@ func TestEchoArgs(t *testing.T) { fmt.Fprintf(os.Stdout, "%s\n", b) os.Exit(0) } + +// a probe still asking when magpie exits is ended by EndProbes, and +// EndProbes returns once its kill is over, not after its whole wait (#1278) +func TestEndProbesWindows(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + cmd := ProbeContext(ctx, "ping", "-n", "60", "127.0.0.1") + out, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, _ = io.Copy(io.Discard, out) + done <- cmd.Wait() + }() + time.Sleep(500 * time.Millisecond) // asking, not starting + start := time.Now() + EndProbes() + if d := time.Since(start); d > endWait { + t.Fatalf("EndProbes took %v over a probe it killed", d) + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("the probe went on after EndProbes") + } +} diff --git a/internal/proc/tree.go b/internal/proc/tree.go index 3773a2598..3339b9b9d 100644 --- a/internal/proc/tree.go +++ b/internal/proc/tree.go @@ -45,6 +45,6 @@ func (t *Tree) Kill() { if t.done { return } - t.kill(t.cmd) + _ = t.kill(t.cmd) _ = t.cmd.Process.Kill() } diff --git a/internal/proc/tree_other.go b/internal/proc/tree_other.go index 481525f40..234e593dc 100644 --- a/internal/proc/tree_other.go +++ b/internal/proc/tree_other.go @@ -31,8 +31,12 @@ func (group) join(*exec.Cmd) {} // is still in the group, and the group keeps its id while any of it lives, // so the group is signalled again until none of it is left. Its leader, // killed and not yet waited for, counts until it is: hence behind the -// caller, which waits for it next. -func (group) kill(cmd *exec.Cmd) { +// caller, which waits for it next. The channel closes once none of the group +// is left, or killFor has passed: magpie exiting or putting a new version in +// its place waits for it, since an exit ends the loop with what it missed +// still running (#1278). +func (group) kill(cmd *exec.Cmd) <-chan struct{} { + gone := make(chan struct{}) pgid := cmd.Process.Pid // the one kill function for the whole kill, taken once: the loop below // outlives the caller, and a test swapping signalGroup for its own and @@ -40,9 +44,11 @@ func (group) kill(cmd *exec.Cmd) { // data race TestProbeKillEndsWhatTheSignalMissed went red under). signal := signalGroup if signal(pgid) != nil { - return // none of it is left + close(gone) // none of it is left + return gone } go func() { + defer close(gone) for end := time.Now().Add(killFor); time.Now().Before(end); { time.Sleep(5 * time.Millisecond) if signal(pgid) != nil { @@ -50,6 +56,7 @@ func (group) kill(cmd *exec.Cmd) { } } }() + return gone } // signalGroup kills the group pgid leads; a var so a test can have it miss. @@ -61,4 +68,4 @@ var killFor = 10 * time.Second // sweep ends what is left of the group once its leader is gone: the group // keeps the leader's pid while any of it runs, so none else has it. -func (g group) sweep(cmd *exec.Cmd) { g.kill(cmd) } +func (g group) sweep(cmd *exec.Cmd) { _ = g.kill(cmd) } diff --git a/internal/proc/tree_windows.go b/internal/proc/tree_windows.go index 2703439dd..86685f9fb 100644 --- a/internal/proc/tree_windows.go +++ b/internal/proc/tree_windows.go @@ -39,12 +39,18 @@ func (g *group) join(cmd *exec.Cmd) { g.job = job } -func (g *group) kill(*exec.Cmd) { +// kill ends the job's processes. Unlike a Unix group, a job takes no new +// process once it is being ended, so nothing can be missed and nothing is +// left to wait on: the channel is closed already. +func (g *group) kill(*exec.Cmd) <-chan struct{} { if g.job != 0 { _ = windows.TerminateJobObject(g.job, 1) } + return closed } +var closed = func() chan struct{} { c := make(chan struct{}); close(c); return c }() + func (g *group) sweep(*exec.Cmd) { if g.job != 0 { _ = windows.CloseHandle(g.job)