use super::{sensors::SensorCollector, topology::SysfsTopologyCollector};
use crate::model::cpu::CpuTopology;
use anyhow::Result;
use std::{collections::BTreeMap, fs, path::PathBuf};
#[derive(Debug, Clone, Copy, Default)]
pub struct CpuTimes {
pub user: u64,
pub nice: u64,
pub system: u64,
pub idle: u64,
pub iowait: u64,
pub irq: u64,
pub softirq: u64,
pub steal: u64,
}
impl CpuTimes {
fn total(self) -> u64 {
self.user
.saturating_add(self.nice)
.saturating_add(self.system)
.saturating_add(self.idle)
.saturating_add(self.iowait)
.saturating_add(self.irq)
.saturating_add(self.softirq)
.saturating_add(self.steal)
}
fn busy(self) -> u64 {
self.total()
.saturating_sub(self.idle)
.saturating_sub(self.iowait)
}
}
pub fn parse_proc_stat(input: &str) -> BTreeMap<u32, CpuTimes> {
input
.lines()
.filter_map(|line| {
let mut fields = line.split_whitespace();
let name = fields.next()?;
let id = name.strip_prefix("cpu")?.parse().ok()?;
let values: Vec<u64> = fields
.take(8)
.filter_map(|value| value.parse().ok())
.collect();
if values.len() < 4 {
return None;
}
Some((
id,
CpuTimes {
user: values[0],
nice: values.get(1).copied().unwrap_or_default(),
system: values.get(2).copied().unwrap_or_default(),
idle: values[3],
iowait: values.get(4).copied().unwrap_or_default(),
irq: values.get(5).copied().unwrap_or_default(),
softirq: values.get(6).copied().unwrap_or_default(),
steal: values.get(7).copied().unwrap_or_default(),
},
))
})
.collect()
}
pub fn utilization_delta(previous: CpuTimes, current: CpuTimes) -> Option<f64> {
let total_delta = current.total().checked_sub(previous.total())?;
let busy_delta = current.busy().checked_sub(previous.busy())?;
if total_delta == 0 {
return None;
}
Some((busy_delta as f64 / total_delta as f64 * 100.0).clamp(0.0, 100.0))
}
#[derive(Debug, Clone)]
pub struct ProcStatCollector {
root: PathBuf,
previous: Option<BTreeMap<u32, CpuTimes>>,
}
impl Default for ProcStatCollector {
fn default() -> Self {
Self::new("/proc")
}
}
impl ProcStatCollector {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self {
root: root.into(),
previous: None,
}
}
pub fn collect(&mut self, topology: &mut CpuTopology) -> Result<()> {
let current = parse_proc_stat(&fs::read_to_string(self.root.join("stat"))?);
if let Some(previous) = &self.previous {
for cpu in &mut topology.cpus {
cpu.utilization = previous.get(&cpu.logical_id).and_then(|old| {
current
.get(&cpu.logical_id)
.and_then(|new| utilization_delta(*old, *new))
});
}
}
self.previous = Some(current);
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct CpuCollector {
topology: SysfsTopologyCollector,
stat: ProcStatCollector,
sensors: SensorCollector,
pub last: Option<CpuTopology>,
}
impl Default for CpuCollector {
fn default() -> Self {
Self::new()
}
}
impl CpuCollector {
pub fn new() -> Self {
Self {
topology: SysfsTopologyCollector::default(),
stat: ProcStatCollector::default(),
sensors: SensorCollector::default(),
last: None,
}
}
pub fn collect(&mut self) -> Result<CpuTopology> {
let mut topology = self.topology.collect()?;
self.stat.collect(&mut topology)?;
self.sensors.apply(&mut topology);
self.last = Some(topology.clone());
Ok(topology)
}
}