job-limits 0.1.0

Memory limits for child processes, and a guard that cleans up the whole process tree (same API on unix and Windows)
Documentation
//! Put a memory limit on a child process, and clean up the whole process tree when a [`Guard`] is dropped.
//!
//! It works the same way on unix and Windows.
//!
//! | | unix | Windows |
//! |---|---|---|
//! | Memory limit | `setrlimit(RLIMIT_AS)` before the child starts | `PROCESS_MEMORY` of a Job Object |
//! | Cleanup | The child gets its own process group; dropping the `Guard` sends `SIGKILL` to the whole group | `KILL_ON_JOB_CLOSE` of a Job Object |
//!
//! ```no_run
//! use std::process::Command;
//!
//! let limits = job_limits::Limits::new().process_memory(1 << 30);
//! let (mut child, guard) = limits.spawn(&mut Command::new("my-tool"))?;
//! child.wait()?;
//! drop(guard); // ends any grandchildren left behind
//! # Ok::<(), std::io::Error>(())
//! ```
//!
//! # What the limit means
//!
//! The limit applies to the memory one child process can allocate. Once it is exceeded, allocations fail
//! (whether the child then dies is up to the child).
//! Each OS counts differently: address space on unix, commit charge on Windows.
//! The same value therefore does not give exactly the same behavior.
//!
//! - Linux enforces the limit. macOS may not enforce `RLIMIT_AS`. A failure to set the limit is ignored
//!   (the child runs without it).
//! - On Windows, the limit is not in effect for the short time between starting the child and putting it
//!   into the Job.
//! - On unix, if the child ends before the `Guard` is dropped and its process group becomes empty, the
//!   process ID may be reused by an unrelated group, which the `Guard` would then kill. Dropping the
//!   `Guard` right after `wait`ing for the child avoids this in practice.

#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(not(any(unix, windows)))]
compile_error!("job-limits supports only unix and Windows");

#[cfg(unix)]
mod unix;
#[cfg(unix)]
use unix as sys;

#[cfg(windows)]
mod windows;
#[cfg(windows)]
use windows as sys;

use std::io;
use std::process::{Child, Command};

/// Limits to put on a child process.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Limits {
    process_memory: Option<u64>,
}

impl Limits {
    /// No limits.
    pub fn new() -> Self {
        Self::default()
    }

    /// The memory limit of one child process, in bytes. 0 is not allowed.
    pub fn process_memory(mut self, bytes: u64) -> Self {
        self.process_memory = Some(bytes);
        self
    }

    fn check(&self) -> io::Result<()> {
        if self.process_memory == Some(0) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "the memory limit must not be 0",
            ));
        }
        Ok(())
    }

    /// Spawns a child process with the limits applied. Dropping the returned [`Guard`] ends the child and its descendants.
    ///
    /// If the limits cannot be applied, the child is killed and an error is returned.
    pub fn spawn(&self, command: &mut Command) -> io::Result<(Child, Guard)> {
        self.check()?;
        sys::prepare(self, command);
        let mut child = command.spawn()?;
        match sys::attach(self, child.id(), sys::raw(&child)) {
            Ok(inner) => Ok((child, Guard(inner))),
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                Err(e)
            }
        }
    }

    /// The tokio version of [`spawn`](Self::spawn).
    #[cfg(feature = "tokio")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
    pub fn spawn_tokio(
        &self,
        command: &mut tokio::process::Command,
    ) -> io::Result<(tokio::process::Child, Guard)> {
        self.check()?;
        sys::prepare(self, command.as_std_mut());
        let mut child = command.spawn()?;
        let attached = match child.id() {
            Some(id) => sys::raw_tokio(&child).and_then(|raw| sys::attach(self, id, raw)),
            None => Err(io::Error::other("the child process has already ended")),
        };
        match attached {
            Ok(inner) => Ok((child, Guard(inner))),
            Err(e) => {
                // `start_kill` is enough here; the caller reaps the child when it drops it
                let _ = child.start_kill();
                Err(e)
            }
        }
    }
}

/// Cleans up a child process. Dropping it ends the child and its descendants.
///
/// It is fine for the child to have ended already.
#[derive(Debug)]
pub struct Guard(#[allow(dead_code)] sys::Guard);