aidaemon-tools 0.29.0

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
Documentation
use std::time::Duration;

/// Configure commands to run in their own process group (Unix).
/// This allows terminating the full process tree on cancel/timeout.
#[cfg(unix)]
pub fn configure_command_for_process_group(command: &mut tokio::process::Command) {
    // SAFETY: pre_exec runs in the child process after fork and before exec.
    // We only call the async-signal-safe setpgid syscall.
    unsafe {
        command.pre_exec(|| {
            if libc::setpgid(0, 0) != 0 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
}

#[cfg(not(unix))]
pub fn configure_command_for_process_group(command: &mut tokio::process::Command) {
    let _ = command;
}

#[cfg(unix)]
fn send_signal_to_process_group_or_pid(pid: u32, signal: i32) -> bool {
    if pid == 0 {
        return false;
    }
    let raw_pid = pid as libc::pid_t;
    // Prefer signalling the process group (negative pid), fallback to direct pid.
    let group_ok = unsafe { libc::kill(-raw_pid, signal) == 0 };
    if group_ok {
        return true;
    }
    unsafe { libc::kill(raw_pid, signal) == 0 }
}

/// Send SIGTERM to a process group (or fallback process pid).
#[cfg(unix)]
pub fn send_sigterm(pid: u32) -> bool {
    send_signal_to_process_group_or_pid(pid, libc::SIGTERM)
}

/// Send SIGKILL to a process group (or fallback process pid).
#[cfg(unix)]
pub fn send_sigkill(pid: u32) -> bool {
    send_signal_to_process_group_or_pid(pid, libc::SIGKILL)
}

/// Windows has no signals: ask the process tree to close (`taskkill /T`).
#[cfg(not(unix))]
pub fn send_sigterm(pid: u32) -> bool {
    taskkill(pid, false)
}

/// End the process tree at once (`taskkill /T /F`).
#[cfg(not(unix))]
pub fn send_sigkill(pid: u32) -> bool {
    taskkill(pid, true)
}

#[cfg(not(unix))]
fn taskkill(pid: u32, force: bool) -> bool {
    if pid == 0 {
        return false;
    }
    let mut command = std::process::Command::new("taskkill");
    command.args(["/PID", &pid.to_string(), "/T"]);
    if force {
        command.arg("/F");
    }
    command
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|status| status.success())
}

/// Best-effort process tree termination with TERM->KILL escalation.
pub async fn terminate_process_tree(pid: u32, child: &mut tokio::process::Child, grace: Duration) {
    #[cfg(unix)]
    {
        if !send_sigterm(pid) {
            let _ = child.start_kill();
        }

        let exited = tokio::time::timeout(grace, child.wait()).await;
        if exited.is_err() {
            let _ = send_sigkill(pid);
            let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await;
        }
    }

    #[cfg(not(unix))]
    {
        // The whole tree, as on Unix: a shell's children too.
        if !send_sigterm(pid) {
            let _ = child.start_kill();
        }
        if tokio::time::timeout(grace, child.wait()).await.is_err() {
            if !send_sigkill(pid) {
                let _ = child.start_kill();
            }
            let _ = tokio::time::timeout(Duration::from_secs(1), child.wait()).await;
        }
    }
}

/// Win32 job-object FFI: the `winnt.h` layouts and the four `kernel32`
/// calls this crate needs, declared here so no Windows bindings crate joins
/// the dependency graph. Compiled for tests on every platform so the layout
/// checks run in Unix CI too.
#[cfg(any(windows, test))]
#[allow(dead_code)] // FFI layouts: fields exist for their size and offset.
mod win32_job {
    /// `JOBOBJECT_BASIC_LIMIT_INFORMATION` (`winnt.h`).
    #[repr(C)]
    #[derive(Debug, Default, Clone, Copy)]
    pub(super) struct JobObjectBasicLimitInformation {
        pub per_process_user_time_limit: i64, // LARGE_INTEGER
        pub per_job_user_time_limit: i64,     // LARGE_INTEGER
        pub limit_flags: u32,                 // DWORD
        pub minimum_working_set_size: usize,  // SIZE_T
        pub maximum_working_set_size: usize,  // SIZE_T
        pub active_process_limit: u32,        // DWORD
        pub affinity: usize,                  // ULONG_PTR
        pub priority_class: u32,              // DWORD
        pub scheduling_class: u32,            // DWORD
    }

    /// `IO_COUNTERS` (`winnt.h`): six `ULONGLONG`s.
    #[repr(C)]
    #[derive(Debug, Default, Clone, Copy)]
    pub(super) struct IoCounters {
        pub read_operation_count: u64,
        pub write_operation_count: u64,
        pub other_operation_count: u64,
        pub read_transfer_count: u64,
        pub write_transfer_count: u64,
        pub other_transfer_count: u64,
    }

    /// `JOBOBJECT_EXTENDED_LIMIT_INFORMATION` (`winnt.h`).
    #[repr(C)]
    #[derive(Debug, Default, Clone, Copy)]
    pub(super) struct JobObjectExtendedLimitInformation {
        pub basic_limit_information: JobObjectBasicLimitInformation,
        pub io_info: IoCounters,
        pub process_memory_limit: usize,     // SIZE_T
        pub job_memory_limit: usize,         // SIZE_T
        pub peak_process_memory_used: usize, // SIZE_T
        pub peak_job_memory_used: usize,     // SIZE_T
    }

    /// `JobObjectExtendedLimitInformation` in `JOBOBJECTINFOCLASS`.
    pub(super) const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS: i32 = 9;
    /// Close of the job's last handle ends every process in it.
    pub(super) const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000;

    #[cfg(windows)]
    #[link(name = "kernel32")]
    unsafe extern "system" {
        pub(super) fn CreateJobObjectW(
            job_attributes: *const std::ffi::c_void,
            name: *const u16,
        ) -> *mut std::ffi::c_void;
        pub(super) fn SetInformationJobObject(
            job: *mut std::ffi::c_void,
            information_class: i32,
            information: *const std::ffi::c_void,
            information_length: u32,
        ) -> i32;
        pub(super) fn AssignProcessToJobObject(
            job: *mut std::ffi::c_void,
            process: *mut std::ffi::c_void,
        ) -> i32;
        pub(super) fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
    }
}

/// A Win32 job object whose processes all end when its last handle closes
/// (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`): on drop, or by the OS when the
/// owning process exits or crashes. The handle is not inheritable, so a
/// child never keeps its own job alive.
#[cfg(windows)]
pub struct JobObject {
    handle: std::ptr::NonNull<std::ffi::c_void>,
}

// SAFETY: a job-object HANDLE is a kernel handle, valid from any thread;
// the Win32 job calls are thread-safe and `Drop` closes it exactly once.
#[cfg(windows)]
unsafe impl Send for JobObject {}
#[cfg(windows)]
unsafe impl Sync for JobObject {}

#[cfg(windows)]
impl JobObject {
    /// An anonymous job that ends its processes when it is closed.
    pub fn kill_on_close() -> std::io::Result<Self> {
        use win32_job::*;
        // SAFETY: null attributes and name ask for an anonymous job with a
        // non-inheritable handle; NULL is the only failure value.
        let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        let handle = std::ptr::NonNull::new(raw).ok_or_else(std::io::Error::last_os_error)?;
        // Owned from here: an early return closes it.
        let job = Self { handle };
        let mut info = JobObjectExtendedLimitInformation::default();
        info.basic_limit_information.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        // SAFETY: `info` is the `winnt.h` layout for this class and lives
        // across the call; the length is its exact size.
        let ok = unsafe {
            SetInformationJobObject(
                job.handle.as_ptr(),
                JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS,
                (&raw const info).cast(),
                std::mem::size_of::<JobObjectExtendedLimitInformation>() as u32,
            )
        };
        if ok == 0 {
            return Err(std::io::Error::last_os_error());
        }
        Ok(job)
    }

    /// Put a running child (and the processes it starts from now on) in
    /// this job. A child already reaped has no handle left to assign.
    pub fn assign(&self, child: &tokio::process::Child) -> std::io::Result<()> {
        let Some(process) = child.raw_handle() else {
            return Err(std::io::Error::other("child already reaped"));
        };
        // SAFETY: the job handle is live while `self` is, and `process` is
        // live while `child` (borrowed for the call) holds it.
        let ok = unsafe { win32_job::AssignProcessToJobObject(self.handle.as_ptr(), process) };
        if ok == 0 {
            return Err(std::io::Error::last_os_error());
        }
        Ok(())
    }
}

#[cfg(windows)]
impl Drop for JobObject {
    fn drop(&mut self) {
        // SAFETY: the handle came from CreateJobObjectW and is closed once.
        unsafe {
            win32_job::CloseHandle(self.handle.as_ptr());
        }
    }
}

/// The daemon-wide kill-on-close job, made on first use. It is never
/// dropped: its handle closes only when the daemon process ends, however it
/// ends, and Windows then ends every process in it. One job for the whole
/// process (not one per spawn) because callers turn a `SpawnedProcess` into
/// its bare `Child` and keep that for the run; a per-spawn job dropped there
/// would end the child at once.
#[cfg(windows)]
fn daemon_job() -> Option<&'static JobObject> {
    static JOB: std::sync::OnceLock<Option<JobObject>> = std::sync::OnceLock::new();
    JOB.get_or_init(|| match JobObject::kill_on_close() {
        Ok(job) => Some(job),
        Err(error) => {
            tracing::warn!(%error, "could not create the kill-on-close job object; spawned processes may outlive the daemon");
            None
        }
    })
    .as_ref()
}

/// Tie a freshly spawned child (and what it starts afterwards) to the
/// daemon's life: on Windows it joins the daemon-wide kill-on-close job, so a
/// killed or crashed daemon takes its process trees with it. Best effort: a
/// failure (say, a parent job that forbids nesting) is logged and the child
/// runs on. A no-op elsewhere, where process groups do this job.
pub fn bind_child_to_daemon_lifetime(child: &tokio::process::Child) {
    #[cfg(windows)]
    {
        let Some(job) = daemon_job() else {
            return;
        };
        if let Err(error) = job.assign(child) {
            tracing::debug!(%error, pid = child.id(), "could not add child to the kill-on-close job");
        }
    }
    #[cfg(not(windows))]
    let _ = child;
}

#[cfg(test)]
mod tests {
    use super::win32_job::*;
    use std::mem::{align_of, offset_of, size_of};

    /// The `winnt.h` layouts, checked on every host: a wrong size makes
    /// `SetInformationJobObject` fail with ERROR_BAD_LENGTH on Windows.
    #[test]
    fn job_limit_structs_match_winnt_layout() {
        let word = size_of::<usize>();
        assert_eq!(size_of::<IoCounters>(), 48);
        assert_eq!(offset_of!(JobObjectBasicLimitInformation, limit_flags), 16);
        assert_eq!(
            offset_of!(JobObjectExtendedLimitInformation, io_info),
            size_of::<JobObjectBasicLimitInformation>()
        );
        assert_eq!(
            offset_of!(JobObjectExtendedLimitInformation, process_memory_limit),
            size_of::<JobObjectBasicLimitInformation>() + 48
        );
        assert_eq!(
            size_of::<JobObjectExtendedLimitInformation>(),
            size_of::<JobObjectBasicLimitInformation>() + 48 + 4 * word
        );
        assert_eq!(align_of::<JobObjectExtendedLimitInformation>(), 8);
        assert_eq!(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, 0x2000);
        assert_eq!(JOB_OBJECT_EXTENDED_LIMIT_INFORMATION_CLASS, 9);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn job_limit_structs_match_winnt_layout_64_bit() {
        type Basic = JobObjectBasicLimitInformation;
        assert_eq!(offset_of!(Basic, per_process_user_time_limit), 0);
        assert_eq!(offset_of!(Basic, per_job_user_time_limit), 8);
        assert_eq!(offset_of!(Basic, limit_flags), 16);
        assert_eq!(offset_of!(Basic, minimum_working_set_size), 24);
        assert_eq!(offset_of!(Basic, maximum_working_set_size), 32);
        assert_eq!(offset_of!(Basic, active_process_limit), 40);
        assert_eq!(offset_of!(Basic, affinity), 48);
        assert_eq!(offset_of!(Basic, priority_class), 56);
        assert_eq!(offset_of!(Basic, scheduling_class), 60);
        assert_eq!(size_of::<Basic>(), 64);

        type Extended = JobObjectExtendedLimitInformation;
        assert_eq!(offset_of!(Extended, io_info), 64);
        assert_eq!(offset_of!(Extended, process_memory_limit), 112);
        assert_eq!(offset_of!(Extended, job_memory_limit), 120);
        assert_eq!(offset_of!(Extended, peak_process_memory_used), 128);
        assert_eq!(offset_of!(Extended, peak_job_memory_used), 136);
        assert_eq!(size_of::<Extended>(), 144);
    }

    /// On Windows, a child in the job is ended when the job closes.
    #[cfg(windows)]
    #[tokio::test]
    async fn closing_the_job_ends_its_process() {
        let job = super::JobObject::kill_on_close().expect("create job");
        let mut child = tokio::process::Command::new("cmd")
            .args(["/C", "ping -n 30 127.0.0.1 >NUL"])
            .stdout(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .expect("spawn");
        job.assign(&child).expect("assign");
        drop(job);
        let status = tokio::time::timeout(std::time::Duration::from_secs(10), child.wait())
            .await
            .expect("child ended with the job")
            .expect("wait");
        assert!(!status.success());
    }
}