1use std::ffi::OsStr;
5#[cfg(test)]
6use std::ffi::OsString;
7use std::io::{self, Read};
8use std::path::Path;
9#[cfg(test)]
10use std::path::PathBuf;
11use std::process::{Command, Stdio};
12use std::sync::mpsc;
13use std::time::{Duration, Instant};
14
15use cuno_core::Env;
16
17#[derive(Clone, Debug, Default)]
19pub struct Output {
20 pub success: bool,
22 pub stdout: Vec<u8>,
25 pub stderr: Vec<u8>,
27}
28
29pub trait Runner {
31 fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output>;
35
36 fn run_in(
39 &self,
40 program: &Path,
41 args: &[&OsStr],
42 env: &Env,
43 cwd: &Path,
44 ) -> std::io::Result<Output> {
45 let _ = cwd;
46 self.run(program, args, env)
47 }
48}
49
50pub const TOOL_TIMEOUT: Duration = Duration::from_secs(30);
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct SystemRunner {
58 limit: Duration,
60}
61
62impl SystemRunner {
63 pub const fn new() -> SystemRunner {
65 SystemRunner {
66 limit: TOOL_TIMEOUT,
67 }
68 }
69
70 pub const fn with_limit(limit: Duration) -> SystemRunner {
74 SystemRunner { limit }
75 }
76}
77
78impl Default for SystemRunner {
79 fn default() -> SystemRunner {
80 SystemRunner::new()
81 }
82}
83
84impl Runner for SystemRunner {
85 fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> io::Result<Output> {
88 self.wait(Command::new(program).args(args), env)
89 }
90
91 fn run_in(&self, program: &Path, args: &[&OsStr], env: &Env, cwd: &Path) -> io::Result<Output> {
92 self.wait(Command::new(program).args(args).current_dir(cwd), env)
93 }
94}
95
96impl SystemRunner {
97 fn wait(&self, command: &mut Command, env: &Env) -> io::Result<Output> {
100 let limit = self.limit;
101 let mut child = command
102 .env_clear()
103 .envs(env.vars())
104 .stdin(Stdio::null())
105 .stdout(Stdio::piped())
106 .stderr(Stdio::piped())
107 .spawn()?;
108 let timed_out = || {
109 io::Error::new(
110 io::ErrorKind::TimedOut,
111 format!(
112 "did not finish within {} seconds and was stopped",
113 limit.as_secs_f64()
114 ),
115 )
116 };
117 let drain = |pipe: Option<Box<dyn Read + Send>>| {
123 let (send, receive) = mpsc::channel();
124 std::thread::spawn(move || {
125 let mut bytes = Vec::new();
126 if let Some(mut pipe) = pipe {
127 let _ = pipe.read_to_end(&mut bytes);
128 }
129 let _ = send.send(bytes);
130 });
131 receive
132 };
133 let stdout = drain(child.stdout.take().map(|p| Box::new(p) as _));
134 let stderr = drain(child.stderr.take().map(|p| Box::new(p) as _));
135 let deadline = Instant::now() + limit;
136 let status = loop {
137 match child.try_wait() {
138 Ok(Some(status)) => break status,
139 Ok(None) => {}
140 Err(e) => {
142 let _ = child.kill();
143 let _ = child.wait();
144 return Err(e);
145 }
146 }
147 if Instant::now() >= deadline {
148 let _ = child.kill();
149 let _ = child.wait();
150 return Err(timed_out());
151 }
152 std::thread::sleep(Duration::from_millis(10));
153 };
154 let collect = |pipe: mpsc::Receiver<Vec<u8>>| {
155 pipe.recv_timeout(deadline.saturating_duration_since(Instant::now()))
156 .map_err(|_| timed_out())
157 };
158 Ok(Output {
159 success: status.success(),
160 stdout: collect(stdout)?,
161 stderr: collect(stderr)?,
162 })
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169 use cuno_core::NameCase;
170
171 #[cfg(windows)]
174 #[test]
175 fn the_child_sees_exactly_the_given_environment() {
176 let comspec = std::env::var_os("ComSpec").expect("ComSpec is set on Windows");
177 let root = std::env::var_os("SystemRoot").expect("SystemRoot is set on Windows");
178 let env = Env::from_pairs(
179 [
180 ("SystemRoot".into(), root),
181 ("CUNO_RUN_PROBE".into(), "given".into()),
182 ],
183 NameCase::Insensitive,
184 );
185 let out = SystemRunner::new()
186 .run(
187 comspec.as_ref(),
188 &["/d".as_ref(), "/c".as_ref(), "set".as_ref()],
189 &env,
190 )
191 .unwrap();
192 let text = String::from_utf8_lossy(&out.stdout);
193 assert!(text.lines().any(|l| l == "CUNO_RUN_PROBE=given"), "{text}");
194 assert!(
195 !text
196 .lines()
197 .any(|l| l.to_ascii_uppercase().starts_with("PATH=")),
198 "{text}"
199 );
200 }
201
202 fn helper(name: &str) -> (PathBuf, Vec<OsString>) {
207 let args = ["--ignored", "--exact", name, "--nocapture"]
208 .map(OsString::from)
209 .to_vec();
210 (std::env::current_exe().unwrap(), args)
211 }
212
213 fn run_helper(runner: SystemRunner, name: &str, env: &Env) -> io::Result<Output> {
214 let (program, args) = helper(name);
215 let args: Vec<&OsStr> = args.iter().map(|a| a.as_os_str()).collect();
216 runner.run(&program, &args, env)
217 }
218
219 fn limited(limit: Duration) -> SystemRunner {
220 SystemRunner { limit }
221 }
222
223 #[test]
225 #[ignore]
226 fn sleeps_then_marks() {
227 if let Some(marker) = std::env::var_os("CUNO_SLEEP_MARKER") {
228 std::thread::sleep(Duration::from_secs(3));
229 std::fs::write(marker, "finished").unwrap();
230 }
231 }
232
233 #[test]
236 #[ignore]
237 fn exits_leaving_a_sleeper() {
238 if std::env::var_os("CUNO_LEAVE_SLEEPER").is_some() {
239 let (program, args) = helper("run::tests::sleeps_then_marks");
240 #[allow(clippy::zombie_processes)]
242 Command::new(program)
243 .args(args)
244 .stdout(Stdio::inherit())
245 .spawn()
246 .unwrap();
247 }
248 }
249
250 #[test]
252 #[ignore]
253 fn floods_both_streams_then_fails() {
254 if std::env::var_os("CUNO_FLOOD").is_some() {
255 use std::io::Write;
256 let line = "0123456789abcdef".repeat(64);
257 for _ in 0..200 {
258 println!("out {line}");
259 let _ = writeln!(io::stderr(), "err {line}");
260 }
261 std::process::exit(3);
262 }
263 }
264
265 #[test]
267 #[ignore]
268 fn reads_stdin_to_the_end() {
269 if std::env::var_os("CUNO_READ_STDIN").is_some() {
270 let mut input = Vec::new();
271 io::stdin().read_to_end(&mut input).unwrap();
272 println!("stdin ended");
273 }
274 }
275
276 #[test]
279 #[ignore]
280 fn runs_a_reader_of_stdin() {
281 if std::env::var_os("CUNO_RUN_READER").is_some() {
282 let env = Env::from_process()
283 .without(&["CUNO_RUN_READER"])
284 .with("CUNO_READ_STDIN", "1".into());
285 match run_helper(
286 limited(Duration::from_secs(5)),
287 "run::tests::reads_stdin_to_the_end",
288 &env,
289 ) {
290 Ok(out) => println!(
291 "reader: {}",
292 String::from_utf8_lossy(&out.stdout).contains("stdin ended")
293 ),
294 Err(e) => println!("reader: {e}"),
295 }
296 }
297 }
298
299 #[test]
302 fn the_system_runner_stops_tools_after_thirty_seconds() {
303 assert_eq!(TOOL_TIMEOUT, Duration::from_secs(30));
304 assert_eq!(SystemRunner::new().limit, TOOL_TIMEOUT);
305 assert_eq!(SystemRunner::default(), SystemRunner::new());
306 }
307
308 #[test]
313 fn a_tool_past_the_limit_is_stopped() {
314 let dir = tempfile::tempdir().unwrap();
315 let marker = dir.path().join("marker");
316 let env = Env::from_process().with("CUNO_SLEEP_MARKER", marker.clone().into());
317 let started = Instant::now();
318 let err = run_helper(
319 limited(Duration::from_millis(300)),
320 "run::tests::sleeps_then_marks",
321 &env,
322 )
323 .unwrap_err();
324 assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}");
325 assert!(err.to_string().contains("0.3 seconds"), "{err}");
326 assert!(
327 started.elapsed() < Duration::from_secs(2),
328 "{:?}",
329 started.elapsed()
330 );
331 std::thread::sleep(Duration::from_secs(4));
332 assert!(!marker.exists(), "the tool kept running after the limit");
333 }
334
335 #[test]
338 fn output_held_open_after_exit_is_waited_for_only_until_the_limit() {
339 let dir = tempfile::tempdir().unwrap();
340 let env = Env::from_process()
341 .with("CUNO_SLEEP_MARKER", dir.path().join("marker").into())
342 .with("CUNO_LEAVE_SLEEPER", "1".into());
343 let started = Instant::now();
344 let err = run_helper(
345 limited(Duration::from_millis(1500)),
346 "run::tests::exits_leaving_a_sleeper",
347 &env,
348 )
349 .unwrap_err();
350 assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}");
351 assert!(
352 started.elapsed() < Duration::from_millis(2500),
353 "{:?}",
354 started.elapsed()
355 );
356 }
357
358 #[test]
362 fn a_failing_tool_returns_both_streams_in_full() {
363 let env = Env::from_process().with("CUNO_FLOOD", "1".into());
364 let out = run_helper(
365 limited(Duration::from_secs(20)),
366 "run::tests::floods_both_streams_then_fails",
367 &env,
368 )
369 .unwrap();
370 assert!(!out.success);
371 let count = |bytes: &[u8], prefix: &str| {
372 String::from_utf8_lossy(bytes)
373 .lines()
374 .filter(|l| l.starts_with(prefix))
375 .count()
376 };
377 assert_eq!(count(&out.stdout, "out "), 200);
378 assert_eq!(count(&out.stderr, "err "), 200);
379 assert_eq!(count(&out.stdout, "err "), 0);
380 }
381
382 #[test]
386 fn a_tool_sees_its_stdin_closed() {
387 let (program, args) = helper("run::tests::runs_a_reader_of_stdin");
388 let mut middle = Command::new(program)
389 .args(args)
390 .env("CUNO_RUN_READER", "1")
391 .stdin(Stdio::piped())
392 .stdout(Stdio::piped())
393 .spawn()
394 .unwrap();
395 let _open = middle.stdin.take();
396 let mut text = String::new();
397 middle
398 .stdout
399 .take()
400 .unwrap()
401 .read_to_string(&mut text)
402 .unwrap();
403 middle.wait().unwrap();
404 assert!(text.contains("reader: true"), "{text}");
405 }
406}