adk_sandbox/process_tree_unix.rs
1//! Process groups that hold a process and every process it starts (spec 3.2 §10 W1, K-I5).
2//!
3//! A Unix process tree is held in a session and process group of its own: the process is
4//! started as the leader of a new session ([`ProcessGroup::new_session`]), every process it
5//! starts belongs to the group, and a signal sent to the group reaches all of them, the
6//! descendants of a leader that has already exited included. [`ProcessGroup`] is the Unix
7//! counterpart of the Windows `JobObject` this module holds there: the stdio servers of
8//! `adk-tool`'s `McpServerManager`, the kernel's drivers among them, end this way, and the
9//! end returns only once every process of the group has exited.
10//!
11//! A process group is not a boundary the way a Job Object is. A process that starts a
12//! session or group of its own (`setsid`, `setpgid`) leaves the group, and nothing ends the
13//! group when its owner is killed outright, since the owner then runs no cleanup.
14
15use std::io;
16use std::sync::{Mutex, MutexGuard, PoisonError};
17use std::time::{Duration, Instant};
18
19/// How often a terminating group is asked whether its processes have exited.
20const TERMINATION_POLL: Duration = Duration::from_millis(5);
21
22/// A process group whose leader the group holds, which ends as a whole (spec 3.2 §10 W1,
23/// K-I5).
24///
25/// Start the process with [`new_session`](Self::new_session) and hand the spawned child to
26/// [`contain`](Self::contain). The group keeps the leader unreaped until it ends the group,
27/// so the leader's process id, which is the group's id, cannot be reused while the group is
28/// signalled. [`terminate_and_wait`](Self::terminate_and_wait) sends the group `SIGTERM`,
29/// then `SIGKILL`, and returns once every process in it has exited;
30/// [`terminate`](Self::terminate) sends `SIGKILL` at once. Dropping the group sends
31/// `SIGKILL` to whatever is left in it.
32///
33/// # Example
34///
35/// ```rust,no_run
36/// use adk_sandbox::process_tree::ProcessGroup;
37///
38/// # async fn run() -> std::io::Result<()> {
39/// let mut command = tokio::process::Command::new("sh");
40/// command.args(["-c", "sleep 100 & sleep 100"]);
41/// ProcessGroup::new_session(&mut command);
42/// let group = ProcessGroup::contain(command.spawn()?)?;
43/// // The `sleep` the shell left in the background ends here too.
44/// assert!(group.terminate_and_wait_async(ProcessGroup::TERMINATION_WAIT).await?);
45/// # Ok(())
46/// # }
47/// ```
48#[derive(Debug)]
49pub struct ProcessGroup {
50 /// The group's id: its leader's process id.
51 id: libc::pid_t,
52 /// The leader until the group reaps it; while it is held, its id names this group only.
53 leader: Mutex<Option<tokio::process::Child>>,
54}
55
56impl ProcessGroup {
57 /// How long [`terminate_and_wait`](Self::terminate_and_wait) callers wait by default for
58 /// the group's processes to exit: a process that handles `SIGTERM` gets up to half of
59 /// it, and `SIGKILL` ends the rest in milliseconds.
60 pub const TERMINATION_WAIT: Duration = Duration::from_secs(2);
61
62 /// Makes `command` start its process as the leader of a new session, and so of a new
63 /// process group whose id is the process's own, with no controlling terminal.
64 ///
65 /// Without a controlling terminal the process can neither read from nor inject input
66 /// into the owner's terminal, and the terminal's signals, such as Ctrl-C's `SIGINT`, do
67 /// not reach it: its owner ends it. A command that already makes its process a group
68 /// leader, with `process_group(0)`, keeps that group and its session.
69 ///
70 /// # Example
71 ///
72 /// ```rust,no_run
73 /// use adk_sandbox::process_tree::ProcessGroup;
74 ///
75 /// let mut command = tokio::process::Command::new("my-mcp-server");
76 /// ProcessGroup::new_session(&mut command).kill_on_drop(true);
77 /// ```
78 pub fn new_session(command: &mut tokio::process::Command) -> &mut tokio::process::Command {
79 // SAFETY: the closure runs in the forked child before `exec` and calls only `setsid`,
80 // `getpgrp` and `getpid`, which are async-signal-safe, and reads `errno`; it touches
81 // no memory of the parent.
82 unsafe {
83 command.pre_exec(|| {
84 if libc::setsid() == -1 {
85 let error = io::Error::last_os_error();
86 // `setsid` refuses a process that already leads its group, which
87 // `process_group(0)` makes it before this runs.
88 if libc::getpgrp() != libc::getpid() {
89 return Err(error);
90 }
91 }
92 Ok(())
93 })
94 }
95 }
96
97 /// Holds `child`, which [`new_session`](Self::new_session) started, as the leader of its
98 /// group.
99 ///
100 /// # Errors
101 ///
102 /// Returns an error when the child has already been reaped or leads no process group of
103 /// its own, as a command spawned without [`new_session`](Self::new_session) does. The
104 /// child is then sent `SIGKILL`, since nothing could end what it starts.
105 ///
106 /// # Example
107 ///
108 /// ```rust,no_run
109 /// use adk_sandbox::process_tree::ProcessGroup;
110 ///
111 /// # fn run() -> std::io::Result<()> {
112 /// let mut command = tokio::process::Command::new("my-mcp-server");
113 /// ProcessGroup::new_session(&mut command);
114 /// let group = ProcessGroup::contain(command.spawn()?)?;
115 /// assert!(group.id() > 1);
116 /// # Ok(())
117 /// # }
118 /// ```
119 pub fn contain(mut child: tokio::process::Child) -> io::Result<Self> {
120 let id = child.id().and_then(|pid| libc::pid_t::try_from(pid).ok()).ok_or_else(|| {
121 io::Error::other("the process was reaped before its process group could be held")
122 })?;
123 // SAFETY: `getpgid` takes a process id and has no memory-safety preconditions.
124 let group = unsafe { libc::getpgid(id) };
125 // A leader that has already exited is unreaped, and some systems report no group for
126 // it; its id stays reserved all the same.
127 let exited = group == -1 && io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH);
128 if id <= 1 || (group != id && !exited) {
129 let _ = child.start_kill();
130 return Err(io::Error::other(format!(
131 "process {id} leads no process group of its own, so the processes it starts \
132 could not be ended with it; start it with ProcessGroup::new_session"
133 )));
134 }
135 Ok(Self { id, leader: Mutex::new(Some(child)) })
136 }
137
138 /// The group's id, which is its leader's process id.
139 pub fn id(&self) -> u32 {
140 self.id.unsigned_abs()
141 }
142
143 /// Sends `SIGKILL` to every process in the group, the leader included.
144 ///
145 /// Termination is asynchronous: a process can still complete I/O it had in flight, such
146 /// as a write to a file, after this returns.
147 /// [`terminate_and_wait`](Self::terminate_and_wait) returns only once every process has
148 /// exited. A group whose leader it has already reaped is not signalled, since its id may
149 /// then name another group.
150 pub fn terminate(&self) {
151 let leader = self.leader();
152 if leader.is_some() {
153 signal(self.id, libc::SIGKILL);
154 }
155 }
156
157 /// Waits, for at most `limit`, until the group's leader has exited, without reaping it,
158 /// and returns whether it has. The rest of the group may still run.
159 ///
160 /// # Errors
161 ///
162 /// Returns the OS error when the leader's state cannot be queried.
163 ///
164 /// # Example
165 ///
166 /// ```rust,no_run
167 /// use std::time::Duration;
168 /// use adk_sandbox::process_tree::ProcessGroup;
169 ///
170 /// # async fn run(group: ProcessGroup) -> std::io::Result<()> {
171 /// if !group.wait_for_leader(Duration::from_secs(3)).await? {
172 /// group.terminate_and_wait_async(ProcessGroup::TERMINATION_WAIT).await?;
173 /// }
174 /// # Ok(())
175 /// # }
176 /// ```
177 pub async fn wait_for_leader(&self, limit: Duration) -> io::Result<bool> {
178 let deadline = Instant::now() + limit;
179 loop {
180 let exited = match self.leader().as_ref() {
181 Some(_) => leader_exited(self.id)?,
182 None => true,
183 };
184 if exited {
185 return Ok(true);
186 }
187 if Instant::now() >= deadline {
188 return Ok(false);
189 }
190 tokio::time::sleep(TERMINATION_POLL).await;
191 }
192 }
193
194 /// Ends the group and waits, for at most `limit`, until each of its processes has exited,
195 /// so nothing a process had in flight lands after the call returns. Returns whether every
196 /// process has exited. The wait blocks the thread;
197 /// [`terminate_and_wait_async`](Self::terminate_and_wait_async) is its async form.
198 ///
199 /// The group is sent `SIGTERM`, and `SIGKILL` once its leader has exited or half of
200 /// `limit` has passed. The leader is then reaped, and the call returns once no process of
201 /// the group is left, including descendants the leader left behind, which the system
202 /// reaps once they exit. A second call only waits.
203 ///
204 /// # Errors
205 ///
206 /// Returns the OS error when the leader cannot be waited for.
207 ///
208 /// # Example
209 ///
210 /// ```rust,no_run
211 /// use adk_sandbox::process_tree::ProcessGroup;
212 ///
213 /// # fn run(group: ProcessGroup) -> std::io::Result<()> {
214 /// assert!(group.terminate_and_wait(ProcessGroup::TERMINATION_WAIT)?);
215 /// # Ok(())
216 /// # }
217 /// ```
218 pub fn terminate_and_wait(&self, limit: Duration) -> io::Result<bool> {
219 let deadline = Instant::now() + limit;
220 let mut termination = Termination::begin(self, limit / 2);
221 loop {
222 if termination.finished()? {
223 return Ok(true);
224 }
225 if Instant::now() >= deadline {
226 return Ok(false);
227 }
228 std::thread::sleep(TERMINATION_POLL);
229 }
230 }
231
232 /// [`terminate_and_wait`](Self::terminate_and_wait) that sleeps on the Tokio timer
233 /// instead of blocking the thread.
234 ///
235 /// # Errors
236 ///
237 /// Returns the OS error when the leader cannot be waited for.
238 ///
239 /// # Example
240 ///
241 /// ```rust,no_run
242 /// use adk_sandbox::process_tree::ProcessGroup;
243 ///
244 /// # async fn run(group: ProcessGroup) -> std::io::Result<()> {
245 /// assert!(group.terminate_and_wait_async(ProcessGroup::TERMINATION_WAIT).await?);
246 /// # Ok(())
247 /// # }
248 /// ```
249 pub async fn terminate_and_wait_async(&self, limit: Duration) -> io::Result<bool> {
250 let deadline = Instant::now() + limit;
251 let mut termination = Termination::begin(self, limit / 2);
252 loop {
253 if termination.finished()? {
254 return Ok(true);
255 }
256 if Instant::now() >= deadline {
257 return Ok(false);
258 }
259 tokio::time::sleep(TERMINATION_POLL).await;
260 }
261 }
262
263 /// The leader, `None` once the group has reaped it. Signals are sent under this lock, so
264 /// the leader cannot be reaped while one is on its way.
265 fn leader(&self) -> MutexGuard<'_, Option<tokio::process::Child>> {
266 self.leader.lock().unwrap_or_else(PoisonError::into_inner)
267 }
268}
269
270impl Drop for ProcessGroup {
271 fn drop(&mut self) {
272 // The leader is then dropped unreaped, and Tokio reaps it once it exits.
273 if self.leader.get_mut().unwrap_or_else(PoisonError::into_inner).is_some() {
274 signal(self.id, libc::SIGKILL);
275 }
276 }
277}
278
279/// A group being ended: `SIGTERM` sent, `SIGKILL` once the leader has exited or the grace
280/// has passed, then the leader reaped and the rest of the group waited for.
281struct Termination<'a> {
282 group: &'a ProcessGroup,
283 /// When `SIGKILL` follows a `SIGTERM` the leader has not exited on.
284 kill_at: Instant,
285 /// Whether `SIGKILL` has been sent.
286 killed: bool,
287}
288
289impl<'a> Termination<'a> {
290 fn begin(group: &'a ProcessGroup, grace: Duration) -> Self {
291 let leader = group.leader();
292 if leader.is_some() {
293 signal(group.id, libc::SIGTERM);
294 }
295 Self { group, kill_at: Instant::now() + grace, killed: leader.is_none() }
296 }
297
298 /// Whether every process of the group has exited, advancing the termination.
299 fn finished(&mut self) -> io::Result<bool> {
300 let mut leader = self.group.leader();
301 if let Some(child) = leader.as_mut() {
302 if !self.killed {
303 if !leader_exited(self.group.id)? && Instant::now() < self.kill_at {
304 return Ok(false);
305 }
306 signal(self.group.id, libc::SIGKILL);
307 self.killed = true;
308 }
309 if child.try_wait()?.is_none() {
310 return Ok(false);
311 }
312 *leader = None;
313 }
314 drop(leader);
315 // A member the system has yet to reap still counts: it may not have finished exiting.
316 // SAFETY: `kill` has no memory-safety preconditions; signal 0 only checks that a
317 // process of the group exists.
318 let probed = unsafe { libc::kill(-self.group.id, 0) };
319 Ok(probed == -1 && io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH))
320 }
321}
322
323/// Sends `signal` to the group `id`. The caller holds the group's unreaped leader, so `id`
324/// names no other group.
325fn signal(id: libc::pid_t, signal: libc::c_int) {
326 // SAFETY: `killpg` takes a group id and a signal and cannot violate memory safety; `id` is
327 // greater than 1, so it never names the caller's own group or every process. A failure
328 // means no process of the group is left to signal.
329 unsafe {
330 libc::killpg(id, signal);
331 }
332}
333
334/// Whether the unreaped child `id` has exited. `waitid` with `WNOWAIT` leaves it unreaped,
335/// so its id stays reserved.
336fn leader_exited(id: libc::pid_t) -> io::Result<bool> {
337 loop {
338 // SAFETY: all zeroes is a valid `siginfo_t`, which `waitid` writes only into; a zero
339 // `si_pid` afterwards means the child has not exited.
340 let (waited, pid) = unsafe {
341 let mut info: libc::siginfo_t = std::mem::zeroed();
342 let waited = libc::waitid(
343 libc::P_PID,
344 id.unsigned_abs(),
345 &mut info,
346 libc::WEXITED | libc::WNOWAIT | libc::WNOHANG,
347 );
348 (waited, info.si_pid())
349 };
350 if waited == 0 {
351 return Ok(pid != 0);
352 }
353 let error = io::Error::last_os_error();
354 match error.raw_os_error() {
355 Some(libc::EINTR) => {}
356 // Not a child of this process any more: it has exited and been reaped.
357 Some(libc::ECHILD) => return Ok(true),
358 _ => return Err(error),
359 }
360 }
361}