1mod 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
30pub const STALL: Duration = Duration::from_secs(300);
37
38const BUSY_TICKS: u64 = cpu::TICKS_PER_SECOND;
40
41pub 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
55pub 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
126fn 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
163fn 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
174fn 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
193fn 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
220fn 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
248const REPORT_LIMIT_SECS: &str = "10";
250
251fn 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 #[test]
278 fn a_chatty_command_is_left_alone() {
279 let _processes = crate::test_support::processes();
280 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 #[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 #[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 #[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 #[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 #[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 #[test]
424 fn a_silent_busy_command_is_left_alone() {
425 let _processes = crate::test_support::processes();
426 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 #[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}