1use std::io::{self, Read as _};
9use std::os::unix::process::CommandExt as _;
10use std::process::{Child, Command, ExitStatus, Output, Stdio};
11use std::sync::{Mutex, MutexGuard, PoisonError, mpsc};
12use std::time::{Duration, Instant};
13
14use crate::api;
15use rustix::process::{Pid, Signal, kill_process_group};
16
17#[derive(Debug)]
19pub struct Running(Mutex<Groups>);
20
21#[derive(Debug)]
22struct Groups {
23 running: Vec<Pid>,
25 stopped: bool,
27}
28
29pub static RUNNING: Running = Running::new();
31
32impl Default for Running {
33 fn default() -> Running {
34 Running::new()
35 }
36}
37
38impl Running {
39 pub const fn new() -> Running {
41 Running(Mutex::new(Groups {
42 running: Vec::new(),
43 stopped: false,
44 }))
45 }
46
47 fn lock(&self) -> MutexGuard<'_, Groups> {
48 self.0.lock().unwrap_or_else(PoisonError::into_inner)
49 }
50
51 pub fn stop(&self) {
53 let mut groups = self.lock();
54 groups.stopped = true;
55 for group in &groups.running {
56 let _ = kill_process_group(*group, Signal::KILL);
57 }
58 }
59
60 fn spawn(&self, command: &mut Command) -> io::Result<(Child, Pid)> {
62 let mut groups = self.lock();
63 if groups.stopped {
64 return Err(io::Error::other("runnerd is stopping"));
65 }
66 let child = command.process_group(0).spawn()?;
67 let group = Pid::from_child(&child);
68 groups.running.push(group);
69 Ok((child, group))
70 }
71
72 fn ended(&self, group: Pid) {
73 self.lock().running.retain(|running| *running != group);
74 }
75}
76
77pub fn output_within(
80 command: &mut Command,
81 deadline: Duration,
82 running: &Running,
83) -> io::Result<Output> {
84 let until = Instant::now() + deadline;
85 command
86 .stdin(Stdio::null())
87 .stdout(Stdio::piped())
88 .stderr(Stdio::piped());
89 let (mut child, group) = running.spawn(command)?;
90 let read = collect(&mut child, until);
91 if !matches!(read, Some(Ok(_))) {
92 let _ = kill_process_group(group, Signal::KILL);
94 }
95 let _ = child.wait();
97 running.ended(group);
98 read.ok_or_else(|| {
99 io::Error::new(
100 io::ErrorKind::TimedOut,
101 format!(
102 "it did not finish within {}",
103 api::duration(deadline.as_secs())
104 ),
105 )
106 })?
107}
108
109fn collect(child: &mut Child, until: Instant) -> Option<io::Result<Output>> {
111 let (sender, read) = mpsc::channel();
113 let pipes: [Option<Box<dyn io::Read + Send>>; 2] = [
114 child
115 .stdout
116 .take()
117 .map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
118 child
119 .stderr
120 .take()
121 .map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
122 ];
123 for (index, pipe) in pipes.into_iter().enumerate() {
124 let sender = sender.clone();
125 std::thread::spawn(move || {
127 let mut bytes = Vec::new();
128 if let Some(mut pipe) = pipe {
129 let _ = pipe.read_to_end(&mut bytes);
130 }
131 let _ = sender.send((index, bytes));
132 });
133 }
134 let status: ExitStatus = loop {
135 match child.try_wait() {
136 Ok(Some(status)) => break status,
137 Ok(None) => {}
138 Err(error) => return Some(Err(error)),
139 }
140 if Instant::now() >= until {
141 return None;
142 }
143 std::thread::sleep(Duration::from_millis(10));
144 };
145 let mut output = Output {
146 status,
147 stdout: Vec::new(),
148 stderr: Vec::new(),
149 };
150 for _ in 0..2 {
151 let (index, bytes) = read
152 .recv_timeout(until.saturating_duration_since(Instant::now()))
153 .ok()?;
154 if index == 0 {
155 output.stdout = bytes;
156 } else {
157 output.stderr = bytes;
158 }
159 }
160 Some(Ok(output))
161}
162
163#[cfg(test)]
164mod tests;