Skip to main content

greengate_runtime/
tree_run.rs

1//! Running one tree gate's command with a deadline (ADR-0024).
2//!
3//! A tree gate is optional work beside the commit's real checks, so it must
4//! never outlive the time it was given, and never leave anything running when
5//! it is stopped:
6//!
7//! - it runs in its **own process group**, reniced so it yields CPU to the
8//!   mandatory checks;
9//! - it has a hard **deadline** and a **cancel** flag (the dispatcher sets it
10//!   when the slack after the mandatory checks runs out);
11//! - on either, the **whole group** is killed (TERM, then KILL) before this
12//!   returns, so a lock held for the run is released only once nothing that
13//!   could still write the cache is alive.
14//!
15//! The outcome is richer than `common::run_quiet`'s `bool`. The caller needs to
16//! tell a lint failure (withhold the stamp, say how many problems) from a
17//! timeout or a cancel (the cache was not proven cold or warm) from a tool that
18//! could not start.
19
20use 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/// How a tree gate's run ended.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub enum TreeRun {
32    /// Exit 0.
33    Passed,
34    /// Non-zero exit, with a one-line summary (the tool's last non-empty
35    /// output line, e.g. eslint's `✖ 3 problems (3 errors, 0 warnings)`).
36    Failed(String),
37    /// The deadline passed; the group was killed.
38    TimedOut,
39    /// The cancel flag was set; the group was killed.
40    Cancelled,
41    /// The command could not be started.
42    Spawn(String),
43}
44
45/// Lines of output kept for the summary. The tool's output is not shown: a
46/// tree gate never decides the commit, so its findings are CI's to print.
47const TAIL: usize = 64;
48
49/// How often the runner looks at the child, the deadline and the flag.
50const POLL: Duration = Duration::from_millis(20);
51
52/// How long TERM gets before KILL.
53const GRACE: Duration = Duration::from_millis(500);
54
55/// Nice increment for a tree gate: below the mandatory checks, not starved.
56#[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/// One pipe for BOTH stdout and stderr, as `2>&1` would: the tool's lines
70/// arrive in the order it wrote them, so "the last line" means something.
71#[cfg(unix)]
72fn merged_pipe() -> Option<(File, Stdio, Stdio)> {
73    use std::os::unix::io::FromRawFd;
74    let mut fds = [0i32; 2];
75    // SAFETY: `fds` is two writable ints, which is all `pipe` writes.
76    if unsafe { libc_pipe(fds.as_mut_ptr()) } != 0 {
77        return None;
78    }
79    // SAFETY: both fds were just created and are owned by nobody else.
80    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/// Signal every process in `pgid`'s group. `kill(-pgid, sig)`.
91#[cfg(unix)]
92fn signal_group(pgid: u32, sig: i32) -> bool {
93    // SAFETY: plain integers in, an int out; no memory is shared.
94    unsafe { libc_kill(-(pgid as i32), sig) == 0 }
95}
96
97/// Whether any process of the group is still alive (`kill(-pgid, 0)`).
98#[cfg(unix)]
99pub fn group_alive(pgid: u32) -> bool {
100    signal_group(pgid, 0)
101}
102
103/// The process groups of tree gates running right now.
104///
105/// A gate's own process group is what lets a timeout or a cancel kill the
106/// whole tree it forked — and also what hides it from a signal sent to amont:
107/// `kill <pid>`, a tool's timeout, the group of the `git push` that ran the
108/// hook. Fifteen `uv run pyright` groups from killed pushes were found alive
109/// 3 hours to 3 days later, re-parented to init (amont#302). So every running
110/// group is listed here, and the signal watcher (`staged_only`) reaps the list
111/// before amont re-raises and dies.
112#[cfg(unix)]
113static LIVE: std::sync::Mutex<Vec<u32>> = std::sync::Mutex::new(Vec::new());
114
115/// Set once amont is dying of a signal; see [`reap_live`].
116static DYING: AtomicBool = AtomicBool::new(false);
117
118/// Is amont dying of a signal right now? For code that must undo what it just
119/// did before it parks ([`park_if_dying`]).
120pub(crate) fn is_dying() -> bool {
121    DYING.load(Ordering::SeqCst)
122}
123
124/// Hold the calling thread while amont dies of a signal: the watcher thread
125/// re-raises it with the default disposition, which ends the process. Never
126/// returns once `DYING` is set; returns at once otherwise.
127pub(crate) fn park_if_dying() {
128    while DYING.load(Ordering::SeqCst) {
129        std::thread::sleep(POLL);
130    }
131}
132
133/// Record that amont is dying of a signal, before the watcher thread has run:
134/// from the signal handler itself, so a Ctrl-C that also killed a child can
135/// never be seen by the code that child's death unblocks as "not dying". One
136/// atomic store, which is async-signal-safe.
137#[cfg(unix)]
138pub(crate) fn mark_dying() {
139    DYING.store(true, Ordering::SeqCst);
140}
141
142/// Lists `pgid` in [`LIVE`] for as long as it is held.
143#[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/// Kill every tree gate still running: TERM, the same grace as a timeout,
164/// then KILL. Called by the signal watcher in ordinary thread context, never
165/// from the handler itself. A no-op when no gate runs.
166#[cfg(unix)]
167pub fn reap_live() {
168    // Before the kill: a gate that dies of THIS reap must not return to its
169    // caller, which would finish and exit 0 before the watcher re-raises —
170    // a killed amont reporting success. `run_output` parks instead.
171    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            // Reap the leader so its pid cannot linger as a zombie in the
199            // group, then ask whether anybody else is left.
200            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
252/// Run `argv` in `cwd` until it exits, `deadline` passes, or `cancel` is set.
253pub 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
259/// [`run`], returning the tool's output (its last lines) on success — for a
260/// bounded, cancellable probe such as `<tool> --version`.
261pub 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        // SAFETY: `setpriority` is async-signal-safe and touches no memory;
307        // it lowers only this child's priority, between fork and exec.
308        unsafe {
309            cmd.pre_exec(|| {
310                libc_setpriority(0, 0, NICENESS);
311                Ok(())
312            });
313        }
314    }
315    // Armed before the spawn: a signal landing between the spawn and the
316    // listing would otherwise find nothing to reap. Idempotent.
317    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    // The parent's copies of the write end went into `cmd` and die with it,
325    // so the reader sees EOF once every process holding the pipe has exited.
326    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                // Read to EOF before summarising — bounded, because a
342                // grandchild the tool left behind may still hold the pipe. A
343                // caller that needs the OUTPUT (a version probe) waits up to
344                // its own deadline or cancel: on a loaded machine the reader
345                // can lag the exit, and a half-read version would silently
346                // name another cache namespace.
347                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                // A cancelled probe answers nothing, whatever it printed: a
359                // caller that cancelled must not get a version to act on.
360                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                    // The tool exited, but something it started still holds
368                    // the pipe past the deadline: kill the group, or that
369                    // process outlives the probe. The leader is already
370                    // reaped; `kill_tree` signals by its group id, which no
371                    // new process can take while a member is alive.
372                    kill_tree(&mut child);
373                    // With the holders dead the pipe closes, so the readers
374                    // reach EOF and the output is whole — what a successful
375                    // tool printed is still its answer.
376                    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    /// The deadline kills the WHOLE group: a grandchild the tool forked must
458    /// not survive it (it could still be writing the cache).
459    ///
460    /// Three seconds for the shell to fork and record its grandchild: at
461    /// 400 ms, a loaded machine killed the shell before it wrote the pid
462    /// file, and the test failed on reading it rather than on a survivor.
463    #[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        // SAFETY: probing a pid with signal 0.
478        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    /// A probe whose tool EXITS but leaves a child holding the pipe: the
484    /// output wait reaches the deadline, the child's group dies with it (the
485    /// leader is already reaped, so this is a different branch from the one
486    /// above), and what the tool printed before exiting 0 is still returned.
487    #[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        // Polled, not checked once: a killed member answers `kill -0` until it
504        // is reaped.
505        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); // best-effort temp cleanup; a leftover dir fails nothing
511    }
512
513    /// A probe cancelled while a child holds its pipe answers nothing, even
514    /// though the tool itself exited 0 with a version.
515    #[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}