Skip to main content

xtask/
watchdog.rs

1//! Runs a command that is expected to keep talking, and diagnoses it if it stops.
2//!
3//! A coverage run hung for over an hour: two web integration tests stopped
4//! producing output while the job's heartbeat kept pulsing, so nothing looked
5//! wrong until the deadline killed it — with no indication of which tests were
6//! responsible. Diagnosing it meant catching the pod live and hand-running
7//! `pg_stat_activity` and `/proc` inspection before it disappeared. The next
8//! occurrence should arrive already diagnosed.
9//!
10//! Only for commands whose silence is itself a symptom. The musl link is quiet
11//! for twelve minutes and is perfectly healthy; wrapping that would be a way to
12//! kill good builds.
13
14mod cpu;
15mod group;
16mod supervised;
17
18use std::io::{BufRead, BufReader};
19use std::os::unix::process::CommandExt;
20use std::process::{Child, Command, ExitStatus, Stdio};
21use std::sync::Arc;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::time::{Duration, Instant};
24
25use anyhow::{Context, Result, bail};
26use group::Group;
27pub use group::Termination;
28pub use supervised::run_supervised;
29
30/// How long a watched command may produce nothing and do no CPU work before
31/// it is declared stuck.
32///
33/// Silence alone is not enough: a test binary whose last test runs for many
34/// minutes prints nothing meanwhile, yet keeps every core busy. The hang this
35/// exists for was silent and idle for eleven minutes.
36pub const STALL: Duration = Duration::from_secs(300);
37
38/// CPU time the process tree must spend for its silence to count as work.
39const BUSY_TICKS: u64 = cpu::TICKS_PER_SECOND;
40
41/// Runs a command, forwarding its output, and fails if it goes quiet.
42///
43/// `database_url` is the database the child works against, queried for
44/// diagnostics if it stalls; the ambient `DATABASE_URL` is deliberately not
45/// consulted, as it may name a different server.
46pub fn run_watched(
47    program: &str,
48    args: &[&str],
49    env: &[(&str, &str)],
50    database_url: Option<&str>,
51) -> Result<()> {
52    run_watched_for(program, args, env, database_url, STALL)
53}
54
55/// As [`run_watched`], with the silence budget supplied.
56///
57/// Exists so the stall path itself is testable: a test cannot wait out the real
58/// five minutes, and a guard that has never fired is not known to work.
59pub fn run_watched_for(
60    program: &str,
61    args: &[&str],
62    env: &[(&str, &str)],
63    database_url: Option<&str>,
64    stall: Duration,
65) -> Result<()> {
66    let termination = Termination::watch()?;
67    let mut command = Command::new(program);
68    command
69        .args(args)
70        .stdout(Stdio::piped())
71        .stderr(Stdio::piped())
72        .process_group(0);
73    for (key, value) in env {
74        command.env(key, value);
75    }
76    let mut child = command
77        .spawn()
78        .with_context(|| format!("failed to run {program}"))?;
79
80    let last_output = Arc::new(AtomicU64::new(0));
81    let started = Instant::now();
82
83    let mut pumps = Vec::new();
84    if let Some(stdout) = child.stdout.take() {
85        pumps.push(pump(stdout, Arc::clone(&last_output), started, false));
86    }
87    if let Some(stderr) = child.stderr.take() {
88        pumps.push(pump(stderr, Arc::clone(&last_output), started, true));
89    }
90
91    let group = Group::of(&child);
92    let verdict = watch(
93        &mut child,
94        &group,
95        &termination,
96        &last_output,
97        started,
98        stall,
99        database_url,
100    );
101    group.kill();
102    let _ = child.wait();
103    for pump in pumps {
104        let _ = pump.join();
105    }
106
107    match verdict? {
108        Verdict::Exited(status) if status.success() => Ok(()),
109        Verdict::Exited(status) => bail!("{program} {} exited with {status}", args.join(" ")),
110        Verdict::Terminated => bail!("{program} interrupted by a termination signal"),
111        Verdict::Stalled { quiet, detected } => bail!(
112            "{program} produced no output for {quiet}s and sat idle, killed \
113             {}ms after the stall was seen — see the diagnostics above. This is the \
114             silent-hang failure mode, not a slow build.",
115            detected.elapsed().as_millis()
116        ),
117    }
118}
119
120enum Verdict {
121    Exited(ExitStatus),
122    Terminated,
123    Stalled { quiet: u64, detected: Instant },
124}
125
126/// Polls the child until it exits, is told to stop, or goes quiet; on a stall
127/// the diagnostics are gathered here, with the group frozen but alive.
128fn watch(
129    child: &mut Child,
130    group: &Group,
131    termination: &Termination,
132    last_output: &AtomicU64,
133    started: Instant,
134    stall: Duration,
135    database_url: Option<&str>,
136) -> Result<Verdict> {
137    let mut cpu_mark = cpu::tree_ticks(child.id());
138    let mut last_busy = 0;
139    loop {
140        if let Some(status) = child.try_wait().context("waiting on the child")? {
141            return Ok(Verdict::Exited(status));
142        }
143        if termination.requested() {
144            return Ok(Verdict::Terminated);
145        }
146        let now = started.elapsed().as_secs();
147        let ticks = cpu::tree_ticks(child.id());
148        if follow_cpu(&mut cpu_mark, ticks) {
149            last_busy = now;
150        }
151        let quiet = now.saturating_sub(last_output.load(Ordering::Relaxed).max(last_busy));
152        if quiet > stall.as_secs() {
153            let detected = Instant::now();
154            let threads = group.thread_states();
155            group.freeze();
156            diagnose(quiet, &threads, database_url);
157            return Ok(Verdict::Stalled { quiet, detected });
158        }
159        std::thread::sleep(Duration::from_millis(500));
160    }
161}
162
163/// Moves `mark` to `ticks` in either direction; true when the tree gained at
164/// least [`BUSY_TICKS`] since the mark. Following a drop keeps a total that
165/// fell from hiding later work.
166fn follow_cpu(mark: &mut u64, ticks: u64) -> bool {
167    let busy = ticks.saturating_sub(*mark) >= BUSY_TICKS;
168    if busy || ticks < *mark {
169        *mark = ticks;
170    }
171    busy
172}
173
174/// Forwards a stream line by line, recording when each line arrived.
175fn pump<R: std::io::Read + Send + 'static>(
176    stream: R,
177    last_output: Arc<AtomicU64>,
178    started: Instant,
179    is_stderr: bool,
180) -> std::thread::JoinHandle<()> {
181    std::thread::spawn(move || {
182        for line in BufReader::new(stream).lines().map_while(Result::ok) {
183            last_output.store(started.elapsed().as_secs(), Ordering::Relaxed);
184            if is_stderr {
185                eprintln!("{line}");
186            } else {
187                println!("{line}");
188            }
189        }
190    })
191}
192
193/// Everything worth knowing about a stuck run, gathered with the process tree
194/// frozen, before it is killed, because killing it drops the database
195/// connections and the process tree being diagnosed.
196///
197/// Each of these had to be gathered by hand from a live pod last time, racing
198/// the job's deadline. The database view is the one that mattered: connections
199/// sitting `idle / ClientRead` while the client waited on the socket is what
200/// identified a desynchronised connection rather than a slow query.
201fn diagnose(quiet: u64, threads: &[String], database_url: Option<&str>) {
202    eprintln!(
203        "\n>> STALL: no output and no CPU work for {quiet}s — child frozen, collecting diagnostics\n"
204    );
205
206    for (title, args) in database_diagnostics(database_url) {
207        eprintln!(">> {title}:");
208        report("psql", &args);
209    }
210
211    eprintln!(">> thread states of the stuck process tree:");
212    for line in threads {
213        eprintln!("{line}");
214    }
215    eprintln!(">> processes:");
216    report("ps", &["-eo", "pid,ppid,etime,stat,pcpu,args"]);
217    eprintln!();
218}
219
220/// The psql invocations that describe the database the child was given; none
221/// without one, since the ambient server is not the child's.
222fn database_diagnostics(database_url: Option<&str>) -> Vec<(&'static str, [&str; 3])> {
223    let Some(url) = database_url else {
224        return Vec::new();
225    };
226    vec![
227        (
228            "database activity",
229            [
230                url,
231                "-tAc",
232                "select pid, state, wait_event_type, wait_event, \
233                 left(replace(query, chr(10), ' '), 80) from pg_stat_activity \
234                 where backend_type = 'client backend'",
235            ],
236        ),
237        (
238            "locks not granted",
239            [
240                url,
241                "-tAc",
242                "select pid, relation::regclass, mode from pg_locks where not granted",
243            ],
244        ),
245    ]
246}
247
248/// How long one diagnostic may run; a hung `psql` must not hold the failure back.
249const REPORT_LIMIT_SECS: &str = "10";
250
251/// Best effort: a diagnostic that cannot run must not mask the stall itself.
252fn report(program: &str, args: &[&str]) {
253    report_within(REPORT_LIMIT_SECS, program, args);
254}
255
256fn report_within(limit_secs: &str, program: &str, args: &[&str]) {
257    let run = Command::new("timeout")
258        .args(["--kill-after=1", limit_secs, program])
259        .args(args)
260        .output();
261    match run {
262        Ok(out) => {
263            for line in String::from_utf8_lossy(&out.stdout).lines().take(40) {
264                eprintln!("   {line}");
265            }
266        }
267        Err(err) => eprintln!("   ({program} unavailable: {err})"),
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use nix::sys::signal::{Signal, raise};
275
276    /// A command that keeps talking must not be killed, however long it runs.
277    #[test]
278    fn a_chatty_command_is_left_alone() {
279        let _processes = crate::test_support::processes();
280        // Prints for longer than a stall check cycle, in small gaps.
281        let out = run_watched(
282            "bash",
283            &["-c", "for i in 1 2 3 4 5; do echo line $i; sleep 0.3; done"],
284            &[],
285            None,
286        );
287        assert!(
288            out.is_ok(),
289            "a command producing output must not be stalled: {out:?}"
290        );
291    }
292
293    #[test]
294    fn cpu_work_above_a_lowered_mark_is_activity() {
295        let mut mark = 5_000;
296        assert!(!follow_cpu(&mut mark, 1_000));
297        assert_eq!(mark, 1_000);
298        assert!(follow_cpu(&mut mark, 1_000 + BUSY_TICKS));
299        assert_eq!(mark, 1_000 + BUSY_TICKS);
300    }
301
302    #[test]
303    fn cpu_below_the_busy_threshold_keeps_the_mark() {
304        let mut mark = 1_000;
305        assert!(!follow_cpu(&mut mark, 1_000 + BUSY_TICKS - 1));
306        assert_eq!(mark, 1_000);
307    }
308
309    fn killed_after_ms(text: &str) -> u64 {
310        text.split("killed ")
311            .nth(1)
312            .and_then(|rest| rest.split("ms").next())
313            .and_then(|ms| ms.trim().parse().ok())
314            .unwrap_or(u64::MAX)
315    }
316
317    /// The guard must actually fire, kill the child, and say so.
318    #[test]
319    fn a_silent_command_is_stalled_and_killed() {
320        let _processes = crate::test_support::processes();
321        let started = Instant::now();
322        let err = run_watched_for(
323            "bash",
324            &["-c", "echo starting; sleep 120"],
325            &[],
326            None,
327            Duration::from_secs(2),
328        )
329        .expect_err("a command silent past its budget must fail");
330
331        let text = format!("{err}");
332        assert!(text.contains("no output for"), "{text}");
333        assert!(
334            killed_after_ms(&text) < 5_000,
335            "the child was not killed promptly after the stall: {text}"
336        );
337        assert!(
338            started.elapsed() < Duration::from_secs(60),
339            "the stalled run took {:?} end to end",
340            started.elapsed()
341        );
342    }
343
344    fn pid_alive(pid: i32) -> bool {
345        std::fs::read_to_string(format!("/proc/{pid}/stat"))
346            .is_ok_and(|stat| !stat.contains(") Z "))
347    }
348
349    /// The kill must take the whole process tree, not only the direct child.
350    #[test]
351    fn a_stalled_run_kills_its_grandchildren() {
352        let _processes = crate::test_support::processes();
353        let dir = tempfile::tempdir().expect("tempdir");
354        let pid_file = dir.path().join("grandchild.pid");
355        let script = format!("sleep 120 & echo $! > {}; wait", pid_file.display());
356        run_watched_for("bash", &["-c", &script], &[], None, Duration::from_secs(2))
357            .expect_err("a silent command must be stalled");
358
359        let pid: i32 = std::fs::read_to_string(&pid_file)
360            .expect("the grandchild recorded its pid")
361            .trim()
362            .parse()
363            .expect("numeric pid");
364        std::thread::sleep(Duration::from_millis(200));
365        assert!(!pid_alive(pid), "grandchild {pid} survived the stall kill");
366    }
367
368    /// Ctrl-C reaches xtask, not the child's own process group: it must be passed on.
369    #[test]
370    fn a_termination_signal_takes_the_whole_group_down() {
371        let _processes = crate::test_support::processes();
372        let dir = tempfile::tempdir().expect("tempdir");
373        let pid_file = dir.path().join("grandchild.pid");
374        let script = format!("sleep 120 & echo $! > {}; wait", pid_file.display());
375        let marker = pid_file.clone();
376        let sender = std::thread::spawn(move || {
377            let deadline = Instant::now() + Duration::from_secs(10);
378            while !marker.exists() && Instant::now() < deadline {
379                std::thread::sleep(Duration::from_millis(20));
380            }
381            raise(Signal::SIGTERM)
382        });
383        let err = run_watched_for("bash", &["-c", &script], &[], None, Duration::from_secs(60))
384            .expect_err("a terminated run must fail");
385        sender.join().expect("sender").expect("raise");
386
387        assert!(format!("{err}").contains("interrupted"), "{err}");
388        let pid: i32 = std::fs::read_to_string(&pid_file)
389            .expect("the grandchild recorded its pid")
390            .trim()
391            .parse()
392            .expect("numeric pid");
393        std::thread::sleep(Duration::from_millis(200));
394        assert!(!pid_alive(pid), "grandchild {pid} survived the termination");
395    }
396
397    /// Diagnostics query the database the child was given, and none without one.
398    #[test]
399    fn diagnostics_query_only_the_passed_database_url() {
400        let url = "postgres://private/db";
401        let queries = database_diagnostics(Some(url));
402        assert_eq!(queries.len(), 2);
403        for (_, args) in queries {
404            assert_eq!(args[0], url);
405        }
406        assert!(database_diagnostics(None).is_empty());
407    }
408
409    /// A diagnostic that hangs is cut off at its limit.
410    #[test]
411    fn a_hung_diagnostic_is_cut_off_at_its_limit() {
412        let _processes = crate::test_support::processes();
413        let started = Instant::now();
414        report_within("1", "sleep", &["60"]);
415        assert!(
416            started.elapsed() < Duration::from_secs(30),
417            "the diagnostic ran for {:?}",
418            started.elapsed()
419        );
420    }
421
422    /// A long silent computation is progress, not a hang.
423    #[test]
424    fn a_silent_busy_command_is_left_alone() {
425        let _processes = crate::test_support::processes();
426        // The loop must log BUSY_TICKS of CPU within each budget; a 10 s budget
427        // needs only a 10% CPU share, which a loaded CI runner still grants.
428        let out = run_watched_for(
429            "bash",
430            &[
431                "-c",
432                "end=$((SECONDS+12)); while [ $SECONDS -lt $end ]; do :; done",
433            ],
434            &[],
435            None,
436            Duration::from_secs(10),
437        );
438        assert!(
439            out.is_ok(),
440            "a command busy on the CPU must not be stalled: {out:?}"
441        );
442    }
443
444    /// A command that fails must still report its failure, not a stall.
445    #[test]
446    fn a_failing_command_reports_its_exit_status() {
447        let _processes = crate::test_support::processes();
448        let err = run_watched("bash", &["-c", "echo working; exit 3"], &[], None)
449            .expect_err("a non-zero exit must be an error");
450        let text = format!("{err}");
451        assert!(text.contains("exited with"), "{text}");
452        assert!(
453            !text.contains("no output for"),
454            "a failing command must not be misreported as a stall: {text}"
455        );
456    }
457}