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. The default cleanup waits
51/// synchronously; [`Self::spawn_with_cleanup`] can select 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 process group, preserving caller-configured IO.
115    ///
116    /// # Errors
117    /// Returns the native spawn/setup failure. No retries are performed.
118    pub fn spawn(command: &mut Command) -> io::Result<Self> {
119        Self::spawn_with_cleanup(command, CleanupPolicy::KillAndWait)
120    }
121
122    /// Spawn a new owned group with caller-selected termination timing.
123    ///
124    /// The policy applies whenever termination is needed, including communication
125    /// failures and Drop during unwinding. It does not change natural waiting or
126    /// successful background handoff. No signal handler or reaper thread is added.
127    ///
128    /// ```no_run
129    /// use ic_host_process::child::{CleanupPolicy, OwnedChild};
130    /// use std::{process::Command, time::Duration};
131    /// let mut child = OwnedChild::spawn_with_cleanup(
132    ///     &mut Command::new("caller-selected-tool"),
133    ///     CleanupPolicy::TermThenKill {
134    ///         grace: Duration::from_secs(5),
135    ///         reap_timeout: Duration::from_secs(5),
136    ///     },
137    /// )?;
138    /// // Configure command IO before spawn; communicate/admit before handoff.
139    /// child.terminate()?;
140    /// # Ok::<(), Box<dyn std::error::Error>>(())
141    /// ```
142    /// # Errors
143    /// Returns the native spawn/setup failure. No retries are performed.
144    pub fn spawn_with_cleanup(command: &mut Command, cleanup: CleanupPolicy) -> io::Result<Self> {
145        command.process_group(0);
146        Self::spawn_inner(command, true, cleanup)
147    }
148
149    /// Spawn once owning only the direct child, without changing command settings.
150    ///
151    /// Preserves inherited or explicitly configured process-group selection and
152    /// IO. This permits foreground callers to retain terminal-group membership;
153    /// it does not create a session, transfer terminal control or forward signals.
154    /// No executable admission, retry or signal handler is installed.
155    ///
156    /// Waiting reaps only this child. Termination and Drop kill only this child
157    /// and wait synchronously using [`CleanupPolicy::KillAndWait`]. Descendants
158    /// are never signalled, even if the command explicitly selects a new group.
159    /// Their lifecycle and inherited pipe writers remain caller-owned; no-deadline
160    /// communication may wait indefinitely for their EOF after the child exits.
161    /// Use [`Self::spawn`] when ownership of a new group is required.
162    ///
163    /// # Errors
164    /// Returns the native spawn/setup failure. No retries are performed.
165    pub fn spawn_direct(command: &mut Command) -> io::Result<Self> {
166        Self::spawn_inner(command, false, CleanupPolicy::KillAndWait)
167    }
168
169    pub(crate) const fn is_owned(&self) -> bool {
170        self.owned && self.reap_started.is_none()
171    }
172
173    fn spawn_inner(command: &mut Command, group: bool, cleanup: CleanupPolicy) -> io::Result<Self> {
174        command.spawn().map(|child| Self {
175            child,
176            group,
177            status: None,
178            owned: true,
179            cleanup,
180            reap_started: None,
181        })
182    }
183
184    /// Direct-child PID, for observation only; it can be reused after reaping.
185    #[must_use]
186    pub fn id(&self) -> u32 {
187        self.child.id()
188    }
189
190    /// Take caller-configured piped stdin. Close it before waiting for EOF-driven children.
191    pub const fn take_stdin(&mut self) -> Option<ChildStdin> {
192        self.child.stdin.take()
193    }
194
195    /// Take caller-configured piped stdout; the caller owns draining and bounds.
196    pub const fn take_stdout(&mut self) -> Option<ChildStdout> {
197        self.child.stdout.take()
198    }
199
200    /// Take caller-configured piped stderr; the caller owns draining and bounds.
201    pub const fn take_stderr(&mut self) -> Option<ChildStderr> {
202        self.child.stderr.take()
203    }
204
205    /// Observe leader exit without signalling or reaping it.
206    ///
207    /// An exited leader stays reserved with `WNOWAIT`, so cancellation, failed IO
208    /// admission and unwinding still clean its group. Repeated observations do
209    /// not release ownership. After a completed wait/termination/handoff, returns
210    /// the cached status. This status alone does not establish a handoff.
211    ///
212    /// Call [`Self::handoff`] only after admitting a successful background start.
213    /// Otherwise use [`Self::wait`] or [`Self::terminate`] to clean and reap.
214    /// # Errors
215    /// Returns native inspection errors; external reaping invalidates ownership.
216    pub fn poll_exit(&mut self) -> io::Result<Option<ExitStatus>> {
217        if let Some(status) = self.status {
218            return Ok(Some(status));
219        }
220        self.observe_exit(true)?
221            .map(|status| {
222                // Unix wait status encoding used by Linux and Darwin. waitid's
223                // siginfo status is an exit code/signal, not an encoded wait status.
224                let raw = if let Some(code) = status.exit_status() {
225                    code << 8
226                } else if let Some(signal) = status.terminating_signal() {
227                    signal | if status.dumped() { 0x80 } else { 0 }
228                } else {
229                    return Err(io::Error::other("waitid returned a non-exit observation"));
230                };
231                Ok(ExitStatus::from_raw(raw))
232            })
233            .transpose()
234    }
235
236    /// Reap an already successful leader without signalling its remaining group.
237    ///
238    /// This is the explicit transfer point for a background lifetime. The caller
239    /// must first admit its IO/result and arrange application-owned readiness,
240    /// cancellation and stop/recovery. Zero exit does not prove those obligations.
241    /// No PID/group handle is transferred: it could be reused after reaping.
242    /// Subsequent wait/termination/Drop never signal the handed-off group.
243    ///
244    /// Use [`Self::poll_exit`] while draining IO and checking cancellation. A
245    /// running or unsuccessful leader is refused without releasing ownership;
246    /// use ordinary wait/termination for failed startup, keeping its original
247    /// failure separate from any cleanup error. Drop still attempts cleanup.
248    /// # Errors
249    /// Returns `InvalidInput` for a running, unsuccessful, terminating or already-reaped
250    /// leader, or native inspection/reap errors. Reap failures retain cleanup
251    /// ownership unless it was lost externally.
252    pub fn handoff(&mut self) -> io::Result<ExitStatus> {
253        if !self.is_owned() || !self.poll_exit()?.is_some_and(|status| status.success()) {
254            return Err(io::Error::new(
255                io::ErrorKind::InvalidInput,
256                "handoff requires an owned, successfully exited leader",
257            ));
258        }
259        self.reap()
260    }
261
262    /// Inspect exit without blocking on a running child; clean its group before reaping.
263    ///
264    /// Repeated successful calls return the cached status without signalling again.
265    /// # Errors
266    /// Returns native inspection, group-signal or reap errors. The leader remains
267    /// reserved on a group-signal failure, so explicit cleanup can still be attempted.
268    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
269        if let Some(status) = self.status {
270            return Ok(Some(status));
271        }
272        if !self.owned {
273            return Err(Errno::CHILD.into());
274        }
275        if self.group {
276            if self.observe_exit(true)?.is_none() {
277                return Ok(None);
278            }
279            self.signal_group(Signal::KILL)?;
280            self.reap().map(Some)
281        } else {
282            let result = retry_interrupted(|| self.child.try_wait());
283            if let Ok(Some(status)) = result {
284                self.status = Some(status);
285                self.owned = false;
286            }
287            self.check_wait_ownership(&result);
288            result
289        }
290    }
291
292    /// Wait for natural leader exit, then clean its group and reap the leader.
293    ///
294    /// Close/drain caller-owned pipes as needed before waiting. No deadline or
295    /// cancellation policy is installed; callers may use polling instead.
296    /// # Errors
297    /// Returns native inspection, group-signal or reap errors.
298    pub fn wait(&mut self) -> io::Result<ExitStatus> {
299        if let Some(status) = self.status {
300            return Ok(status);
301        }
302        if self.group {
303            self.observe_exit(false)?;
304            self.signal_group(Signal::KILL)?;
305        }
306        self.reap()
307    }
308
309    /// Terminate the owned group or direct child, then reap the child.
310    ///
311    /// Repeated calls after reaping return the cached status and never signal a
312    /// reused PID. A prior group failure still matters even if reaping succeeded;
313    /// later calls cannot recover group ownership and do not erase that evidence.
314    /// With [`CleanupPolicy::TermThenKill`], successful TERM signalling is followed
315    /// by the full grace period without reaping, then KILL even if the leader has
316    /// exited. A TERM error does not prevent KILL or reaping. The reap allowance
317    /// begins after signalling; repeated termination and Drop never restart it or
318    /// repeat escalation. Reap timeout returns `TimedOut` in `wait_error` while
319    /// keeping the unreaped child owned. Callers may explicitly recover with
320    /// `try_wait`/`wait`; dropping after timeout can leave an unreaped child until
321    /// parent exit. No background reaper is installed. Scheduling and native
322    /// syscall latency are outside these polling bounds.
323    /// # Errors
324    /// Retains each failed cleanup step separately. Group failure triggers a
325    /// direct-child kill fallback. Drop cannot report errors; call this explicitly
326    /// when cleanup evidence matters.
327    pub fn terminate(&mut self) -> Result<ExitStatus, CleanupError> {
328        if let Some(status) = self.status {
329            return Ok(status);
330        }
331        let first_attempt = self.reap_started.is_none();
332        let term_error =
333            if first_attempt && let CleanupPolicy::TermThenKill { grace, .. } = self.cleanup {
334                let error = self.signal_group(Signal::TERM).err();
335                if error.is_none() {
336                    let started = Instant::now();
337                    while started.elapsed() < grace {
338                        std::thread::sleep(
339                            grace
340                                .saturating_sub(started.elapsed())
341                                .min(Duration::from_secs(1)),
342                        );
343                    }
344                }
345                error
346            } else {
347                None
348            };
349        let group_error = if first_attempt && self.group {
350            self.signal_group(Signal::KILL).err()
351        } else {
352            None
353        };
354        let kill_error = if first_attempt && self.owned && (!self.group || group_error.is_some()) {
355            retry_interrupted(|| self.child.kill()).err()
356        } else {
357            None
358        };
359        let waited = match self.cleanup {
360            CleanupPolicy::KillAndWait => self.reap(),
361            CleanupPolicy::TermThenKill { reap_timeout, .. } => {
362                let started = *self.reap_started.get_or_insert_with(Instant::now);
363                self.reap_bounded(started, reap_timeout)
364            }
365        };
366        match waited {
367            Ok(status) if term_error.is_none() && group_error.is_none() && kill_error.is_none() => {
368                Ok(status)
369            }
370            other => Err(CleanupError {
371                status: self.status,
372                term_error,
373                group_error,
374                kill_error,
375                wait_error: other.err(),
376            }),
377        }
378    }
379
380    fn pid(&self) -> io::Result<Pid> {
381        if !self.owned {
382            return Err(Errno::CHILD.into());
383        }
384        Pid::from_raw(i32::try_from(self.id()).map_err(io::Error::other)?)
385            .ok_or_else(|| io::Error::other("child PID is zero"))
386    }
387
388    fn observe_exit(&mut self, nonblocking: bool) -> io::Result<Option<WaitIdStatus>> {
389        let pid = self.pid()?;
390        // NOWAIT reserves the leader PID until cleanup or explicit handoff,
391        // avoiding signals to an unrelated group after an early leader exit.
392        let mut options = WaitIdOptions::EXITED | WaitIdOptions::NOWAIT;
393        if nonblocking {
394            options |= WaitIdOptions::NOHANG;
395        }
396        let result = retry_interrupted(|| waitid(WaitId::Pid(pid), options).map_err(Into::into));
397        self.check_wait_ownership(&result);
398        result
399    }
400
401    #[cfg_attr(
402        not(target_os = "macos"),
403        allow(
404            clippy::needless_pass_by_ref_mut,
405            reason = "Darwin inspects and may invalidate child ownership"
406        )
407    )]
408    fn signal_group(&mut self, signal: Signal) -> io::Result<()> {
409        let pid = self.pid()?;
410        match retry_interrupted(|| kill_process_group(pid, signal).map_err(Into::into)) {
411            Ok(()) => Ok(()),
412            Err(error) if error.raw_os_error() == Some(Errno::SRCH.raw_os_error()) => Ok(()),
413            #[cfg(target_os = "macos")]
414            Err(error)
415                if error.raw_os_error() == Some(Errno::PERM.raw_os_error())
416                    && self.observe_exit(true)?.is_some()
417                    && macos::sole_group_member(pid) =>
418            {
419                Ok(())
420            }
421            Err(error) => Err(error),
422        }
423    }
424
425    fn reap(&mut self) -> io::Result<ExitStatus> {
426        if !self.owned {
427            return Err(Errno::CHILD.into());
428        }
429        let result = retry_interrupted(|| self.child.wait());
430        if let Ok(status) = result {
431            self.status = Some(status);
432            self.owned = false;
433        }
434        self.check_wait_ownership(&result);
435        result
436    }
437
438    fn reap_bounded(&mut self, started: Instant, timeout: Duration) -> io::Result<ExitStatus> {
439        if !self.owned {
440            return Err(Errno::CHILD.into());
441        }
442        loop {
443            // Never call blocking wait, including after an interrupted poll.
444            let result = self.child.try_wait();
445            self.check_wait_ownership(&result);
446            match result {
447                Ok(Some(status)) => {
448                    self.status = Some(status);
449                    self.owned = false;
450                    return Ok(status);
451                }
452                Ok(None) => {}
453                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
454                Err(error) => return Err(error),
455            }
456            let remaining = timeout.saturating_sub(started.elapsed());
457            if remaining.is_zero() {
458                return Err(io::Error::new(
459                    io::ErrorKind::TimedOut,
460                    "child reap timed out",
461                ));
462            }
463            std::thread::sleep(remaining.min(Duration::from_millis(2)));
464        }
465    }
466
467    fn check_wait_ownership<T>(&mut self, result: &io::Result<T>) {
468        if result
469            .as_ref()
470            .is_err_and(|error| error.raw_os_error() == Some(Errno::CHILD.raw_os_error()))
471        {
472            // An external reaper violates exclusive ownership; never signal a
473            // potentially reused PID after observing that ownership was lost.
474            self.owned = false;
475        }
476    }
477}
478
479impl Drop for OwnedChild {
480    fn drop(&mut self) {
481        if self.owned {
482            let _ = self.terminate();
483        }
484    }
485}
486
487fn retry_interrupted<T>(mut operation: impl FnMut() -> io::Result<T>) -> io::Result<T> {
488    loop {
489        match operation() {
490            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
491            result => return result,
492        }
493    }
494}