Skip to main content

xtask/watchdog/
cpu.rs

1//! CPU time spent by a process and everything it spawned, read from `/proc`.
2//!
3//! A test binary running one long test prints nothing until that test ends, so
4//! silence alone cannot tell a stuck run from a busy one. The hang the watchdog
5//! exists for sat idle on a socket; a run burning CPU is making progress.
6
7/// `/proc` reports CPU time in `USER_HZ` ticks, fixed at 100 by the kernel ABI.
8pub const TICKS_PER_SECOND: u64 = 100;
9
10struct Stat {
11    pid: u32,
12    ppid: u32,
13    pgrp: u32,
14    ticks: u64,
15}
16
17/// User plus system ticks of `root` and all its live descendants, each with the
18/// ticks of its reaped children rolled up, so a finished process does not
19/// make the total fall.
20pub fn tree_ticks(root: u32) -> u64 {
21    let stats = read_stats();
22    let mut tree = vec![root];
23    let mut next = 0;
24    while let Some(&pid) = tree.get(next) {
25        tree.extend(stats.iter().filter(|s| s.ppid == pid).map(|s| s.pid));
26        next += 1;
27    }
28    stats
29        .iter()
30        .filter(|s| tree.contains(&s.pid))
31        .fold(0, |sum, s| sum.saturating_add(s.ticks))
32}
33
34/// Live members of the process group `pgid`, the leader included.
35pub fn group_members(pgid: u32) -> Vec<u32> {
36    read_stats()
37        .iter()
38        .filter(|s| s.pgrp == pgid)
39        .map(|s| s.pid)
40        .collect()
41}
42
43fn read_stats() -> Vec<Stat> {
44    std::fs::read_dir("/proc")
45        .into_iter()
46        .flatten()
47        .flatten()
48        .filter_map(|entry| std::fs::read_to_string(entry.path().join("stat")).ok())
49        .filter_map(|text| parse(&text))
50        .collect()
51}
52
53/// A `/proc/<pid>/stat` line. The command name sits in parentheses and may
54/// itself hold spaces and parentheses, so fields are counted after the last `)`.
55fn parse(text: &str) -> Option<Stat> {
56    let (head, rest) = text.rsplit_once(')')?;
57    let pid = head.split_once(" (")?.0.trim().parse().ok()?;
58    let fields: Vec<&str> = rest.split_whitespace().collect();
59    let field = |index: usize| fields.get(index)?.parse::<u64>().ok();
60    Some(Stat {
61        pid,
62        ppid: fields.get(1)?.parse().ok()?,
63        pgrp: fields.get(2)?.parse().ok()?,
64        ticks: (11..=14).try_fold(0u64, |sum, index| sum.checked_add(field(index)?))?,
65    })
66}
67
68#[cfg(test)]
69mod tests;