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.
8
pub const TICKS_PER_SECOND: u64 = 100;
9

            
10
struct 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.
20
82
pub fn tree_ticks(root: u32) -> u64 {
21
82
    let stats = read_stats();
22
82
    let mut tree = vec![root];
23
82
    let mut next = 0;
24
191
    while let Some(&pid) = tree.get(next) {
25
6201
        tree.extend(stats.iter().filter(|s| s.ppid == pid).map(|s| s.pid));
26
109
        next += 1;
27
    }
28
82
    stats
29
82
        .iter()
30
4579
        .filter(|s| tree.contains(&s.pid))
31
115
        .fold(0, |sum, s| sum.saturating_add(s.ticks))
32
82
}
33

            
34
/// Live members of the process group `pgid`, the leader included.
35
10
pub fn group_members(pgid: u32) -> Vec<u32> {
36
10
    read_stats()
37
10
        .iter()
38
506
        .filter(|s| s.pgrp == pgid)
39
17
        .map(|s| s.pid)
40
        .collect()
41
10
}
42

            
43
92
fn read_stats() -> Vec<Stat> {
44
92
    std::fs::read_dir("/proc")
45
92
        .into_iter()
46
92
        .flatten()
47
92
        .flatten()
48
10160
        .filter_map(|entry| std::fs::read_to_string(entry.path().join("stat")).ok())
49
5085
        .filter_map(|text| parse(&text))
50
        .collect()
51
92
}
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 `)`.
55
5088
fn parse(text: &str) -> Option<Stat> {
56
5088
    let (head, rest) = text.rsplit_once(')')?;
57
5087
    let pid = head.split_once(" (")?.0.trim().parse().ok()?;
58
5087
    let fields: Vec<&str> = rest.split_whitespace().collect();
59
20345
    let field = |index: usize| fields.get(index)?.parse::<u64>().ok();
60
    Some(Stat {
61
5087
        pid,
62
5087
        ppid: fields.get(1)?.parse().ok()?,
63
5087
        pgrp: fields.get(2)?.parse().ok()?,
64
20345
        ticks: (11..=14).try_fold(0u64, |sum, index| sum.checked_add(field(index)?))?,
65
    })
66
5088
}
67

            
68
#[cfg(test)]
69
mod tests;