pub mod cpu;
pub mod disk;
pub mod gauges;
pub mod mem;
pub mod net;
pub mod pressure;
pub mod process;
mod sampler;
use std::time::Duration;
pub use cpu::CpuReading;
pub use sampler::spawn;
pub const CATEGORY_NAMES: &[&str] = &[
"cpu", "io", "ram", "rambw", "storage", "net", "pressure", "proc",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Categories {
pub cpu: bool,
pub io: bool,
pub ram: bool,
pub rambw: bool,
pub storage: bool,
pub net: bool,
pub pressure: bool,
pub proc: bool,
}
impl Categories {
pub const ALL: Categories = Categories {
cpu: true,
io: true,
ram: true,
rambw: true,
storage: true,
net: true,
pressure: true,
proc: true,
};
pub fn any(&self) -> bool {
*self != Categories::default()
}
fn flag(&mut self, name: &str) -> Option<&mut bool> {
Some(match name {
"cpu" => &mut self.cpu,
"io" => &mut self.io,
"ram" => &mut self.ram,
"rambw" => &mut self.rambw,
"storage" => &mut self.storage,
"net" => &mut self.net,
"pressure" => &mut self.pressure,
"proc" => &mut self.proc,
_ => return None,
})
}
pub fn names(&self) -> String {
let mut copy = *self;
CATEGORY_NAMES
.iter()
.filter(|name| copy.flag(name).is_some_and(|on| *on))
.copied()
.collect::<Vec<_>>()
.join(",")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Selection {
Cats(Categories),
Any,
}
pub fn parse_selection(value: &str) -> Result<Selection, String> {
let trimmed = value.trim();
if trimmed.eq_ignore_ascii_case("any") {
return Ok(Selection::Any);
}
if trimmed
.to_ascii_lowercase()
.split(',')
.any(|t| t.trim() == "any")
{
return Err("sysmon: `any` stands alone (it means \"every available \
subsystem\") — combining it with named categories is \
ambiguous. Use `sysmon=any`, or name the categories."
.to_string());
}
parse_categories(trimmed).map(Selection::Cats)
}
pub fn parse_categories(value: &str) -> Result<Categories, String> {
if value.trim().eq_ignore_ascii_case("all") {
return Ok(Categories::ALL);
}
let valid = CATEGORY_NAMES.join(", ");
let mut cats = Categories::default();
for token in value.split(',') {
let name = token.trim().to_ascii_lowercase();
if name.is_empty() {
continue;
}
match cats.flag(&name) {
Some(flag) => *flag = true,
None => {
return Err(format!(
"sysmon: unknown category '{name}'. Valid: all, any, or a \
comma list of {valid}"
));
}
}
}
if !cats.any() {
return Err(format!(
"sysmon: no categories enabled. Use `sysmon=all`, `sysmon=any` or a comma \
list of {valid}"
));
}
Ok(cats)
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SysmonSample {
pub cpu: Option<CpuReading>,
pub io: Option<(String, f64)>,
pub io_rates: Vec<disk::DiskRate>,
pub ram: Option<(f64, f64)>,
pub rambw: Option<f64>,
pub storage: Option<(String, f64)>,
pub net: Vec<net::NetRate>,
pub pressure: Option<pressure::PressureReading>,
pub procs: Vec<process::ProcReading>,
}
#[derive(Debug, Clone)]
pub struct SysmonConfig {
pub cats: Categories,
pub interval: Duration,
pub membw_peak_bytes_per_s: Option<f64>,
pub procs: Vec<process::ProcTarget>,
}
pub const fn platform_supported() -> bool {
cfg!(target_os = "linux")
}
pub const UNSUPPORTED_PLATFORM: &str = "sysmon: the sampler reads /proc and is available on \
Linux only; run without `sysmon=` on this host";
pub fn check_rambw_requirements(config: &SysmonConfig) -> Result<(), String> {
if !config.cats.rambw {
return Ok(());
}
if mem::read_membw_bytes().is_none() {
return Err("\
sysmon: rambw was requested, but the kernel resctrl interface is not \
available at /sys/fs/resctrl/mon_data.
To enable memory-bandwidth monitoring:
1. The CPU must support bandwidth monitoring (Intel RDT / AMD QoS) —
check for the `cqm_mbm_total` flag: grep -m1 cqm_mbm_total /proc/cpuinfo
2. The kernel must be built with CONFIG_X86_CPU_RESCTRL (standard on
mainstream distro kernels).
3. Mount the interface: sudo mount -t resctrl resctrl /sys/fs/resctrl
If this host cannot support it (most VMs cannot), name the categories \
without rambw, or use sysmon=any to enable every subsystem this host \
supports."
.to_string());
}
if config.membw_peak_bytes_per_s.is_none() {
return Err("\
sysmon: rambw needs a peak-bandwidth reference to turn bytes/s into a \
utilization. Set it with sysmon_membw_gbps=<peak> (the host's rated \
memory bandwidth in GB/s), name the categories without rambw, or use \
sysmon=any"
.to_string());
}
Ok(())
}
pub fn check_pressure_requirements(config: &SysmonConfig) -> Result<(), String> {
if !config.cats.pressure || pressure::read_pressure().is_some() {
return Ok(());
}
Err("\
sysmon: pressure was requested, but the kernel's pressure stall \
information is not readable at /proc/pressure. It needs a kernel built \
with CONFIG_PSI (4.20 or later) that was not booted with `psi=0`, and a \
container must be given the host's /proc/pressure. Name the categories \
without pressure, or use sysmon=any to enable every subsystem this \
host supports."
.to_string())
}
pub fn check_requirements(config: &SysmonConfig) -> Result<(), String> {
if !platform_supported() {
return Err(UNSUPPORTED_PLATFORM.to_string());
}
if !config.procs.is_empty() && !config.cats.proc {
return Err(
"sysmon: `sysmon_procs=` names processes to watch, and the `proc` \
category is not enabled; add `proc` to `sysmon=`"
.to_string(),
);
}
check_rambw_requirements(config)?;
check_pressure_requirements(config)
}
pub fn resolve_any(config: &SysmonConfig) -> (Categories, Vec<String>) {
if !platform_supported() {
return (
Categories::default(),
vec![UNSUPPORTED_PLATFORM.to_string()],
);
}
let mut cats = Categories::ALL;
let mut skipped = Vec::new();
let probe = SysmonConfig {
cats,
..config.clone()
};
let first = |reason: String| reason.lines().next().unwrap_or("unavailable").to_string();
if let Err(reason) = check_rambw_requirements(&probe) {
cats.rambw = false;
skipped.push(format!(
"{} (run `sysmon=rambw` for the enable steps)",
first(reason)
));
}
if let Err(reason) = check_pressure_requirements(&probe) {
cats.pressure = false;
skipped.push(format!(
"{} (run `sysmon=pressure` for the details)",
first(reason)
));
}
(cats, skipped)
}
#[cfg(test)]
mod tests;