rustsy-process 0.2.0-alpha.1

Declared process graphs with verified local artifact caching
Documentation
use crate::Node;
use std::{
    fs::File,
    io,
    path::Path,
    process::{Child, Command, Stdio},
    sync::atomic::{AtomicBool, Ordering},
    time::{Duration, Instant},
};

pub(crate) struct Execution {
    pub status: crate::Status,
    pub exit_code: Option<i32>,
    pub cpu_ns: Option<u64>,
    pub peak_job_commit_bytes: Option<u64>,
}

pub(crate) fn run(
    node: &Node,
    tool: &Path,
    cwd: &Path,
    logs: &Path,
    cancel: &AtomicBool,
) -> io::Result<Execution> {
    let mut command = Command::new(tool);
    command
        .args(&node.args)
        .current_dir(cwd)
        .env_clear()
        .envs(&node.env);
    command
        .stdin(Stdio::null())
        .stdout(File::create(logs.join("stdout"))?)
        .stderr(File::create(logs.join("stderr"))?);
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }
    let start = Instant::now();
    let mut child = command.spawn()?;
    let group = match Group::attach(&child, node.hard_ram_bytes) {
        Ok(group) => group,
        Err(e) => {
            let _ = child.kill();
            let _ = child.wait();
            return Err(e);
        }
    };
    let outcome: io::Result<_> = (|| {
        loop {
            if cancel.load(Ordering::Acquire)
                || start.elapsed() >= Duration::from_millis(node.timeout_ms)
            {
                group.stop(&mut child);
                let _ = child.wait();
                return Ok((
                    if cancel.load(Ordering::Acquire) {
                        crate::Status::Cancelled
                    } else {
                        crate::Status::Timeout
                    },
                    None,
                ));
            }
            if let Some(exit) = child.try_wait()? {
                return Ok((
                    if exit.success() {
                        crate::Status::Executed
                    } else {
                        crate::Status::Failed
                    },
                    exit.code(),
                ));
            }
            std::thread::sleep(Duration::from_millis(1));
        }
    })();
    #[cfg(windows)]
    // External processes that require persistent descendants must use another
    // integration. The job gives the caller a bounded lifetime for this action.
    group.stop(&mut child);
    if outcome.is_err() {
        group.stop(&mut child);
        let _ = child.wait();
    }
    let (status, exit_code) = outcome?;
    let (cpu_ns, peak_job_commit_bytes) = group.usage();
    Ok(Execution {
        status,
        exit_code,
        cpu_ns,
        peak_job_commit_bytes,
    })
}

#[cfg(windows)]
struct Group(std::os::windows::io::OwnedHandle);

#[cfg(windows)]
impl Group {
    fn attach(child: &Child, memory: usize) -> io::Result<Self> {
        use std::{
            os::windows::io::{AsRawHandle, FromRawHandle},
            ptr::null,
        };
        use windows_sys::Win32::System::JobObjects::*;

        // All pointers reference live Windows handles or initialized structures
        // whose sizes match the information class queried below.
        unsafe {
            let handle = CreateJobObjectW(null(), null());
            if handle.is_null() {
                return Err(io::Error::last_os_error());
            }
            let job = Self(std::os::windows::io::OwnedHandle::from_raw_handle(handle));
            let mut caps = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
            caps.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
            if memory != 0 {
                caps.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
                caps.JobMemoryLimit = memory;
            }
            if SetInformationJobObject(
                handle,
                JobObjectExtendedLimitInformation,
                std::ptr::from_ref(&caps).cast(),
                size_of_val(&caps) as u32,
            ) == 0
            {
                return Err(io::Error::last_os_error());
            }
            if AssignProcessToJobObject(handle, child.as_raw_handle()) == 0 {
                // A very short-lived child may exit before attachment.
                use windows_sys::Win32::System::Threading::GetExitCodeProcess;
                let mut code = 259;
                if GetExitCodeProcess(child.as_raw_handle(), &mut code) == 0 || code == 259 {
                    return Err(io::Error::last_os_error());
                }
            }
            Ok(job)
        }
    }

    fn stop(&self, child: &mut Child) {
        use std::os::windows::io::AsRawHandle;
        use windows_sys::Win32::System::JobObjects::TerminateJobObject;
        // Terminate only the unnamed job owned by this launcher.
        if unsafe { TerminateJobObject(self.0.as_raw_handle(), 1) } == 0 {
            let _ = child.kill();
        }
    }

    fn usage(&self) -> (Option<u64>, Option<u64>) {
        use std::{os::windows::io::AsRawHandle, ptr::null_mut};
        use windows_sys::Win32::System::JobObjects::*;
        let mut cpu = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
        let mut memory = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
        let handle = self.0.as_raw_handle();
        // The driver writes at most the supplied structure lengths.
        unsafe {
            let accounted = QueryInformationJobObject(
                handle,
                JobObjectBasicAccountingInformation,
                std::ptr::from_mut(&mut cpu).cast(),
                size_of_val(&cpu) as u32,
                null_mut(),
            ) != 0;
            let known_memory = QueryInformationJobObject(
                handle,
                JobObjectExtendedLimitInformation,
                std::ptr::from_mut(&mut memory).cast(),
                size_of_val(&memory) as u32,
                null_mut(),
            ) != 0;
            (
                accounted.then_some(
                    (cpu.TotalUserTime.saturating_add(cpu.TotalKernelTime).max(0) as u64)
                        .saturating_mul(100),
                ),
                known_memory.then_some(memory.PeakJobMemoryUsed as u64),
            )
        }
    }
}

#[cfg(not(windows))]
struct Group;

#[cfg(not(windows))]
impl Group {
    fn attach(_: &Child, memory: usize) -> io::Result<Self> {
        if memory != 0 {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "hard process RAM limit requires Windows Job Objects",
            ));
        }
        Ok(Self)
    }
    fn stop(&self, child: &mut Child) {
        #[cfg(unix)]
        if let Ok(pid) = i32::try_from(child.id()) {
            // The child was placed in its own process group before exec.
            unsafe {
                libc::kill(-pid, libc::SIGKILL);
            }
        }
        let _ = child.kill();
    }
    fn usage(&self) -> (Option<u64>, Option<u64>) {
        (None, None)
    }
}