Skip to main content

ic_host_process/child/
mod.rs

1//! Explicit child ownership and cleanup, without application lifecycle policy.
2//!
3//! Callers own executable admission, IO, readiness, cancellation and deadlines.
4//! Group cleanup signals members of a newly created group; it cannot contain
5//! processes that escape that group or prove completion of external effects.
6
7#[cfg(target_os = "macos")]
8mod macos;
9#[cfg(test)]
10mod tests;
11
12use rustix::{
13    io::Errno,
14    process::{Pid, Signal, WaitId, WaitIdOptions, WaitIdStatus, kill_process_group, waitid},
15};
16use std::{
17    fmt, io,
18    os::unix::process::{CommandExt, ExitStatusExt},
19    process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus},
20    time::{Duration, Instant},
21};
22
23/// Caller-selected termination behavior for an owned process group.
24#[derive(Clone, Copy, Debug)]
25pub enum CleanupPolicy {
26    /// Signal KILL immediately, then wait synchronously for the leader.
27    KillAndWait,
28    /// Signal TERM, reserve the leader through the grace period, then signal
29    /// KILL and poll reaping for at most the selected duration.
30    TermThenKill {
31        /// Time allowed after successful TERM signalling, even if the leader exits.
32        grace: Duration,
33        /// Reap allowance after KILL; zero permits one nonblocking observation.
34        reap_timeout: Duration,
35    },
36}
37
38/// One exclusively owned child, normally spawned as a new process-group leader.
39///
40/// [`Self::spawn`] preserves the command's IO, environment and other settings,
41/// replacing its process-group selection with a new group. It performs no
42/// executable admission. The child must not change groups, and callers must
43/// not independently reap it (including through a global SIGCHLD handler).
44///
45/// Ordinary waiting signals remaining group members before reaping the leader.
46/// For a deliberate background handoff, [`Self::poll_exit`] observes without
47/// releasing cleanup ownership, then [`Self::handoff`] reaps a successful leader
48/// without signalling its group. The caller then owns the background lifetime.
49/// Drop makes a best-effort kill/reap attempt, including during unwinding. Use
50/// [`Self::terminate`] to observe cleanup failures. [`Self::spawn`] requires a
51/// cleanup policy: synchronous kill/reap or TERM grace with bounded reaping.
52/// Successful signalling is not proof that descendants
53/// have exited or completed external effects. Only the direct child is reaped.
54/// Group signalling can succeed for only some members when credentials differ.
55/// [`Self::spawn_direct`] instead preserves the command's process-group selection
56/// and owns only the direct child. Its wait, termination and Drop never signal
57/// other group members; descendant lifetime remains with the caller.
58pub struct OwnedChild {
59    child: Child,
60    group: bool,
61    status: Option<ExitStatus>,
62    owned: bool,
63    cleanup: CleanupPolicy,
64    reap_started: Option<Instant>,
65}
66
67/// Failures observed during one explicit termination attempt.
68///
69/// Keep this separately from the caller's original cancellation/operation error.
70/// If group signalling fails, direct-child kill and reaping are still attempted.
71#[derive(Debug)]
72pub struct CleanupError {
73    /// Status retained if the direct child was reaped despite another failure.
74    pub status: Option<ExitStatus>,
75    /// Failure signalling TERM to the owned process group.
76    pub term_error: Option<io::Error>,
77    /// Failure signalling KILL to the owned process group.
78    pub group_error: Option<io::Error>,
79    /// Failure killing the direct child (including fallback after group failure).
80    pub kill_error: Option<io::Error>,
81    /// Failure reaping the direct child.
82    pub wait_error: Option<io::Error>,
83}
84
85impl fmt::Display for CleanupError {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str("child cleanup failed")?;
88        for (operation, error) in [
89            ("group TERM", &self.term_error),
90            ("group signal", &self.group_error),
91            ("child kill", &self.kill_error),
92            ("child wait", &self.wait_error),
93        ] {
94            if let Some(error) = error {
95                write!(f, "; {operation}: {error}")?;
96            }
97        }
98        Ok(())
99    }
100}
101
102impl std::error::Error for CleanupError {
103    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
104        self.term_error
105            .as_ref()
106            .or(self.group_error.as_ref())
107            .or(self.kill_error.as_ref())
108            .or(self.wait_error.as_ref())
109            .map(|error| error as &dyn std::error::Error)
110    }
111}
112
113impl OwnedChild {
114    /// Spawn once in a new owned group with caller-selected cleanup and IO.
115    ///
116    /// The policy applies whenever termination is needed, including communication
117    /// failures and Drop during unwinding. It does not change natural waiting or
118    /// successful background handoff. No signal handler or reaper thread is added.
119    ///
120    /// ```no_run
121    /// use ic_host_process::child::{CleanupPolicy, OwnedChild};
122    /// use std::{process::Command, time::Duration};
123    /// let mut child = OwnedChild::spawn(
124    ///     &mut Command::new("caller-selected-tool"),
125    ///     CleanupPolicy::TermThenKill {
126    ///         grace: Duration::from_secs(5),
127    ///         reap_timeout: Duration::from_secs(5),
128    ///     },
129    /// )?;
130    /// // Configure command IO before spawn; communicate/admit before handoff.
131    /// child.terminate()?;
132    /// # Ok::<(), Box<dyn std::error::Error>>(())
133    /// ```
134    /// # Errors
135    /// Returns the native spawn/setup failure. No retries are performed.
136    pub fn spawn(command: &mut Command, cleanup: CleanupPolicy) -> io::Result<Self> {
137        command.process_group(0);
138        Self::spawn_inner(command, true, cleanup)
139    }
140
141    /// Spawn once owning only the direct child, without changing command settings.
142    ///
143    /// Preserves inherited or explicitly configured process-group selection and
144    /// IO. This permits foreground callers to retain terminal-group membership;
145    /// it does not create a session, transfer terminal control or forward signals.
146    /// No executable admission, retry or signal handler is installed.
147    ///
148    /// Waiting reaps only this child. Termination and Drop kill only this child
149    /// and wait synchronously using [`CleanupPolicy::KillAndWait`]. Descendants
150    /// are never signalled, even if the command explicitly selects a new group.
151    /// Their lifecycle and inherited pipe writers remain caller-owned; no-deadline
152    /// communication may wait indefinitely for their EOF after the child exits.
153    /// Use [`Self::spawn`] when ownership of a new group is required.
154    ///
155    /// # Errors
156    /// Returns the native spawn/setup failure. No retries are performed.
157    pub fn spawn_direct(command: &mut Command) -> io::Result<Self> {
158        Self::spawn_inner(command, false, CleanupPolicy::KillAndWait)
159    }
160
161    /// Take direct-child ownership after a caller-owned spawn boundary.
162    ///
163    /// The caller transfers its existing child and configured IO without respawning
164    /// or granting process-group ownership. This supports command-custody spawners;
165    /// ordinary bounded communication, cancellation and direct-child cleanup apply.
166    /// The caller must not independently reap the child after transferring it.
167    #[must_use]
168    pub const fn from_spawned_direct(child: Child) -> Self {
169        Self {
170            child,
171            group: false,
172            status: None,
173            owned: true,
174            cleanup: CleanupPolicy::KillAndWait,
175            reap_started: None,
176        }
177    }
178
179    pub(crate) const fn is_owned(&self) -> bool {
180        self.owned && self.reap_started.is_none()
181    }
182
183    fn spawn_inner(command: &mut Command, group: bool, cleanup: CleanupPolicy) -> io::Result<Self> {
184        command.spawn().map(|child| {
185            let mut owner = Self::from_spawned_direct(child);
186            owner.group = group;
187            owner.cleanup = cleanup;
188            owner
189        })
190    }
191
192    /// Direct-child PID, for observation only; it can be reused after reaping.
193    #[must_use]
194    pub fn id(&self) -> u32 {
195        self.child.id()
196    }
197
198    /// Take caller-configured piped stdin. Close it before waiting for EOF-driven children.
199    pub const fn take_stdin(&mut self) -> Option<ChildStdin> {
200        self.child.stdin.take()
201    }
202
203    /// Take caller-configured piped stdout; the caller owns draining and bounds.
204    pub const fn take_stdout(&mut self) -> Option<ChildStdout> {
205        self.child.stdout.take()
206    }
207
208    /// Take caller-configured piped stderr; the caller owns draining and bounds.
209    pub const fn take_stderr(&mut self) -> Option<ChildStderr> {
210        self.child.stderr.take()
211    }
212
213    /// Observe leader exit without signalling or reaping it.
214    ///
215    /// An exited leader stays reserved with `WNOWAIT`, so cancellation, failed IO
216    /// admission and unwinding still clean its group. Repeated observations do
217    /// not release ownership. After a completed wait/termination/handoff, returns
218    /// the cached status. This status alone does not establish a handoff.
219    ///
220    /// Call [`Self::handoff`] only after admitting a successful background start.
221    /// Otherwise use [`Self::wait`] or [`Self::terminate`] to clean and reap.
222    /// # Errors
223    /// Returns native inspection errors; external reaping invalidates ownership.
224    pub fn poll_exit(&mut self) -> io::Result<Option<ExitStatus>> {
225        if let Some(status) = self.status {
226            return Ok(Some(status));
227        }
228        self.observe_exit(true)?
229            .map(|status| {
230                // Unix wait status encoding used by Linux and Darwin. waitid's
231                // siginfo status is an exit code/signal, not an encoded wait status.
232                let raw = if let Some(code) = status.exit_status() {
233                    code << 8
234                } else if let Some(signal) = status.terminating_signal() {
235                    signal | if status.dumped() { 0x80 } else { 0 }
236                } else {
237                    return Err(io::Error::other("waitid returned a non-exit observation"));
238                };
239                Ok(ExitStatus::from_raw(raw))
240            })
241            .transpose()
242    }
243
244    /// Reap an already successful leader without signalling its remaining group.
245    ///
246    /// This is the explicit transfer point for a background lifetime. The caller
247    /// must first admit its IO/result and arrange application-owned readiness,
248    /// cancellation and stop/recovery. Zero exit does not prove those obligations.
249    /// No PID/group handle is transferred: it could be reused after reaping.
250    /// Subsequent wait/termination/Drop never signal the handed-off group.
251    ///
252    /// Use [`Self::poll_exit`] while draining IO and checking cancellation. A
253    /// running or unsuccessful leader is refused without releasing ownership;
254    /// use ordinary wait/termination for failed startup, keeping its original
255    /// failure separate from any cleanup error. Drop still attempts cleanup.
256    /// # Errors
257    /// Returns `InvalidInput` for a running, unsuccessful, terminating or already-reaped
258    /// leader, or native inspection/reap errors. Reap failures retain cleanup
259    /// ownership unless it was lost externally.
260    pub fn handoff(&mut self) -> io::Result<ExitStatus> {
261        if !self.is_owned() || !self.poll_exit()?.is_some_and(|status| status.success()) {
262            return Err(io::Error::new(
263                io::ErrorKind::InvalidInput,
264                "handoff requires an owned, successfully exited leader",
265            ));
266        }
267        self.reap()
268    }
269
270    /// Inspect exit without blocking on a running child; clean its group before reaping.
271    ///
272    /// Repeated successful calls return the cached status without signalling again.
273    /// # Errors
274    /// Returns native inspection, group-signal or reap errors. The leader remains
275    /// reserved on a group-signal failure, so explicit cleanup can still be attempted.
276    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
277        if let Some(status) = self.status {
278            return Ok(Some(status));
279        }
280        if !self.owned {
281            return Err(Errno::CHILD.into());
282        }
283        if self.group {
284            if self.observe_exit(true)?.is_none() {
285                return Ok(None);
286            }
287            self.signal_group(Signal::KILL)?;
288            self.reap().map(Some)
289        } else {
290            let result = retry_interrupted(|| self.child.try_wait());
291            if let Ok(Some(status)) = result {
292                self.status = Some(status);
293                self.owned = false;
294            }
295            self.check_wait_ownership(&result);
296            result
297        }
298    }
299
300    /// Wait for natural leader exit, then clean its group and reap the leader.
301    ///
302    /// Close/drain caller-owned pipes as needed before waiting. No deadline or
303    /// cancellation policy is installed; callers may use polling instead.
304    /// # Errors
305    /// Returns native inspection, group-signal or reap errors.
306    pub fn wait(&mut self) -> io::Result<ExitStatus> {
307        if let Some(status) = self.status {
308            return Ok(status);
309        }
310        if self.group {
311            self.observe_exit(false)?;
312            self.signal_group(Signal::KILL)?;
313        }
314        self.reap()
315    }
316
317    /// Terminate the owned group or direct child, then reap the child.
318    ///
319    /// Repeated calls after reaping return the cached status and never signal a
320    /// reused PID. A prior group failure still matters even if reaping succeeded;
321    /// later calls cannot recover group ownership and do not erase that evidence.
322    /// With [`CleanupPolicy::TermThenKill`], successful TERM signalling is followed
323    /// by the full grace period without reaping, then KILL even if the leader has
324    /// exited. A TERM error does not prevent KILL or reaping. The reap allowance
325    /// begins after signalling; repeated termination and Drop never restart it or
326    /// repeat escalation. Reap timeout returns `TimedOut` in `wait_error` while
327    /// keeping the unreaped child owned. Callers may explicitly recover with
328    /// `try_wait`/`wait`; dropping after timeout can leave an unreaped child until
329    /// parent exit. No background reaper is installed. Scheduling and native
330    /// syscall latency are outside these polling bounds.
331    /// # Errors
332    /// Retains each failed cleanup step separately. Group failure triggers a
333    /// direct-child kill fallback. Drop cannot report errors; call this explicitly
334    /// when cleanup evidence matters.
335    pub fn terminate(&mut self) -> Result<ExitStatus, CleanupError> {
336        if let Some(status) = self.status {
337            return Ok(status);
338        }
339        let first_attempt = self.reap_started.is_none();
340        let term_error =
341            if first_attempt && let CleanupPolicy::TermThenKill { grace, .. } = self.cleanup {
342                let error = self.signal_group(Signal::TERM).err();
343                if error.is_none() {
344                    let started = Instant::now();
345                    while started.elapsed() < grace {
346                        std::thread::sleep(
347                            grace
348                                .saturating_sub(started.elapsed())
349                                .min(Duration::from_secs(1)),
350                        );
351                    }
352                }
353                error
354            } else {
355                None
356            };
357        let group_error = if first_attempt && self.group {
358            self.signal_group(Signal::KILL).err()
359        } else {
360            None
361        };
362        let kill_error = if first_attempt && self.owned && (!self.group || group_error.is_some()) {
363            retry_interrupted(|| self.child.kill()).err()
364        } else {
365            None
366        };
367        let waited = match self.cleanup {
368            CleanupPolicy::KillAndWait => self.reap(),
369            CleanupPolicy::TermThenKill { reap_timeout, .. } => {
370                let started = *self.reap_started.get_or_insert_with(Instant::now);
371                self.reap_bounded(started, reap_timeout)
372            }
373        };
374        match waited {
375            Ok(status) if term_error.is_none() && group_error.is_none() && kill_error.is_none() => {
376                Ok(status)
377            }
378            other => Err(CleanupError {
379                status: self.status,
380                term_error,
381                group_error,
382                kill_error,
383                wait_error: other.err(),
384            }),
385        }
386    }
387
388    fn pid(&self) -> io::Result<Pid> {
389        if !self.owned {
390            return Err(Errno::CHILD.into());
391        }
392        Pid::from_raw(i32::try_from(self.id()).map_err(io::Error::other)?)
393            .ok_or_else(|| io::Error::other("child PID is zero"))
394    }
395
396    fn observe_exit(&mut self, nonblocking: bool) -> io::Result<Option<WaitIdStatus>> {
397        let pid = self.pid()?;
398        // NOWAIT reserves the leader PID until cleanup or explicit handoff,
399        // avoiding signals to an unrelated group after an early leader exit.
400        let mut options = WaitIdOptions::EXITED | WaitIdOptions::NOWAIT;
401        if nonblocking {
402            options |= WaitIdOptions::NOHANG;
403        }
404        let result = retry_interrupted(|| waitid(WaitId::Pid(pid), options).map_err(Into::into));
405        self.check_wait_ownership(&result);
406        result
407    }
408
409    #[cfg_attr(
410        not(target_os = "macos"),
411        allow(
412            clippy::needless_pass_by_ref_mut,
413            reason = "Darwin inspects and may invalidate child ownership"
414        )
415    )]
416    fn signal_group(&mut self, signal: Signal) -> io::Result<()> {
417        let pid = self.pid()?;
418        match retry_interrupted(|| kill_process_group(pid, signal).map_err(Into::into)) {
419            Ok(()) => Ok(()),
420            Err(error) if error.raw_os_error() == Some(Errno::SRCH.raw_os_error()) => Ok(()),
421            #[cfg(target_os = "macos")]
422            Err(error)
423                if error.raw_os_error() == Some(Errno::PERM.raw_os_error())
424                    && self.observe_exit(true)?.is_some()
425                    && macos::sole_group_member(pid) =>
426            {
427                Ok(())
428            }
429            Err(error) => Err(error),
430        }
431    }
432
433    fn reap(&mut self) -> io::Result<ExitStatus> {
434        if !self.owned {
435            return Err(Errno::CHILD.into());
436        }
437        let result = retry_interrupted(|| self.child.wait());
438        if let Ok(status) = result {
439            self.status = Some(status);
440            self.owned = false;
441        }
442        self.check_wait_ownership(&result);
443        result
444    }
445
446    fn reap_bounded(&mut self, started: Instant, timeout: Duration) -> io::Result<ExitStatus> {
447        if !self.owned {
448            return Err(Errno::CHILD.into());
449        }
450        loop {
451            // Never call blocking wait, including after an interrupted poll.
452            let result = self.child.try_wait();
453            self.check_wait_ownership(&result);
454            match result {
455                Ok(Some(status)) => {
456                    self.status = Some(status);
457                    self.owned = false;
458                    return Ok(status);
459                }
460                Ok(None) => {}
461                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
462                Err(error) => return Err(error),
463            }
464            let remaining = timeout.saturating_sub(started.elapsed());
465            if remaining.is_zero() {
466                return Err(io::Error::new(
467                    io::ErrorKind::TimedOut,
468                    "child reap timed out",
469                ));
470            }
471            std::thread::sleep(remaining.min(Duration::from_millis(2)));
472        }
473    }
474
475    fn check_wait_ownership<T>(&mut self, result: &io::Result<T>) {
476        if result
477            .as_ref()
478            .is_err_and(|error| error.raw_os_error() == Some(Errno::CHILD.raw_os_error()))
479        {
480            // An external reaper violates exclusive ownership; never signal a
481            // potentially reused PID after observing that ownership was lost.
482            self.owned = false;
483        }
484    }
485}
486
487impl Drop for OwnedChild {
488    fn drop(&mut self) {
489        if self.owned {
490            let _ = self.terminate();
491        }
492    }
493}
494
495fn retry_interrupted<T>(mut operation: impl FnMut() -> io::Result<T>) -> io::Result<T> {
496    loop {
497        match operation() {
498            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
499            result => return result,
500        }
501    }
502}