use std::path::{Path, PathBuf};
pub const ROOT: &str = "/sys/fs/cgroup";
pub fn hierarchy_available() -> bool {
Path::new(ROOT).join("cgroup.controllers").exists()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CgroupTarget {
pub name: String,
pub dir: PathBuf,
}
fn group_dir(path: &str) -> PathBuf {
if Path::new(path).starts_with(ROOT) {
PathBuf::from(path)
} else {
Path::new(ROOT).join(path.trim_start_matches('/'))
}
}
pub fn parse_cgroups(value: &str) -> Result<Vec<CgroupTarget>, String> {
let mut targets: Vec<CgroupTarget> = Vec::new();
for item in value.split(',').map(str::trim).filter(|i| !i.is_empty()) {
let Some((name, path)) = item.split_once(':') else {
return Err(format!("'{item}' is not `name:path`"));
};
let (name, path) = (name.trim(), path.trim());
if !crate::is_subject_name(name) {
return Err(format!(
"'{name}' is not a name; a name is letters, digits, `_` and `-`"
));
}
if targets.iter().any(|t| t.name == name) {
return Err(format!("the name '{name}' is given twice"));
}
if path.is_empty() {
return Err(format!("'{name}' has no control group path"));
}
targets.push(CgroupTarget {
name: name.to_string(),
dir: group_dir(path),
});
}
Ok(targets)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CgroupIo {
pub device: String,
pub read_bytes: u64,
pub write_bytes: u64,
pub reads: u64,
pub writes: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CgroupCounters {
pub cpu_usec: Option<u64>,
pub mem_bytes: Option<u64>,
pub io: Vec<CgroupIo>,
}
pub fn parse_cpu_stat(text: &str) -> Option<u64> {
text.lines()
.find_map(|line| line.strip_prefix("usage_usec "))?
.trim()
.parse()
.ok()
}
pub fn parse_io_stat(text: &str, devices: &[((u32, u32), String)]) -> Vec<CgroupIo> {
text.lines()
.filter_map(|line| {
let mut tokens = line.split_whitespace();
let number = tokens.next()?;
let (major, minor) = number.split_once(':')?;
let number_pair: (u32, u32) = (major.parse().ok()?, minor.parse().ok()?);
let pairs: Vec<(&str, u64)> = tokens
.filter_map(|t| {
let (key, value) = t.split_once('=')?;
Some((key, value.parse().ok()?))
})
.collect();
let value = |key: &str| pairs.iter().find(|(k, _)| *k == key).map(|(_, v)| *v);
Some(CgroupIo {
device: devices
.iter()
.find(|(n, _)| *n == number_pair)
.map(|(_, name)| name.clone())
.unwrap_or_else(|| number.to_string()),
read_bytes: value("rbytes")?,
write_bytes: value("wbytes")?,
reads: value("rios")?,
writes: value("wios")?,
})
})
.collect()
}
pub fn read_counters(dir: &Path, devices: &[((u32, u32), String)]) -> Option<CgroupCounters> {
if !dir.is_dir() {
return None;
}
let read = |file: &str| std::fs::read_to_string(dir.join(file)).ok();
Some(CgroupCounters {
cpu_usec: read("cpu.stat").and_then(|t| parse_cpu_stat(&t)),
mem_bytes: read("memory.current").and_then(|t| t.trim().parse().ok()),
io: read("io.stat")
.map(|t| parse_io_stat(&t, devices))
.unwrap_or_default(),
})
}
#[derive(Debug, Clone, PartialEq)]
pub struct CgroupIoRate {
pub device: String,
pub read_bytes_per_s: f64,
pub write_bytes_per_s: f64,
pub read_ops_per_s: f64,
pub write_ops_per_s: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CgroupReading {
pub name: String,
pub cpu_cores: Option<f64>,
pub mem_bytes: Option<f64>,
pub io: Vec<CgroupIoRate>,
}
pub fn reading(
name: &str,
prev: &CgroupCounters,
cur: &CgroupCounters,
dt_s: f64,
) -> CgroupReading {
let per_s = |before: u64, now: u64| -> f64 {
if dt_s <= 0.0 {
0.0
} else {
now.saturating_sub(before) as f64 / dt_s
}
};
CgroupReading {
name: name.to_string(),
cpu_cores: match (prev.cpu_usec, cur.cpu_usec) {
(Some(before), Some(now)) => Some(per_s(before, now) / 1e6),
_ => None,
},
mem_bytes: cur.mem_bytes.map(|b| b as f64),
io: cur
.io
.iter()
.filter_map(|now| {
let before = prev.io.iter().find(|d| d.device == now.device)?;
Some(CgroupIoRate {
device: now.device.clone(),
read_bytes_per_s: per_s(before.read_bytes, now.read_bytes),
write_bytes_per_s: per_s(before.write_bytes, now.write_bytes),
read_ops_per_s: per_s(before.reads, now.reads),
write_ops_per_s: per_s(before.writes, now.writes),
})
})
.collect(),
}
}
pub struct WatchedCgroup {
pub target: CgroupTarget,
last: Option<CgroupCounters>,
missing_reported: bool,
}
impl WatchedCgroup {
pub fn new(target: CgroupTarget) -> Self {
Self {
target,
last: None,
missing_reported: false,
}
}
pub fn sample(
&mut self,
dt_s: f64,
devices: &[((u32, u32), String)],
missing: &mut dyn FnMut(&str),
) -> Option<CgroupReading> {
let Some(cur) = read_counters(&self.target.dir, devices) else {
if !self.missing_reported {
self.missing_reported = true;
missing(&self.target.name);
}
self.last = None;
return None;
};
self.missing_reported = false;
let prev = self.last.replace(cur.clone())?;
Some(reading(&self.target.name, &prev, &cur, dt_s))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn groups_are_names_with_a_path_under_the_hierarchy() {
assert_eq!(
parse_cgroups("node:system.slice/db.service, me:/sys/fs/cgroup/user.slice").unwrap(),
vec![
CgroupTarget {
name: "node".into(),
dir: "/sys/fs/cgroup/system.slice/db.service".into()
},
CgroupTarget {
name: "me".into(),
dir: "/sys/fs/cgroup/user.slice".into()
},
]
);
assert_eq!(
parse_cgroups("a:/system.slice").unwrap()[0].dir,
PathBuf::from("/sys/fs/cgroup/system.slice")
);
for (value, says) in [
("node", "is not `name:path`"),
("a b:x", "is not a name"),
("a:x,a:y", "given twice"),
("a:", "no control group path"),
] {
let err = parse_cgroups(value).unwrap_err();
assert!(err.contains(says), "{value}: {err}");
}
}
#[test]
fn cpu_stat_gives_the_time_taken() {
let text = "usage_usec 2500000\nuser_usec 2000000\nsystem_usec 500000\n";
assert_eq!(parse_cpu_stat(text), Some(2_500_000));
assert_eq!(parse_cpu_stat("user_usec 1\n"), None);
}
#[test]
fn io_stat_is_read_per_device() {
let devices = vec![((259, 0), "nvme0n1".to_string())];
let text = "\
259:0 rbytes=4096 wbytes=8192 rios=1 wios=2 dbytes=0 dios=0
9:127 rbytes=10 wbytes=20 rios=3 wios=4 dbytes=0 dios=0
8:0
";
assert_eq!(
parse_io_stat(text, &devices),
vec![
CgroupIo {
device: "nvme0n1".into(),
read_bytes: 4096,
write_bytes: 8192,
reads: 1,
writes: 2,
},
CgroupIo {
device: "9:127".into(),
read_bytes: 10,
write_bytes: 20,
reads: 3,
writes: 4,
},
]
);
}
#[test]
fn a_reading_is_the_difference_over_the_window() {
let io = |device: &str, write_bytes| CgroupIo {
device: device.into(),
read_bytes: 0,
write_bytes,
reads: 0,
writes: 0,
};
let prev = CgroupCounters {
cpu_usec: Some(1_000_000),
mem_bytes: Some(10),
io: vec![io("sda", 1000)],
};
let cur = CgroupCounters {
cpu_usec: Some(3_000_000),
mem_bytes: Some(4096),
io: vec![io("sda", 5000), io("sdb", 7)],
};
let got = reading("node", &prev, &cur, 2.0);
assert_eq!(got.cpu_cores, Some(1.0));
assert_eq!(got.mem_bytes, Some(4096.0));
assert_eq!(got.io.len(), 1);
assert_eq!(got.io[0].write_bytes_per_s, 2000.0);
let off = reading(
"node",
&CgroupCounters::default(),
&CgroupCounters::default(),
2.0,
);
assert_eq!(
(off.cpu_cores, off.mem_bytes, off.io.len()),
(None, None, 0)
);
}
#[test]
fn a_missing_group_is_said_once() {
let mut watched = WatchedCgroup::new(CgroupTarget {
name: "gone".into(),
dir: "/sys/fs/cgroup/no-such-group-for-this-test".into(),
});
let mut said = 0;
for _ in 0..3 {
assert!(watched.sample(1.0, &[], &mut |_| said += 1).is_none());
}
assert_eq!(said, 1);
}
#[cfg(target_os = "linux")]
#[test]
fn the_own_group_is_read() {
if !hierarchy_available() {
return;
}
let own = std::fs::read_to_string("/proc/self/cgroup").unwrap();
let Some(path) = own.lines().find_map(|line| line.strip_prefix("0::")) else {
return;
};
let mut watched =
WatchedCgroup::new(parse_cgroups(&format!("me:{path}")).unwrap().remove(0));
let mut missing = |name: &str| panic!("{name} reported missing");
assert!(watched.sample(1.0, &[], &mut missing).is_none());
assert_eq!(watched.sample(1.0, &[], &mut missing).unwrap().name, "me");
}
}