1use std::collections::VecDeque;
21use std::fs::File;
22use std::io::{BufRead, BufReader, Read};
23use std::path::Path;
24use std::process::{Child, Command, Stdio};
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::sync::{Arc, Mutex};
27use std::time::{Duration, Instant};
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum TreeRun {
32 Passed,
34 Failed(String),
37 TimedOut,
39 Cancelled,
41 Spawn(String),
43}
44
45const TAIL: usize = 64;
48
49const POLL: Duration = Duration::from_millis(20);
51
52const GRACE: Duration = Duration::from_millis(500);
54
55#[cfg(unix)]
57const NICENESS: i32 = 10;
58
59#[cfg(unix)]
60extern "C" {
61 #[link_name = "setpriority"]
62 fn libc_setpriority(which: i32, who: u32, prio: i32) -> i32;
63 #[link_name = "kill"]
64 fn libc_kill(pid: i32, sig: i32) -> i32;
65 #[link_name = "pipe"]
66 fn libc_pipe(fds: *mut i32) -> i32;
67}
68
69#[cfg(unix)]
72fn merged_pipe() -> Option<(File, Stdio, Stdio)> {
73 use std::os::unix::io::FromRawFd;
74 let mut fds = [0i32; 2];
75 if unsafe { libc_pipe(fds.as_mut_ptr()) } != 0 {
77 return None;
78 }
79 let (read, write) = unsafe { (File::from_raw_fd(fds[0]), File::from_raw_fd(fds[1])) };
81 let write2 = write.try_clone().ok()?;
82 Some((read, Stdio::from(write), Stdio::from(write2)))
83}
84
85#[cfg(unix)]
86const SIGTERM: i32 = 15;
87#[cfg(unix)]
88const SIGKILL: i32 = 9;
89
90#[cfg(unix)]
92fn signal_group(pgid: u32, sig: i32) -> bool {
93 unsafe { libc_kill(-(pgid as i32), sig) == 0 }
95}
96
97#[cfg(unix)]
99pub fn group_alive(pgid: u32) -> bool {
100 signal_group(pgid, 0)
101}
102
103#[cfg(unix)]
113static LIVE: std::sync::Mutex<Vec<u32>> = std::sync::Mutex::new(Vec::new());
114
115static DYING: AtomicBool = AtomicBool::new(false);
117
118pub(crate) fn is_dying() -> bool {
121 DYING.load(Ordering::SeqCst)
122}
123
124pub(crate) fn park_if_dying() {
128 while DYING.load(Ordering::SeqCst) {
129 std::thread::sleep(POLL);
130 }
131}
132
133#[cfg(unix)]
138pub(crate) fn mark_dying() {
139 DYING.store(true, Ordering::SeqCst);
140}
141
142#[cfg(unix)]
144struct Listed(u32);
145
146#[cfg(unix)]
147impl Listed {
148 fn new(pgid: u32) -> Listed {
149 LIVE.lock().unwrap_or_else(|p| p.into_inner()).push(pgid);
150 Listed(pgid)
151 }
152}
153
154#[cfg(unix)]
155impl Drop for Listed {
156 fn drop(&mut self) {
157 LIVE.lock()
158 .unwrap_or_else(|p| p.into_inner())
159 .retain(|g| *g != self.0);
160 }
161}
162
163#[cfg(unix)]
167pub fn reap_live() {
168 DYING.store(true, std::sync::atomic::Ordering::SeqCst);
172 let groups: Vec<u32> = LIVE.lock().unwrap_or_else(|p| p.into_inner()).clone();
173 if groups.is_empty() {
174 return;
175 }
176 for g in &groups {
177 signal_group(*g, SIGTERM);
178 }
179 let until = Instant::now() + GRACE;
180 while Instant::now() < until && groups.iter().any(|g| group_alive(*g)) {
181 std::thread::sleep(POLL);
182 }
183 for g in groups.iter().filter(|g| group_alive(**g)) {
184 signal_group(*g, SIGKILL);
185 }
186}
187
188#[cfg(not(unix))]
189pub fn reap_live() {}
190
191fn kill_tree(child: &mut Child) {
192 #[cfg(unix)]
193 {
194 let pgid = child.id();
195 signal_group(pgid, SIGTERM);
196 let until = Instant::now() + GRACE;
197 while Instant::now() < until {
198 let _ = child.try_wait();
201 if !group_alive(pgid) {
202 break;
203 }
204 std::thread::sleep(POLL);
205 }
206 if group_alive(pgid) {
207 signal_group(pgid, SIGKILL);
208 }
209 }
210 #[cfg(not(unix))]
211 {
212 let _ = Command::new("taskkill")
213 .args(["/PID", &child.id().to_string(), "/T", "/F"])
214 .stdin(Stdio::null())
215 .stdout(Stdio::null())
216 .stderr(Stdio::null())
217 .status();
218 }
219 let _ = child.kill();
220 let _ = child.wait();
221}
222
223fn drain(
224 stream: impl Read + Send + 'static,
225 tail: Arc<Mutex<VecDeque<String>>>,
226) -> std::thread::JoinHandle<()> {
227 std::thread::spawn(move || {
228 for line in BufReader::new(stream).lines().map_while(Result::ok) {
229 if let Ok(mut t) = tail.lock() {
230 if t.len() == TAIL {
231 t.pop_front();
232 }
233 t.push_back(line);
234 }
235 }
236 })
237}
238
239fn summary(tail: &Mutex<VecDeque<String>>) -> String {
240 tail.lock()
241 .ok()
242 .and_then(|t| {
243 t.iter()
244 .rev()
245 .map(|l| l.trim())
246 .find(|l| !l.is_empty())
247 .map(str::to_string)
248 })
249 .unwrap_or_else(|| "no output".to_string())
250}
251
252pub fn run(argv: &[String], cwd: &Path, deadline: Instant, cancel: &AtomicBool) -> TreeRun {
254 let ran = run_inner(argv, cwd, deadline, cancel, false).0;
255 park_if_dying();
256 ran
257}
258
259pub fn run_output(
262 argv: &[String],
263 cwd: &Path,
264 deadline: Instant,
265 cancel: &AtomicBool,
266) -> Result<String, TreeRun> {
267 let ran = run_inner(argv, cwd, deadline, cancel, true);
268 park_if_dying();
269 match ran {
270 (TreeRun::Passed, out) => Ok(out),
271 (other, _) => Err(other),
272 }
273}
274
275fn run_inner(
276 argv: &[String],
277 cwd: &Path,
278 deadline: Instant,
279 cancel: &AtomicBool,
280 need_output: bool,
281) -> (TreeRun, String) {
282 let Some((program, rest)) = argv.split_first() else {
283 return (TreeRun::Spawn("empty command".into()), String::new());
284 };
285 let mut cmd = Command::new(program);
286 cmd.args(rest).current_dir(cwd).stdin(Stdio::null());
287 #[cfg(unix)]
288 let merged = merged_pipe();
289 #[cfg(not(unix))]
290 let merged: Option<(File, Stdio, Stdio)> = None;
291 let reader = match merged {
292 Some((read, out, err)) => {
293 cmd.stdout(out).stderr(err);
294 Some(read)
295 }
296 None => {
297 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
298 None
299 }
300 };
301 crate::hooks::common::strip_git_env(&mut cmd);
302 #[cfg(unix)]
303 {
304 use std::os::unix::process::CommandExt;
305 cmd.process_group(0);
306 unsafe {
309 cmd.pre_exec(|| {
310 libc_setpriority(0, 0, NICENESS);
311 Ok(())
312 });
313 }
314 }
315 crate::staged_only::install_signal_handler();
318 let mut child = match cmd.spawn() {
319 Ok(c) => c,
320 Err(e) => return (TreeRun::Spawn(format!("{program}: {e}")), String::new()),
321 };
322 #[cfg(unix)]
323 let _listed = Listed::new(child.id());
324 drop(cmd);
327 let tail = Arc::new(Mutex::new(VecDeque::with_capacity(TAIL)));
328 let mut drains = Vec::new();
329 if let Some(read) = reader {
330 drains.push(drain(read, Arc::clone(&tail)));
331 }
332 if let Some(out) = child.stdout.take() {
333 drains.push(drain(out, Arc::clone(&tail)));
334 }
335 if let Some(err) = child.stderr.take() {
336 drains.push(drain(err, Arc::clone(&tail)));
337 }
338 loop {
339 match child.try_wait() {
340 Ok(Some(status)) => {
341 let until = if need_output {
348 deadline
349 } else {
350 Instant::now() + GRACE
351 };
352 while Instant::now() < until
353 && !(need_output && cancel.load(Ordering::SeqCst))
354 && drains.iter().any(|d| !d.is_finished())
355 {
356 std::thread::sleep(Duration::from_millis(5));
357 }
358 if need_output && cancel.load(Ordering::SeqCst) {
361 if drains.iter().any(|d| !d.is_finished()) {
362 kill_tree(&mut child);
363 }
364 return (TreeRun::Cancelled, String::new());
365 }
366 if need_output && drains.iter().any(|d| !d.is_finished()) {
367 kill_tree(&mut child);
373 let until = Instant::now() + GRACE;
377 while Instant::now() < until && drains.iter().any(|d| !d.is_finished()) {
378 std::thread::sleep(Duration::from_millis(5));
379 }
380 if !status.success() || drains.iter().any(|d| !d.is_finished()) {
381 return (TreeRun::TimedOut, String::new());
382 }
383 }
384 let out = tail
385 .lock()
386 .map(|t| t.iter().cloned().collect::<Vec<_>>().join("\n"))
387 .unwrap_or_default();
388 return if status.success() {
389 (TreeRun::Passed, out)
390 } else {
391 (TreeRun::Failed(summary(&tail)), out)
392 };
393 }
394 Ok(None) => {}
395 Err(e) => {
396 kill_tree(&mut child);
397 return (TreeRun::Spawn(format!("{program}: {e}")), String::new());
398 }
399 }
400 if cancel.load(Ordering::SeqCst) {
401 kill_tree(&mut child);
402 return (TreeRun::Cancelled, String::new());
403 }
404 if Instant::now() >= deadline {
405 kill_tree(&mut child);
406 return (TreeRun::TimedOut, String::new());
407 }
408 std::thread::sleep(POLL);
409 }
410}
411
412#[cfg(all(test, unix))]
413mod tests {
414 use super::*;
415
416 fn sh(script: &str) -> Vec<String> {
417 vec!["sh".into(), "-c".into(), script.into()]
418 }
419
420 fn soon(ms: u64) -> Instant {
421 Instant::now() + Duration::from_millis(ms)
422 }
423
424 #[test]
425 fn tree_run_passed() {
426 let r = run(
427 &sh("exit 0"),
428 Path::new("."),
429 soon(5_000),
430 &AtomicBool::new(false),
431 );
432 assert_eq!(r, TreeRun::Passed);
433 }
434
435 #[test]
436 fn tree_run_failed_summarises_the_last_line() {
437 let r = run(
438 &sh("echo 'a.ts: bad'; echo '3 problems' >&2; exit 1"),
439 Path::new("."),
440 soon(5_000),
441 &AtomicBool::new(false),
442 );
443 assert_eq!(r, TreeRun::Failed("3 problems".into()));
444 }
445
446 #[test]
447 fn tree_run_spawn_error() {
448 let r = run(
449 &["amont-no-such-program-xyz".to_string()],
450 Path::new("."),
451 soon(5_000),
452 &AtomicBool::new(false),
453 );
454 assert!(matches!(r, TreeRun::Spawn(_)), "{r:?}");
455 }
456
457 #[test]
464 fn tree_run_timed_out_leaves_no_child_alive() {
465 let dir = std::env::temp_dir().join(format!("amont-tree-run-{}", std::process::id()));
466 std::fs::create_dir_all(&dir).unwrap();
467 let pidfile = dir.join("grandchild.pid");
468 let script = format!("sleep 30 & echo $! > {}; wait", pidfile.display());
469 let r = run(&sh(&script), &dir, soon(3_000), &AtomicBool::new(false));
470 assert_eq!(r, TreeRun::TimedOut);
471 let pid: i32 = std::fs::read_to_string(&pidfile)
472 .unwrap()
473 .trim()
474 .parse()
475 .unwrap();
476 std::thread::sleep(Duration::from_millis(100));
477 let alive = unsafe { libc_kill(pid, 0) == 0 };
479 assert!(!alive, "grandchild {pid} survived the deadline");
480 let _ = std::fs::remove_dir_all(&dir);
481 }
482
483 #[test]
488 fn run_output_kills_a_child_left_holding_the_pipe_and_keeps_the_answer() {
489 let dir = std::env::temp_dir().join(format!("amont-probe-{}", std::process::id()));
490 std::fs::create_dir_all(&dir).unwrap();
491 let pgidfile = dir.join("group.pid");
492 let script = format!(
493 "echo $$ > {}; sleep 30 & echo 1.2.3; exit 0",
494 pgidfile.display()
495 );
496 let r = run_output(&sh(&script), &dir, soon(1_500), &AtomicBool::new(false));
497 assert_eq!(r.as_deref().map(str::trim), Ok("1.2.3"));
498 let pgid: u32 = std::fs::read_to_string(&pgidfile)
499 .unwrap()
500 .trim()
501 .parse()
502 .unwrap();
503 let until = Instant::now() + Duration::from_secs(2);
506 while group_alive(pgid) && Instant::now() < until {
507 std::thread::sleep(Duration::from_millis(20));
508 }
509 assert!(!group_alive(pgid), "the group {pgid} outlived the probe");
510 let _ = std::fs::remove_dir_all(&dir); }
512
513 #[test]
516 fn run_output_cancelled_returns_no_answer() {
517 let flag = Arc::new(AtomicBool::new(false));
518 let setter = Arc::clone(&flag);
519 std::thread::spawn(move || {
520 std::thread::sleep(Duration::from_millis(300));
521 setter.store(true, Ordering::SeqCst);
522 });
523 let r = run_output(
524 &sh("sleep 30 & echo 1.2.3; exit 0"),
525 Path::new("."),
526 soon(10_000),
527 &flag,
528 );
529 assert_eq!(r, Err(TreeRun::Cancelled));
530 }
531
532 #[test]
533 fn tree_run_cancelled() {
534 let flag = Arc::new(AtomicBool::new(false));
535 let setter = Arc::clone(&flag);
536 std::thread::spawn(move || {
537 std::thread::sleep(Duration::from_millis(150));
538 setter.store(true, Ordering::SeqCst);
539 });
540 let r = run(&sh("sleep 30"), Path::new("."), soon(10_000), &flag);
541 assert_eq!(r, TreeRun::Cancelled);
542 }
543}