use std::io::{self, Read as _};
use std::os::unix::process::CommandExt as _;
use std::process::{Child, Command, ExitStatus, Output, Stdio};
use std::sync::{Mutex, MutexGuard, PoisonError, mpsc};
use std::time::{Duration, Instant};
use crate::api;
use rustix::process::{Pid, Signal, kill_process_group};
#[derive(Debug)]
pub struct Running(Mutex<Groups>);
#[derive(Debug)]
struct Groups {
running: Vec<Pid>,
stopped: bool,
}
pub static RUNNING: Running = Running::new();
impl Default for Running {
fn default() -> Running {
Running::new()
}
}
impl Running {
pub const fn new() -> Running {
Running(Mutex::new(Groups {
running: Vec::new(),
stopped: false,
}))
}
fn lock(&self) -> MutexGuard<'_, Groups> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn stop(&self) {
let mut groups = self.lock();
groups.stopped = true;
for group in &groups.running {
let _ = kill_process_group(*group, Signal::KILL);
}
}
fn spawn(&self, command: &mut Command) -> io::Result<(Child, Pid)> {
let mut groups = self.lock();
if groups.stopped {
return Err(io::Error::other("runnerd is stopping"));
}
let child = command.process_group(0).spawn()?;
let group = Pid::from_child(&child);
groups.running.push(group);
Ok((child, group))
}
fn ended(&self, group: Pid) {
self.lock().running.retain(|running| *running != group);
}
}
pub fn output_within(
command: &mut Command,
deadline: Duration,
running: &Running,
) -> io::Result<Output> {
let until = Instant::now() + deadline;
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let (mut child, group) = running.spawn(command)?;
let read = collect(&mut child, until);
if !matches!(read, Some(Ok(_))) {
let _ = kill_process_group(group, Signal::KILL);
}
let _ = child.wait();
running.ended(group);
read.ok_or_else(|| {
io::Error::new(
io::ErrorKind::TimedOut,
format!(
"it did not finish within {}",
api::duration(deadline.as_secs())
),
)
})?
}
fn collect(child: &mut Child, until: Instant) -> Option<io::Result<Output>> {
let (sender, read) = mpsc::channel();
let pipes: [Option<Box<dyn io::Read + Send>>; 2] = [
child
.stdout
.take()
.map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
child
.stderr
.take()
.map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
];
for (index, pipe) in pipes.into_iter().enumerate() {
let sender = sender.clone();
std::thread::spawn(move || {
let mut bytes = Vec::new();
if let Some(mut pipe) = pipe {
let _ = pipe.read_to_end(&mut bytes);
}
let _ = sender.send((index, bytes));
});
}
let status: ExitStatus = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) => {}
Err(error) => return Some(Err(error)),
}
if Instant::now() >= until {
return None;
}
std::thread::sleep(Duration::from_millis(10));
};
let mut output = Output {
status,
stdout: Vec::new(),
stderr: Vec::new(),
};
for _ in 0..2 {
let (index, bytes) = read
.recv_timeout(until.saturating_duration_since(Instant::now()))
.ok()?;
if index == 0 {
output.stdout = bytes;
} else {
output.stderr = bytes;
}
}
Some(Ok(output))
}
#[cfg(test)]
mod tests;