Lines
96.9 %
Functions
64.29 %
Branches
100 %
//! Runs a command that is expected to keep talking, and diagnoses it if it stops.
//!
//! A coverage run hung for over an hour: two web integration tests stopped
//! producing output while the job's heartbeat kept pulsing, so nothing looked
//! wrong until the deadline killed it — with no indication of which tests were
//! responsible. Diagnosing it meant catching the pod live and hand-running
//! `pg_stat_activity` and `/proc` inspection before it disappeared. The next
//! occurrence should arrive already diagnosed.
//! Only for commands whose silence is itself a symptom. The musl link is quiet
//! for twelve minutes and is perfectly healthy; wrapping that would be a way to
//! kill good builds.
mod cpu;
mod group;
mod supervised;
use std::io::{BufRead, BufReader};
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use group::Group;
pub use group::Termination;
pub use supervised::run_supervised;
/// How long a watched command may produce nothing and do no CPU work before
/// it is declared stuck.
///
/// Silence alone is not enough: a test binary whose last test runs for many
/// minutes prints nothing meanwhile, yet keeps every core busy. The hang this
/// exists for was silent and idle for eleven minutes.
pub const STALL: Duration = Duration::from_secs(300);
/// CPU time the process tree must spend for its silence to count as work.
const BUSY_TICKS: u64 = cpu::TICKS_PER_SECOND;
/// Runs a command, forwarding its output, and fails if it goes quiet.
/// `database_url` is the database the child works against, queried for
/// diagnostics if it stalls; the ambient `DATABASE_URL` is deliberately not
/// consulted, as it may name a different server.
pub fn run_watched(
program: &str,
args: &[&str],
env: &[(&str, &str)],
database_url: Option<&str>,
) -> Result<()> {
run_watched_for(program, args, env, database_url, STALL)
}
/// As [`run_watched`], with the silence budget supplied.
/// Exists so the stall path itself is testable: a test cannot wait out the real
/// five minutes, and a guard that has never fired is not known to work.
pub fn run_watched_for(
stall: Duration,
let termination = Termination::watch()?;
let mut command = Command::new(program);
command
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0);
for (key, value) in env {
command.env(key, value);
let mut child = command
.spawn()
.with_context(|| format!("failed to run {program}"))?;
let last_output = Arc::new(AtomicU64::new(0));
let started = Instant::now();
let mut pumps = Vec::new();
if let Some(stdout) = child.stdout.take() {
pumps.push(pump(stdout, Arc::clone(&last_output), started, false));
if let Some(stderr) = child.stderr.take() {
pumps.push(pump(stderr, Arc::clone(&last_output), started, true));
let group = Group::of(&child);
let verdict = watch(
&mut child,
&group,
&termination,
&last_output,
started,
stall,
database_url,
);
group.kill();
let _ = child.wait();
for pump in pumps {
let _ = pump.join();
match verdict? {
Verdict::Exited(status) if status.success() => Ok(()),
Verdict::Exited(status) => bail!("{program} {} exited with {status}", args.join(" ")),
Verdict::Terminated => bail!("{program} interrupted by a termination signal"),
Verdict::Stalled { quiet, detected } => bail!(
"{program} produced no output for {quiet}s and sat idle, killed \
{}ms after the stall was seen — see the diagnostics above. This is the \
silent-hang failure mode, not a slow build.",
detected.elapsed().as_millis()
),
enum Verdict {
Exited(ExitStatus),
Terminated,
Stalled { quiet: u64, detected: Instant },
/// Polls the child until it exits, is told to stop, or goes quiet; on a stall
/// the diagnostics are gathered here, with the group frozen but alive.
fn watch(
child: &mut Child,
group: &Group,
termination: &Termination,
last_output: &AtomicU64,
started: Instant,
) -> Result<Verdict> {
let mut cpu_mark = cpu::tree_ticks(child.id());
let mut last_busy = 0;
loop {
if let Some(status) = child.try_wait().context("waiting on the child")? {
return Ok(Verdict::Exited(status));
if termination.requested() {
return Ok(Verdict::Terminated);
let now = started.elapsed().as_secs();
let ticks = cpu::tree_ticks(child.id());
if follow_cpu(&mut cpu_mark, ticks) {
last_busy = now;
let quiet = now.saturating_sub(last_output.load(Ordering::Relaxed).max(last_busy));
if quiet > stall.as_secs() {
let detected = Instant::now();
let threads = group.thread_states();
group.freeze();
diagnose(quiet, &threads, database_url);
return Ok(Verdict::Stalled { quiet, detected });
std::thread::sleep(Duration::from_millis(500));
/// Moves `mark` to `ticks` in either direction; true when the tree gained at
/// least [`BUSY_TICKS`] since the mark. Following a drop keeps a total that
/// fell from hiding later work.
fn follow_cpu(mark: &mut u64, ticks: u64) -> bool {
let busy = ticks.saturating_sub(*mark) >= BUSY_TICKS;
if busy || ticks < *mark {
*mark = ticks;
busy
/// Forwards a stream line by line, recording when each line arrived.
fn pump<R: std::io::Read + Send + 'static>(
stream: R,
last_output: Arc<AtomicU64>,
is_stderr: bool,
) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
for line in BufReader::new(stream).lines().map_while(Result::ok) {
last_output.store(started.elapsed().as_secs(), Ordering::Relaxed);
if is_stderr {
eprintln!("{line}");
} else {
println!("{line}");
})
/// Everything worth knowing about a stuck run, gathered with the process tree
/// frozen, before it is killed, because killing it drops the database
/// connections and the process tree being diagnosed.
/// Each of these had to be gathered by hand from a live pod last time, racing
/// the job's deadline. The database view is the one that mattered: connections
/// sitting `idle / ClientRead` while the client waited on the socket is what
/// identified a desynchronised connection rather than a slow query.
fn diagnose(quiet: u64, threads: &[String], database_url: Option<&str>) {
eprintln!(
"\n>> STALL: no output and no CPU work for {quiet}s — child frozen, collecting diagnostics\n"
for (title, args) in database_diagnostics(database_url) {
eprintln!(">> {title}:");
report("psql", &args);
eprintln!(">> thread states of the stuck process tree:");
for line in threads {
eprintln!(">> processes:");
report("ps", &["-eo", "pid,ppid,etime,stat,pcpu,args"]);
eprintln!();
/// The psql invocations that describe the database the child was given; none
/// without one, since the ambient server is not the child's.
fn database_diagnostics(database_url: Option<&str>) -> Vec<(&'static str, [&str; 3])> {
let Some(url) = database_url else {
return Vec::new();
};
vec![
(
"database activity",
[
url,
"-tAc",
"select pid, state, wait_event_type, wait_event, \
left(replace(query, chr(10), ' '), 80) from pg_stat_activity \
where backend_type = 'client backend'",
],
"locks not granted",
"select pid, relation::regclass, mode from pg_locks where not granted",
]
/// How long one diagnostic may run; a hung `psql` must not hold the failure back.
const REPORT_LIMIT_SECS: &str = "10";
/// Best effort: a diagnostic that cannot run must not mask the stall itself.
fn report(program: &str, args: &[&str]) {
report_within(REPORT_LIMIT_SECS, program, args);
fn report_within(limit_secs: &str, program: &str, args: &[&str]) {
let run = Command::new("timeout")
.args(["--kill-after=1", limit_secs, program])
.output();
match run {
Ok(out) => {
for line in String::from_utf8_lossy(&out.stdout).lines().take(40) {
eprintln!(" {line}");
Err(err) => eprintln!(" ({program} unavailable: {err})"),
#[cfg(test)]
mod tests {
use super::*;
use nix::sys::signal::{Signal, raise};
/// A command that keeps talking must not be killed, however long it runs.
#[test]
fn a_chatty_command_is_left_alone() {
let _processes = crate::test_support::processes();
// Prints for longer than a stall check cycle, in small gaps.
let out = run_watched(
"bash",
&["-c", "for i in 1 2 3 4 5; do echo line $i; sleep 0.3; done"],
&[],
None,
assert!(
out.is_ok(),
"a command producing output must not be stalled: {out:?}"
fn cpu_work_above_a_lowered_mark_is_activity() {
let mut mark = 5_000;
assert!(!follow_cpu(&mut mark, 1_000));
assert_eq!(mark, 1_000);
assert!(follow_cpu(&mut mark, 1_000 + BUSY_TICKS));
assert_eq!(mark, 1_000 + BUSY_TICKS);
fn cpu_below_the_busy_threshold_keeps_the_mark() {
let mut mark = 1_000;
assert!(!follow_cpu(&mut mark, 1_000 + BUSY_TICKS - 1));
fn killed_after_ms(text: &str) -> u64 {
text.split("killed ")
.nth(1)
.and_then(|rest| rest.split("ms").next())
.and_then(|ms| ms.trim().parse().ok())
.unwrap_or(u64::MAX)
/// The guard must actually fire, kill the child, and say so.
fn a_silent_command_is_stalled_and_killed() {
let err = run_watched_for(
&["-c", "echo starting; sleep 120"],
Duration::from_secs(2),
)
.expect_err("a command silent past its budget must fail");
let text = format!("{err}");
assert!(text.contains("no output for"), "{text}");
killed_after_ms(&text) < 5_000,
"the child was not killed promptly after the stall: {text}"
started.elapsed() < Duration::from_secs(60),
"the stalled run took {:?} end to end",
started.elapsed()
fn pid_alive(pid: i32) -> bool {
std::fs::read_to_string(format!("/proc/{pid}/stat"))
.is_ok_and(|stat| !stat.contains(") Z "))
/// The kill must take the whole process tree, not only the direct child.
fn a_stalled_run_kills_its_grandchildren() {
let dir = tempfile::tempdir().expect("tempdir");
let pid_file = dir.path().join("grandchild.pid");
let script = format!("sleep 120 & echo $! > {}; wait", pid_file.display());
run_watched_for("bash", &["-c", &script], &[], None, Duration::from_secs(2))
.expect_err("a silent command must be stalled");
let pid: i32 = std::fs::read_to_string(&pid_file)
.expect("the grandchild recorded its pid")
.trim()
.parse()
.expect("numeric pid");
std::thread::sleep(Duration::from_millis(200));
assert!(!pid_alive(pid), "grandchild {pid} survived the stall kill");
/// Ctrl-C reaches xtask, not the child's own process group: it must be passed on.
fn a_termination_signal_takes_the_whole_group_down() {
let marker = pid_file.clone();
let sender = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(10);
while !marker.exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
raise(Signal::SIGTERM)
});
let err = run_watched_for("bash", &["-c", &script], &[], None, Duration::from_secs(60))
.expect_err("a terminated run must fail");
sender.join().expect("sender").expect("raise");
assert!(format!("{err}").contains("interrupted"), "{err}");
assert!(!pid_alive(pid), "grandchild {pid} survived the termination");
/// Diagnostics query the database the child was given, and none without one.
fn diagnostics_query_only_the_passed_database_url() {
let url = "postgres://private/db";
let queries = database_diagnostics(Some(url));
assert_eq!(queries.len(), 2);
for (_, args) in queries {
assert_eq!(args[0], url);
assert!(database_diagnostics(None).is_empty());
/// A diagnostic that hangs is cut off at its limit.
fn a_hung_diagnostic_is_cut_off_at_its_limit() {
report_within("1", "sleep", &["60"]);
started.elapsed() < Duration::from_secs(30),
"the diagnostic ran for {:?}",
/// A long silent computation is progress, not a hang.
fn a_silent_busy_command_is_left_alone() {
// The loop must log BUSY_TICKS of CPU within each budget; a 10 s budget
// needs only a 10% CPU share, which a loaded CI runner still grants.
let out = run_watched_for(
&[
"-c",
"end=$((SECONDS+12)); while [ $SECONDS -lt $end ]; do :; done",
Duration::from_secs(10),
"a command busy on the CPU must not be stalled: {out:?}"
/// A command that fails must still report its failure, not a stall.
fn a_failing_command_reports_its_exit_status() {
let err = run_watched("bash", &["-c", "echo working; exit 3"], &[], None)
.expect_err("a non-zero exit must be an error");
assert!(text.contains("exited with"), "{text}");
!text.contains("no output for"),
"a failing command must not be misreported as a stall: {text}"