artifactize-tools 0.27.0

Portable scoped tools and safe file access for artifactize.
Documentation
//! Unix executable lookup and process groups.

use std::io;

mod desktop;
pub(crate) use desktop::open_desktop;

/// Arm all terminal and termination signals now, before a call can spawn a child.
pub(crate) fn stop_requested() -> io::Result<impl Future<Output = ()> + Send> {
    use tokio::signal::unix::{SignalKind, signal};
    let mut interrupt = signal(SignalKind::interrupt())?;
    let mut hangup = signal(SignalKind::hangup())?;
    let mut terminate = signal(SignalKind::terminate())?;
    Ok(async move {
        tokio::select! {
            _ = interrupt.recv() => {},
            _ = hangup.recv() => {},
            _ = terminate.recv() => {},
        }
    })
}

/// A program and its own process group. Only `reap` may wait on the Tokio child;
/// until `kill` takes the group, the unreaped child reserves its PID and group ID.
pub(crate) struct Tree {
    child: tokio::process::Child,
    group: Option<rustix::process::Pid>,
    exits: tokio::signal::unix::Signal,
}

/// A group ID of zero selects the child's own PID as its new group ID.
const CHILD_PID_AS_GROUP: i32 = 0;

/// Start `command` as the leader of a new process group.
pub(crate) fn spawn_tree(command: &mut tokio::process::Command) -> io::Result<Tree> {
    use tokio::signal::unix::{SignalKind, signal};

    // Subscribe before spawn so an exit between the first probe and recv wakes us.
    let exits = signal(SignalKind::child())?;
    command.process_group(CHILD_PID_AS_GROUP);
    let child = command.spawn()?;
    let pid = child.id().expect("a child not yet waited on has a PID");
    let pid = i32::try_from(pid).expect("Unix process IDs fit pid_t");
    let group = rustix::process::Pid::from_raw(pid).expect("a child's PID is positive");
    Ok(Tree {
        child,
        group: Some(group),
        exits,
    })
}

impl Tree {
    pub(crate) fn take_output(
        &mut self,
    ) -> (tokio::process::ChildStdout, tokio::process::ChildStderr) {
        (
            self.child.stdout.take().expect("piped stdout"),
            self.child.stderr.take().expect("piped stderr"),
        )
    }

    /// Observe the leader's exit without freeing the group's numeric identity.
    pub(crate) async fn exited(&mut self) -> io::Result<()> {
        use rustix::process::{WaitId, WaitIdOptions, waitid};

        let group = self.group.expect("exit observation precedes cleanup");
        let options = WaitIdOptions::EXITED | WaitIdOptions::NOWAIT | WaitIdOptions::NOHANG;
        loop {
            match waitid(WaitId::Pid(group), options) {
                Ok(Some(_)) => return Ok(()),
                Ok(None) => {
                    self.exits.recv().await.ok_or_else(|| {
                        io::Error::other("Child exit notifications ended unexpectedly.")
                    })?;
                }
                Err(rustix::io::Errno::INTR) => continue,
                Err(error) => return Err(error.into()),
            }
        }
    }

    /// Kill every remaining process before relinquishing the group's identity.
    fn kill(&mut self) -> io::Result<()> {
        if let Some(group) = self.group.take() {
            kill_group(group)?;
        }
        Ok(())
    }

    /// Kill the group before the only wait that consumes the leader's exit status.
    pub(crate) async fn reap(&mut self) -> io::Result<std::process::ExitStatus> {
        if let Err(error) = self.kill() {
            let _ = self.child.start_kill();
            let _ = self.child.wait().await;
            return Err(error);
        }
        self.child.wait().await
    }
}

fn kill_group(group: rustix::process::Pid) -> io::Result<()> {
    match rustix::process::kill_process_group(group, rustix::process::Signal::KILL) {
        Ok(()) | Err(rustix::io::Errno::SRCH) => Ok(()),
        #[cfg(target_os = "macos")]
        Err(rustix::io::Errno::PERM) => {
            use artifactize_foundation::platform::process::{child_identity, kill_saved_group};

            // Darwin may refuse a signal to a zombie-only group. Use Foundation's
            // fallback while the unreaped leader still reserves the group ID.
            kill_saved_group(child_identity(group.as_raw_pid() as u32)?)
        }
        Err(error) => Err(error.into()),
    }
}

impl Drop for Tree {
    fn drop(&mut self) {
        // Also handles a dropped future: while `group` is set, Tokio hasn't reaped it.
        let _ = self.kill();
    }
}