返回 last30days-skill
proc_group_unix.go
根目录 / mcp / internal / engine / proc_group_unix.go
1 //go:build !windows
2
3 package engine
4
5 import (
6 "context"
7 "errors"
8 "os/exec"
9 "syscall"
10 "time"
11 )
12
13 var errWaitNoReapUnsupported = errors.New("wait without reap unsupported")
14
15 // Overridable seams for deterministic process-lifecycle ordering tests.
16 var (
17 signalProcessGroupFunc = func(pid int, sig syscall.Signal) error {
18 return syscall.Kill(-pid, sig)
19 }
20 signalDirectChildFunc = func(cmd *exec.Cmd, sig syscall.Signal) error {
21 if cmd.Process == nil {
22 return nil
23 }
24 if sig == syscall.SIGKILL {
25 return cmd.Process.Kill()
26 }
27 return cmd.Process.Signal(sig)
28 }
29 waitChildNoReapFunc = waitChildNoReap
30 waitCmdFunc = func(cmd *exec.Cmd) error {
31 return cmd.Wait()
32 }
33 )
34
35 // setProcessGroup puts the engine child in its own process group so a
36 // timeout kill reaches same-group helpers on the primary unreaped wait path.
37 // Descendants spawned via lib/subproc.py (including grok CLI, bird-search,
38 // yt-dlp, digg) run in their own pgids (os.setsid) and are cleaned up by the
39 // engine's SIGTERM handler (killpg per registered child), even when the
40 // fallback path signals only the direct Python child.
41 func setProcessGroup(cmd *exec.Cmd) {
42 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
43 }
44
45 // termProcessGroup SIGTERMs the whole engine process group (negative pid =
46 // group). This runs the python SIGTERM handler, which cleans the setsid'd
47 // descendant groups before the SIGKILL backstop. Errors are ignored: the
48 // group may already be gone when the deadline fires.
49 func termProcessGroup(cmd *exec.Cmd) {
50 if cmd.Process == nil {
51 return
52 }
53 _ = signalProcessGroupFunc(cmd.Process.Pid, syscall.SIGTERM)
54 }
55
56 // killProcessGroup SIGKILLs the whole engine process group (negative pid =
57 // group). ESRCH and other errors are intentionally ignored: the group may
58 // already be gone when the deadline fires.
59 func killProcessGroup(cmd *exec.Cmd) {
60 if cmd.Process == nil {
61 return
62 }
63 _ = signalProcessGroupFunc(cmd.Process.Pid, syscall.SIGKILL)
64 }
65
66 // waitCommand monitors cmd until it exits or ctx ends, ensuring all
67 // process-group signals are delivered while the child leader is still unreaped
68 // so the OS cannot recycle its PID/PGID into an unrelated process group.
69 func waitCommand(ctx context.Context, cmd *exec.Cmd, grace time.Duration) error {
70 return waitCommandWithDrain(ctx, cmd, grace, pipeGracePeriod, nil, nil)
71 }
72
73 // waitCommandWithDrain coordinates leader exit watching, output-pipe draining,
74 // context cancellation, and leader reaping. Because stdout/stderr are explicit
75 // *os.File pipes, cmd.Wait() only reaps the leader; keeping cmd.Wait() last
76 // keeps the leader's PID/PGID pinned throughout draining so same-group helpers
77 // holding pipes open are still cleaned up if ctx cancels or pipeGrace elapses.
78 func waitCommandWithDrain(
79 ctx context.Context,
80 cmd *exec.Cmd,
81 grace, pipeGrace time.Duration,
82 drainDone <-chan struct{},
83 closeReadPipes func(),
84 ) error {
85 drainDone, closeReadPipes = normalizeDrain(drainDone, closeReadPipes)
86 if cmd.Process == nil || cmd.Process.Pid <= 0 {
87 err := waitCmdFunc(cmd)
88 finishDrain(drainDone, closeReadPipes, pipeGrace)
89 return err
90 }
91 pid := cmd.Process.Pid
92 exitedCh := make(chan error, 1)
93 go func() {
94 exitedCh <- waitChildNoReapFunc(pid)
95 }()
96
97 select {
98 case noReapErr := <-exitedCh:
99 // Only noReapErr == nil guarantees the leader is an unreaped zombie;
100 // any error falls back so context timeout/cancel still kills the child.
101 if noReapErr != nil {
102 return waitCommandFallback(ctx, cmd, grace, pipeGrace, drainDone, closeReadPipes)
103 }
104 // Leader exited while still unreaped. Keep it pinned as a zombie until
105 // output pipes finish draining so cancellation or pipeGrace expiration
106 // can still safely signal same-group helpers holding stdout/stderr open.
107 return drainWhileLeaderUnreaped(ctx, cmd, grace, pipeGrace, drainDone, closeReadPipes)
108
109 case <-ctx.Done():
110 // Leader is not yet reaped, so its PID/PGID cannot be recycled while
111 // SIGTERM and any SIGKILL backstop execute.
112 termProcessGroup(cmd)
113
114 timer := time.NewTimer(grace)
115 defer timer.Stop()
116
117 select {
118 case noReapErr := <-exitedCh:
119 if noReapErr != nil {
120 return waitCommandFallbackAfterTerm(cmd, grace, pipeGrace, drainDone, closeReadPipes)
121 }
122 // Leader exited during grace and remains an unreaped zombie;
123 // SIGKILL any remaining in-group stragglers before reaping.
124 killProcessGroup(cmd)
125 err := waitCmdFunc(cmd)
126 finishDrain(drainDone, closeReadPipes, pipeGrace)
127 return err
128
129 case <-timer.C:
130 killProcessGroup(cmd)
131 <-exitedCh
132 err := waitCmdFunc(cmd)
133 finishDrain(drainDone, closeReadPipes, pipeGrace)
134 return err
135 }
136 }
137 }
138
139 func drainWhileLeaderUnreaped(
140 ctx context.Context,
141 cmd *exec.Cmd,
142 grace, pipeGrace time.Duration,
143 drainDone <-chan struct{},
144 closeReadPipes func(),
145 ) error {
146 if ctx.Err() != nil {
147 killRemainingGroupForDrain(cmd, grace, drainDone)
148 err := waitCmdFunc(cmd)
149 finishDrain(drainDone, closeReadPipes, postKillDrainGrace(pipeGrace))
150 return err
151 }
152 select {
153 case <-drainDone:
154 return waitCmdFunc(cmd)
155 default:
156 }
157
158 var pipeTimerC <-chan time.Time
159 if pipeGrace > 0 {
160 pipeTimer := time.NewTimer(pipeGrace)
161 defer pipeTimer.Stop()
162 pipeTimerC = pipeTimer.C
163 }
164
165 select {
166 case <-drainDone:
167 return waitCmdFunc(cmd)
168
169 case <-ctx.Done():
170 // Leader is still an unreaped zombie; SIGTERM then SIGKILL any
171 // same-group helpers holding pipes open before reaping.
172 killRemainingGroupForDrain(cmd, grace, drainDone)
173 err := waitCmdFunc(cmd)
174 finishDrain(drainDone, closeReadPipes, postKillDrainGrace(pipeGrace))
175 return err
176
177 case <-pipeTimerC:
178 // Leader exited normally, but a descendant still holds pipes open past
179 // pipeGrace. Clean up any same-group helpers before reaping, then cut
180 // off any remaining out-of-group pipe holders.
181 killRemainingGroupForDrain(cmd, grace, drainDone)
182 err := waitCmdFunc(cmd)
183 finishDrain(drainDone, closeReadPipes, postKillDrainGrace(pipeGrace))
184 if err == nil {
185 return exec.ErrWaitDelay
186 }
187 return err
188 }
189 }
190
191 func killRemainingGroupForDrain(cmd *exec.Cmd, grace time.Duration, drainDone <-chan struct{}) {
192 termProcessGroup(cmd)
193 timer := time.NewTimer(grace)
194 defer timer.Stop()
195 select {
196 case <-drainDone:
197 case <-timer.C:
198 }
199 killProcessGroup(cmd)
200 }
201
202 func postKillDrainGrace(pipeGrace time.Duration) time.Duration {
203 const maxPostKillDrain = 200 * time.Millisecond
204 if pipeGrace <= 0 || pipeGrace > maxPostKillDrain {
205 return maxPostKillDrain
206 }
207 return pipeGrace
208 }
209
210 // waitCommandFallback is used only when waitChildNoReap cannot pin the child
211 // leader unreaped. Because cmd.Wait() runs concurrently, it avoids raw numeric
212 // -pid group signals and signals only the direct child through os.Process,
213 // which Go synchronizes internally against PID reuse during reaping.
214 func waitCommandFallback(
215 ctx context.Context,
216 cmd *exec.Cmd,
217 grace, pipeGrace time.Duration,
218 drainDone <-chan struct{},
219 closeReadPipes func(),
220 ) error {
221 waitCh := make(chan error, 1)
222 go func() { waitCh <- waitCmdFunc(cmd) }()
223
224 select {
225 case err := <-waitCh:
226 drainTimedOut := finishDrain(drainDone, closeReadPipes, pipeGrace)
227 if err == nil && drainTimedOut {
228 return exec.ErrWaitDelay
229 }
230 return err
231 case <-ctx.Done():
232 _ = signalDirectChildFunc(cmd, syscall.SIGTERM)
233 return waitCommandFallbackAfterTermCh(cmd, waitCh, grace, pipeGrace, drainDone, closeReadPipes)
234 }
235 }
236
237 func waitCommandFallbackAfterTerm(
238 cmd *exec.Cmd,
239 grace, pipeGrace time.Duration,
240 drainDone <-chan struct{},
241 closeReadPipes func(),
242 ) error {
243 waitCh := make(chan error, 1)
244 go func() { waitCh <- waitCmdFunc(cmd) }()
245 return waitCommandFallbackAfterTermCh(cmd, waitCh, grace, pipeGrace, drainDone, closeReadPipes)
246 }
247
248 func waitCommandFallbackAfterTermCh(
249 cmd *exec.Cmd,
250 waitCh <-chan error,
251 grace, pipeGrace time.Duration,
252 drainDone <-chan struct{},
253 closeReadPipes func(),
254 ) error {
255 timer := time.NewTimer(grace)
256 defer timer.Stop()
257
258 var err error
259 select {
260 case err = <-waitCh:
261 case <-timer.C:
262 _ = signalDirectChildFunc(cmd, syscall.SIGKILL)
263 err = <-waitCh
264 }
265 finishDrain(drainDone, closeReadPipes, pipeGrace)
266 return err
267 }
268
268 lines GO