Skip to main content

krab_runtime/
cgroup.rs

1use std::fs;
2
3#[derive(Clone, Copy, Debug, Default)]
4pub struct Usage {
5    pub cpu_usec: u64,
6    pub mem_bytes: u64,
7}
8
9pub fn container_usage(root: &str, id: &str) -> Option<Usage> {
10    let mut candidates = vec![
11        format!("{root}/system.slice/docker-{id}.scope"),
12        format!("{root}/docker/{id}"),
13        format!("{root}/kubepods.slice/docker-{id}.scope"),
14    ];
15    if let Some(p) = native_cgroup_path(id) {
16        candidates.push(format!("{root}/{p}"));
17    }
18    candidates.iter().find_map(|dir| read_dir(dir))
19}
20
21pub fn native_cgroup_path(id: &str) -> Option<String> {
22    let mut it = id.strip_prefix(crate::NAME_PREFIX)?.splitn(3, '_');
23    let (ns, pod, c) = (it.next()?, it.next()?, it.next()?);
24    let ok = |s: &str| {
25        !s.is_empty()
26            && s != "."
27            && s != ".."
28            && s.bytes()
29                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'.'))
30    };
31    (ok(ns) && ok(pod) && ok(c)).then(|| format!("krab/{ns}_{pod}/{c}"))
32}
33
34fn read_dir(dir: &str) -> Option<Usage> {
35    let mem = fs::read_to_string(format!("{dir}/memory.current")).ok()?;
36    let cpu = fs::read_to_string(format!("{dir}/cpu.stat")).ok()?;
37    let cpu_usec = cpu
38        .lines()
39        .find_map(|l| l.strip_prefix("usage_usec "))
40        .and_then(|v| v.trim().parse().ok())?;
41    Some(Usage {
42        cpu_usec,
43        mem_bytes: mem.trim().parse().ok()?,
44    })
45}
46
47pub fn parse_stat_cpu(stat: &str) -> Option<u64> {
48    let line = stat.lines().next()?;
49    let mut it = line.split_whitespace();
50    if it.next()? != "cpu" {
51        return None;
52    }
53    let v: Vec<u64> = it.filter_map(|x| x.parse().ok()).collect();
54    if v.len() < 4 {
55        return None;
56    }
57    let busy = v[0]
58        + v[1]
59        + v[2]
60        + v.get(5).copied().unwrap_or(0)
61        + v.get(6).copied().unwrap_or(0)
62        + v.get(7).copied().unwrap_or(0);
63    Some(busy)
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn parses_proc_stat() {
72        let s = "cpu  100 0 50 800 10 0 5 0 0 0\ncpu0 1 1 1 1\n";
73        assert_eq!(parse_stat_cpu(s), Some(155));
74    }
75}