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

            
14
mod cpu;
15
mod group;
16
mod supervised;
17

            
18
use std::io::{BufRead, BufReader};
19
use std::os::unix::process::CommandExt;
20
use std::process::{Child, Command, ExitStatus, Stdio};
21
use std::sync::Arc;
22
use std::sync::atomic::{AtomicU64, Ordering};
23
use std::time::{Duration, Instant};
24

            
25
use anyhow::{Context, Result, bail};
26
use group::Group;
27
pub use group::Termination;
28
pub 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.
36
pub const STALL: Duration = Duration::from_secs(300);
37

            
38
/// CPU time the process tree must spend for its silence to count as work.
39
const 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.
46
2
pub fn run_watched(
47
2
    program: &str,
48
2
    args: &[&str],
49
2
    env: &[(&str, &str)],
50
2
    database_url: Option<&str>,
51
2
) -> Result<()> {
52
2
    run_watched_for(program, args, env, database_url, STALL)
53
2
}
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.
59
6
pub fn run_watched_for(
60
6
    program: &str,
61
6
    args: &[&str],
62
6
    env: &[(&str, &str)],
63
6
    database_url: Option<&str>,
64
6
    stall: Duration,
65
6
) -> Result<()> {
66
6
    let termination = Termination::watch()?;
67
6
    let mut command = Command::new(program);
68
6
    command
69
6
        .args(args)
70
6
        .stdout(Stdio::piped())
71
6
        .stderr(Stdio::piped())
72
6
        .process_group(0);
73
6
    for (key, value) in env {
74
        command.env(key, value);
75
    }
76
6
    let mut child = command
77
6
        .spawn()
78
        .with_context(|| format!("failed to run {program}"))?;
79

            
80
6
    let last_output = Arc::new(AtomicU64::new(0));
81
6
    let started = Instant::now();
82

            
83
6
    let mut pumps = Vec::new();
84
6
    if let Some(stdout) = child.stdout.take() {
85
6
        pumps.push(pump(stdout, Arc::clone(&last_output), started, false));
86
    }
87
6
    if let Some(stderr) = child.stderr.take() {
88
6
        pumps.push(pump(stderr, Arc::clone(&last_output), started, true));
89
    }
90

            
91
6
    let group = Group::of(&child);
92
6
    let verdict = watch(
93
6
        &mut child,
94
6
        &group,
95
6
        &termination,
96
6
        &last_output,
97
6
        started,
98
6
        stall,
99
6
        database_url,
100
6
    );
101
6
    group.kill();
102
6
    let _ = child.wait();
103
6
    for pump in pumps {
104
12
        let _ = pump.join();
105
    }
106

            
107
6
    match verdict? {
108
3
        Verdict::Exited(status) if status.success() => Ok(()),
109
1
        Verdict::Exited(status) => bail!("{program} {} exited with {status}", args.join(" ")),
110
1
        Verdict::Terminated => bail!("{program} interrupted by a termination signal"),
111
2
        Verdict::Stalled { quiet, detected } => bail!(
112
2
            "{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
2
            detected.elapsed().as_millis()
116
        ),
117
    }
118
6
}
119

            
120
enum 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.
128
6
fn watch(
129
6
    child: &mut Child,
130
6
    group: &Group,
131
6
    termination: &Termination,
132
6
    last_output: &AtomicU64,
133
6
    started: Instant,
134
6
    stall: Duration,
135
6
    database_url: Option<&str>,
136
6
) -> Result<Verdict> {
137
6
    let mut cpu_mark = cpu::tree_ticks(child.id());
138
6
    let mut last_busy = 0;
139
    loop {
140
46
        if let Some(status) = child.try_wait().context("waiting on the child")? {
141
3
            return Ok(Verdict::Exited(status));
142
43
        }
143
43
        if termination.requested() {
144
1
            return Ok(Verdict::Terminated);
145
42
        }
146
42
        let now = started.elapsed().as_secs();
147
42
        let ticks = cpu::tree_ticks(child.id());
148
42
        if follow_cpu(&mut cpu_mark, ticks) {
149
7
            last_busy = now;
150
35
        }
151
42
        let quiet = now.saturating_sub(last_output.load(Ordering::Relaxed).max(last_busy));
152
42
        if quiet > stall.as_secs() {
153
2
            let detected = Instant::now();
154
2
            let threads = group.thread_states();
155
2
            group.freeze();
156
2
            diagnose(quiet, &threads, database_url);
157
2
            return Ok(Verdict::Stalled { quiet, detected });
158
40
        }
159
40
        std::thread::sleep(Duration::from_millis(500));
160
    }
161
6
}
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.
166
45
fn follow_cpu(mark: &mut u64, ticks: u64) -> bool {
167
45
    let busy = ticks.saturating_sub(*mark) >= BUSY_TICKS;
168
45
    if busy || ticks < *mark {
169
9
        *mark = ticks;
170
36
    }
171
45
    busy
172
45
}
173

            
174
/// Forwards a stream line by line, recording when each line arrived.
175
12
fn pump<R: std::io::Read + Send + 'static>(
176
12
    stream: R,
177
12
    last_output: Arc<AtomicU64>,
178
12
    started: Instant,
179
12
    is_stderr: bool,
180
12
) -> std::thread::JoinHandle<()> {
181
12
    std::thread::spawn(move || {
182
12
        for line in BufReader::new(stream).lines().map_while(Result::ok) {
183
7
            last_output.store(started.elapsed().as_secs(), Ordering::Relaxed);
184
7
            if is_stderr {
185
                eprintln!("{line}");
186
            } else {
187
7
                println!("{line}");
188
            }
189
        }
190
12
    })
191
12
}
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.
201
2
fn diagnose(quiet: u64, threads: &[String], database_url: Option<&str>) {
202
2
    eprintln!(
203
2
        "\n>> STALL: no output and no CPU work for {quiet}s — child frozen, collecting diagnostics\n"
204
    );
205

            
206
2
    for (title, args) in database_diagnostics(database_url) {
207
        eprintln!(">> {title}:");
208
        report("psql", &args);
209
    }
210

            
211
2
    eprintln!(">> thread states of the stuck process tree:");
212
2
    for line in threads {
213
3
        eprintln!("{line}");
214
    }
215
2
    eprintln!(">> processes:");
216
2
    report("ps", &["-eo", "pid,ppid,etime,stat,pcpu,args"]);
217
2
    eprintln!();
218
2
}
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.
222
4
fn database_diagnostics(database_url: Option<&str>) -> Vec<(&'static str, [&str; 3])> {
223
4
    let Some(url) = database_url else {
224
3
        return Vec::new();
225
    };
226
1
    vec![
227
1
        (
228
1
            "database activity",
229
1
            [
230
1
                url,
231
1
                "-tAc",
232
1
                "select pid, state, wait_event_type, wait_event, \
233
1
                 left(replace(query, chr(10), ' '), 80) from pg_stat_activity \
234
1
                 where backend_type = 'client backend'",
235
1
            ],
236
1
        ),
237
1
        (
238
1
            "locks not granted",
239
1
            [
240
1
                url,
241
1
                "-tAc",
242
1
                "select pid, relation::regclass, mode from pg_locks where not granted",
243
1
            ],
244
1
        ),
245
    ]
246
4
}
247

            
248
/// How long one diagnostic may run; a hung `psql` must not hold the failure back.
249
const REPORT_LIMIT_SECS: &str = "10";
250

            
251
/// Best effort: a diagnostic that cannot run must not mask the stall itself.
252
2
fn report(program: &str, args: &[&str]) {
253
2
    report_within(REPORT_LIMIT_SECS, program, args);
254
2
}
255

            
256
3
fn report_within(limit_secs: &str, program: &str, args: &[&str]) {
257
3
    let run = Command::new("timeout")
258
3
        .args(["--kill-after=1", limit_secs, program])
259
3
        .args(args)
260
3
        .output();
261
3
    match run {
262
        Ok(out) => {
263
3
            for line in String::from_utf8_lossy(&out.stdout).lines().take(40) {
264
80
                eprintln!("   {line}");
265
            }
266
        }
267
        Err(err) => eprintln!("   ({program} unavailable: {err})"),
268
    }
269
3
}
270

            
271
#[cfg(test)]
272
mod 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
1
    fn a_chatty_command_is_left_alone() {
279
1
        let _processes = crate::test_support::processes();
280
        // Prints for longer than a stall check cycle, in small gaps.
281
1
        let out = run_watched(
282
1
            "bash",
283
1
            &["-c", "for i in 1 2 3 4 5; do echo line $i; sleep 0.3; done"],
284
1
            &[],
285
1
            None,
286
1
        );
287
1
        assert!(
288
1
            out.is_ok(),
289
            "a command producing output must not be stalled: {out:?}"
290
        );
291
1
    }
292

            
293
    #[test]
294
1
    fn cpu_work_above_a_lowered_mark_is_activity() {
295
1
        let mut mark = 5_000;
296
1
        assert!(!follow_cpu(&mut mark, 1_000));
297
1
        assert_eq!(mark, 1_000);
298
1
        assert!(follow_cpu(&mut mark, 1_000 + BUSY_TICKS));
299
1
        assert_eq!(mark, 1_000 + BUSY_TICKS);
300
1
    }
301

            
302
    #[test]
303
1
    fn cpu_below_the_busy_threshold_keeps_the_mark() {
304
1
        let mut mark = 1_000;
305
1
        assert!(!follow_cpu(&mut mark, 1_000 + BUSY_TICKS - 1));
306
1
        assert_eq!(mark, 1_000);
307
1
    }
308

            
309
1
    fn killed_after_ms(text: &str) -> u64 {
310
1
        text.split("killed ")
311
1
            .nth(1)
312
1
            .and_then(|rest| rest.split("ms").next())
313
1
            .and_then(|ms| ms.trim().parse().ok())
314
1
            .unwrap_or(u64::MAX)
315
1
    }
316

            
317
    /// The guard must actually fire, kill the child, and say so.
318
    #[test]
319
1
    fn a_silent_command_is_stalled_and_killed() {
320
1
        let _processes = crate::test_support::processes();
321
1
        let started = Instant::now();
322
1
        let err = run_watched_for(
323
1
            "bash",
324
1
            &["-c", "echo starting; sleep 120"],
325
1
            &[],
326
1
            None,
327
1
            Duration::from_secs(2),
328
1
        )
329
1
        .expect_err("a command silent past its budget must fail");
330

            
331
1
        let text = format!("{err}");
332
1
        assert!(text.contains("no output for"), "{text}");
333
1
        assert!(
334
1
            killed_after_ms(&text) < 5_000,
335
            "the child was not killed promptly after the stall: {text}"
336
        );
337
1
        assert!(
338
1
            started.elapsed() < Duration::from_secs(60),
339
            "the stalled run took {:?} end to end",
340
            started.elapsed()
341
        );
342
1
    }
343

            
344
2
    fn pid_alive(pid: i32) -> bool {
345
2
        std::fs::read_to_string(format!("/proc/{pid}/stat"))
346
            .is_ok_and(|stat| !stat.contains(") Z "))
347
2
    }
348

            
349
    /// The kill must take the whole process tree, not only the direct child.
350
    #[test]
351
1
    fn a_stalled_run_kills_its_grandchildren() {
352
1
        let _processes = crate::test_support::processes();
353
1
        let dir = tempfile::tempdir().expect("tempdir");
354
1
        let pid_file = dir.path().join("grandchild.pid");
355
1
        let script = format!("sleep 120 & echo $! > {}; wait", pid_file.display());
356
1
        run_watched_for("bash", &["-c", &script], &[], None, Duration::from_secs(2))
357
1
            .expect_err("a silent command must be stalled");
358

            
359
1
        let pid: i32 = std::fs::read_to_string(&pid_file)
360
1
            .expect("the grandchild recorded its pid")
361
1
            .trim()
362
1
            .parse()
363
1
            .expect("numeric pid");
364
1
        std::thread::sleep(Duration::from_millis(200));
365
1
        assert!(!pid_alive(pid), "grandchild {pid} survived the stall kill");
366
1
    }
367

            
368
    /// Ctrl-C reaches xtask, not the child's own process group: it must be passed on.
369
    #[test]
370
1
    fn a_termination_signal_takes_the_whole_group_down() {
371
1
        let _processes = crate::test_support::processes();
372
1
        let dir = tempfile::tempdir().expect("tempdir");
373
1
        let pid_file = dir.path().join("grandchild.pid");
374
1
        let script = format!("sleep 120 & echo $! > {}; wait", pid_file.display());
375
1
        let marker = pid_file.clone();
376
1
        let sender = std::thread::spawn(move || {
377
1
            let deadline = Instant::now() + Duration::from_secs(10);
378
2
            while !marker.exists() && Instant::now() < deadline {
379
1
                std::thread::sleep(Duration::from_millis(20));
380
            }
381
1
            raise(Signal::SIGTERM)
382
1
        });
383
1
        let err = run_watched_for("bash", &["-c", &script], &[], None, Duration::from_secs(60))
384
1
            .expect_err("a terminated run must fail");
385
1
        sender.join().expect("sender").expect("raise");
386

            
387
1
        assert!(format!("{err}").contains("interrupted"), "{err}");
388
1
        let pid: i32 = std::fs::read_to_string(&pid_file)
389
1
            .expect("the grandchild recorded its pid")
390
1
            .trim()
391
1
            .parse()
392
1
            .expect("numeric pid");
393
1
        std::thread::sleep(Duration::from_millis(200));
394
1
        assert!(!pid_alive(pid), "grandchild {pid} survived the termination");
395
1
    }
396

            
397
    /// Diagnostics query the database the child was given, and none without one.
398
    #[test]
399
1
    fn diagnostics_query_only_the_passed_database_url() {
400
1
        let url = "postgres://private/db";
401
1
        let queries = database_diagnostics(Some(url));
402
1
        assert_eq!(queries.len(), 2);
403
1
        for (_, args) in queries {
404
2
            assert_eq!(args[0], url);
405
        }
406
1
        assert!(database_diagnostics(None).is_empty());
407
1
    }
408

            
409
    /// A diagnostic that hangs is cut off at its limit.
410
    #[test]
411
1
    fn a_hung_diagnostic_is_cut_off_at_its_limit() {
412
1
        let _processes = crate::test_support::processes();
413
1
        let started = Instant::now();
414
1
        report_within("1", "sleep", &["60"]);
415
1
        assert!(
416
1
            started.elapsed() < Duration::from_secs(30),
417
            "the diagnostic ran for {:?}",
418
            started.elapsed()
419
        );
420
1
    }
421

            
422
    /// A long silent computation is progress, not a hang.
423
    #[test]
424
1
    fn a_silent_busy_command_is_left_alone() {
425
1
        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
1
        let out = run_watched_for(
429
1
            "bash",
430
1
            &[
431
1
                "-c",
432
1
                "end=$((SECONDS+12)); while [ $SECONDS -lt $end ]; do :; done",
433
1
            ],
434
1
            &[],
435
1
            None,
436
1
            Duration::from_secs(10),
437
1
        );
438
1
        assert!(
439
1
            out.is_ok(),
440
            "a command busy on the CPU must not be stalled: {out:?}"
441
        );
442
1
    }
443

            
444
    /// A command that fails must still report its failure, not a stall.
445
    #[test]
446
1
    fn a_failing_command_reports_its_exit_status() {
447
1
        let _processes = crate::test_support::processes();
448
1
        let err = run_watched("bash", &["-c", "echo working; exit 3"], &[], None)
449
1
            .expect_err("a non-zero exit must be an error");
450
1
        let text = format!("{err}");
451
1
        assert!(text.contains("exited with"), "{text}");
452
1
        assert!(
453
1
            !text.contains("no output for"),
454
            "a failing command must not be misreported as a stall: {text}"
455
        );
456
1
    }
457
}