//! Resource HUD data from /proc, /sys and `nvidia-smi`. Unknown values are `None`, //! never zero. Only Capri's own process tree is read for process load; output is numbers only. use std::collections::HashMap; use std::path::Path; use std::time::{Duration, Instant}; use serde_json::{json, Value}; /// Aggregate CPU times from `/proc/stat`. #[derive(Clone, Copy, Debug, PartialEq)] pub struct CpuTimes { pub cores: usize, pub idle: u64, pub total: u64, } pub fn parse_stat(text: &str) -> Option { let line = text.lines().find(|l| l.starts_with("cpu "))?; let v: Vec = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect(); let cores = text.lines().filter(|l| l.starts_with("cpu") && l.as_bytes().get(3).is_some_and(u8::is_ascii_digit)).count(); (v.len() >= 4).then(|| CpuTimes { cores, idle: v[3] + v.get(4).copied().unwrap_or(0), total: v.iter().take(8).sum() }) } /// `100 * (Δtotal − Δidle) / Δtotal`; `None` on first call, core change or inconsistent deltas. pub fn load_percent(prev: Option, cur: CpuTimes) -> Option { let p = prev.filter(|p| p.cores == cur.cores)?; let total = cur.total.checked_sub(p.total)?; let idle = cur.idle.checked_sub(p.idle)?; (total > 0 && idle <= total).then(|| 100.0 * (total - idle) as f64 / total as f64) } /// CPU package temperature from hwmon (`coretemp` Package, `k10temp`/`zenpower` Tctl/Tdie), /// falling back to the `x86_pkg_temp` thermal zone. `sys` is `/sys` (fixture in tests). pub fn cpu_temperature(sys: &Path) -> Option { let valid = |milli: f64| Some((milli / 100.0).round() / 10.0).filter(|c| (-20.0..=150.0).contains(c)); for dir in std::fs::read_dir(sys.join("class/hwmon")).ok()?.flatten().map(|e| e.path()) { let name = std::fs::read_to_string(dir.join("name")).unwrap_or_default(); if !matches!(name.trim(), "coretemp" | "k10temp" | "zenpower") { continue; } let mut best: Option<(u8, f64)> = None; for i in 1..=64 { let Ok(raw) = std::fs::read_to_string(dir.join(format!("temp{i}_input"))) else { continue }; let label = std::fs::read_to_string(dir.join(format!("temp{i}_label"))).unwrap_or_default(); let rank = match label.trim() { l if l.starts_with("Package id") || l == "Tctl" || l == "Tdie" => 2, _ => 1, }; if let Some(c) = raw.trim().parse::().ok().and_then(valid) && best.is_none_or(|b| rank > b.0 || (rank == b.0 && c > b.1)) { best = Some((rank, c)); } } if let Some((_, c)) = best { return Some(c); } } std::fs::read_dir(sys.join("class/thermal")).ok()?.flatten().map(|e| e.path()).find(|d| std::fs::read_to_string(d.join("type")).is_ok_and(|t| t.trim() == "x86_pkg_temp")).and_then(|d| std::fs::read_to_string(d.join("temp")).ok()?.trim().parse::().ok().and_then(valid)) } /// System CPU utilisation + temperature (read every 10 s, 60 s after a failure). #[derive(Default)] pub struct CpuSampler { prev: Option, temperature: Option, sampled_at: Option, next_read: Option, } impl CpuSampler { pub fn sample(&mut self) -> Value { let cur = std::fs::read_to_string("/proc/stat").ok().as_deref().and_then(parse_stat); let utilization = cur.and_then(|c| load_percent(self.prev, c)); if let Some(c) = cur && self.prev.is_none_or(|p| p.total != c.total) { self.prev = Some(c); } if self.next_read.is_none_or(|t| Instant::now() >= t) { self.temperature = cpu_temperature(Path::new("/sys")); if self.temperature.is_some() { self.sampled_at = Some(crate::now_ms()); } self.next_read = Some(Instant::now() + Duration::from_secs(if self.temperature.is_some() { 10 } else { 60 })); } json!({"utilization": utilization, "temperatureCelsius": self.temperature, "temperatureSampledAt": self.sampled_at}) } } /// `MemTotal`/`MemAvailable` (KiB) → `{totalBytes, freeBytes, usedBytes, percent}`. pub fn parse_meminfo(text: &str) -> Option { let kib = |key: &str| text.lines().find(|l| l.starts_with(key))?.split_whitespace().nth(1)?.parse::().ok(); let (total, free) = (kib("MemTotal:")? * 1024, kib("MemAvailable:")? * 1024); let used = total.saturating_sub(free); Some(json!({"totalBytes": total, "freeBytes": free, "usedBytes": used, "percent": (used as f64 * 1000.0 / total as f64).round() / 10.0})) } /// `nvidia-smi --query-gpu=index,uuid,name,memory.total,memory.free,temperature.gpu,utilization.gpu --format=csv,noheader,nounits` pub fn parse_nvidia_gpus(text: &str) -> Vec { text.lines() .filter_map(|line| { let raw: Vec<&str> = line.split(',').collect(); let f: Vec<&str> = raw.iter().map(|s| s.trim()).collect(); if f.len() < 7 { return None; } let n = f.len(); let name = raw[2..n - 4].join(",").trim().to_string(); let mib = |s: &str| s.parse::().ok().map(|v| v * 1024 * 1024); let (total, free) = (mib(f[n - 4])?, mib(f[n - 3])?); let temp = f[n - 2].parse::().ok().filter(|t| (-20.0..=150.0).contains(t)); let util = f[n - 1].parse::().ok().filter(|u| (0.0..=100.0).contains(u)); let used = total.saturating_sub(free); Some(json!({"id": f[1], "index": f[0].parse::().ok()?, "name": name, "vendor": "nvidia", "totalBytes": total, "freeBytes": free, "usedBytes": used, "percent": if total > 0 { (used as f64 * 1000.0 / total as f64).round() / 10.0 } else { 0.0 }, "utilization": util, "temperatureCelsius": temp, "memoryKind": "dedicated"})) }) .collect() } /// `nvidia-smi --query-compute-apps=pid,used_memory` → bytes per pid. pub fn parse_nvidia_apps(text: &str) -> HashMap { let mut out = HashMap::new(); for line in text.lines() { if let Some((pid, mib)) = line.split_once(',') && let (Ok(pid), Ok(mib)) = (pid.trim().parse::(), mib.trim().parse::()) { *out.entry(pid).or_default() += mib * 1024 * 1024; } } out } /// Runs `nvidia-smi` (2.5 s, <= 64 KiB); `None` when absent or failing. pub async fn nvidia_smi(args: &[&str]) -> Option { let child = tokio::process::Command::new("nvidia-smi").args(args).stdin(std::process::Stdio::null()).stderr(std::process::Stdio::null()).kill_on_drop(true).output(); let out = tokio::time::timeout(Duration::from_millis(2500), child).await.ok()?.ok()?; (out.status.success() && out.stdout.len() <= 64 << 10).then(|| String::from_utf8_lossy(&out.stdout).into_owned()) } /// AMD (amdgpu sysfs) cards: VRAM total/used and busy percent. pub fn amd_gpus(sys: &Path) -> Vec { let read = |p: &Path| std::fs::read_to_string(p).ok().and_then(|s| s.trim().parse::().ok()); let mut out = vec![]; for (i, dev) in std::fs::read_dir(sys.join("class/drm")).into_iter().flatten().flatten().map(|e| e.path().join("device")).enumerate() { if let (Some(total), Some(used)) = (read(&dev.join("mem_info_vram_total")), read(&dev.join("mem_info_vram_used"))) && total > 0 { out.push(json!({"id": format!("amd-{i}"), "index": i, "name": "AMD GPU", "vendor": "amd", "totalBytes": total, "freeBytes": total.saturating_sub(used), "usedBytes": used, "percent": (used as f64 * 1000.0 / total as f64).round() / 10.0, "utilization": read(&dev.join("gpu_busy_percent")), "memoryKind": "dedicated"})); } } out } #[derive(Clone, Debug, PartialEq)] pub struct ProcInfo { pub pid: u32, pub ppid: u32, pub started: u64, pub cpu_ticks: u64, } pub fn parse_proc_stat(pid: u32, text: &str) -> Option { use crate::platform::process::stat_field; let num = |n| stat_field(text, n)?.parse::().ok(); Some(ProcInfo { pid, ppid: num(4)? as u32, started: num(22)?, cpu_ticks: num(14)? + num(15)? }) } /// Root plus descendants that started after their parent (PID-reuse guard). pub fn owned_tree(root: u32, procs: &[ProcInfo]) -> Vec { let Some(r) = procs.iter().find(|p| p.pid == root) else { return vec![] }; let mut out = vec![r.clone()]; let mut i = 0; while i < out.len() { let parent = out[i].clone(); out.extend(procs.iter().filter(|p| p.ppid == parent.pid && p.started >= parent.started && p.pid != parent.pid).cloned()); i += 1; } out } /// Private memory: `smaps_rollup` Private_Clean + Private_Dirty, else `status` RssAnon (bytes). pub fn private_bytes(smaps_rollup: Option<&str>, status: Option<&str>) -> Option { let kib = |text: &str, key: &str| text.lines().find(|l| l.starts_with(key))?.split_whitespace().nth(1)?.parse::().ok(); if let Some(s) = smaps_rollup && let (Some(c), Some(d)) = (kib(s, "Private_Clean:"), kib(s, "Private_Dirty:")) { return Some((c + d) * 1024); } status.and_then(|s| kib(s, "RssAnon:")).map(|k| k * 1024) } /// CPU ticks per (pid, start time). type CpuTicks = HashMap<(u32, u64), u64>; /// Capri process-tree load: `{cpuPercent, ramBytes, vramBytes}`. #[derive(Default)] pub struct ProcessLoad { prev: Option<(Instant, CpuTicks)>, unavailable_until: Option, } impl ProcessLoad { pub async fn sample(&mut self) -> Value { if self.unavailable_until.is_some_and(|t| Instant::now() < t) { return json!({"cpuPercent": null, "ramBytes": null, "vramBytes": null}); } let procs: Vec = std::fs::read_dir("/proc") .into_iter() .flatten() .flatten() .filter_map(|e| e.file_name().to_str()?.parse::().ok()) .filter_map(|pid| parse_proc_stat(pid, &std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?)) .collect(); let owned = owned_tree(std::process::id(), &procs); if owned.is_empty() { self.unavailable_until = Some(Instant::now() + Duration::from_secs(30)); return json!({"cpuPercent": null, "ramBytes": null, "vramBytes": null}); } let ram: Option = owned.iter().map(|p| private_bytes(std::fs::read_to_string(format!("/proc/{}/smaps_rollup", p.pid)).ok().as_deref(), std::fs::read_to_string(format!("/proc/{}/status", p.pid)).ok().as_deref())).sum(); let vram = nvidia_smi(&["--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"]).await.map(|t| { let apps = parse_nvidia_apps(&t); owned.iter().filter_map(|p| apps.get(&p.pid)).sum::() }); let now = Instant::now(); let cur: HashMap<(u32, u64), u64> = owned.iter().map(|p| ((p.pid, p.started), p.cpu_ticks)).collect(); let cpu = self.prev.as_ref().and_then(|(at, prev)| cpu_percent(prev, &cur, now.duration_since(*at), ticks_per_second(), cores())); self.prev = Some((now, cur)); json!({"cpuPercent": cpu, "ramBytes": ram, "vramBytes": vram}) } } /// `min(100, 100 * ΣΔcpu / (elapsed * cores))` over (pid, start) pairs in both samples. pub fn cpu_percent(prev: &HashMap<(u32, u64), u64>, cur: &HashMap<(u32, u64), u64>, elapsed: Duration, hz: u64, cores: usize) -> Option { if elapsed.is_zero() || elapsed > Duration::from_secs(20) || cores == 0 { return None; } let mut delta = 0u64; let mut matched = false; for (key, ticks) in cur { if let Some(before) = prev.get(key) { delta += ticks.checked_sub(*before)?; matched = true; } } matched.then(|| (100.0 * (delta as f64 / hz as f64) / (elapsed.as_secs_f64() * cores as f64)).min(100.0)) } fn ticks_per_second() -> u64 { // SAFETY: sysconf has no preconditions. (unsafe { libc::sysconf(libc::_SC_CLK_TCK) }).max(1) as u64 } fn cores() -> usize { std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1) } /// `memory-status` aggregate. GPU list: NVIDIA via `nvidia-smi`, AMD via sysfs. pub async fn memory_status(cpu: &mut CpuSampler, process: Option<&mut ProcessLoad>) -> Value { let ram = std::fs::read_to_string("/proc/meminfo").ok().as_deref().and_then(parse_meminfo); let mut gpus = nvidia_smi(&["--query-gpu=index,uuid,name,memory.total,memory.free,temperature.gpu,utilization.gpu", "--format=csv,noheader,nounits"]).await.map(|t| parse_nvidia_gpus(&t)).unwrap_or_default(); gpus.extend(amd_gpus(Path::new("/sys"))); let load = match process { Some(p) => p.sample().await, None => Value::Null, }; let now = crate::now_ms(); json!({"sampledAt": now, "gpuSampledAt": now, "ram": ram, "gpus": gpus, "processLoad": load, "cpu": cpu.sample()}) } /// Warning hysteresis: two consecutive high readings with distinct timestamps raise, /// a reading at or below the recovery level clears; dismissal holds until recovery. #[derive(Default)] pub struct ResourceWarnings { state: HashMap, bool, bool)>, // highs, last ts, active, dismissed } pub fn thresholds(metric: &str) -> (f64, f64) { match metric { "cpuTemperature" => (95.0, 90.0), "gpuTemperature" => (87.0, 82.0), _ => (95.0, 90.0), // ram / vram percent } } impl ResourceWarnings { /// Feeds one reading; returns whether the warning shows. `None` never counts as recovery. pub fn update(&mut self, device: &str, metric: &str, value: Option, at: i64) -> bool { let (high, low) = thresholds(metric); let s = self.state.entry(format!("{device}/{metric}")).or_insert((0, None, false, false)); if let Some(v) = value { if v >= high { if s.1 != Some(at) { s.0 = s.0.saturating_add(1); } if s.0 >= 2 { s.2 = true; } } else { s.0 = 0; if v <= low { s.2 = false; s.3 = false; } } s.1 = Some(at); } s.2 && !s.3 } pub fn dismiss(&mut self, device: &str, metric: &str) { if let Some(s) = self.state.get_mut(&format!("{device}/{metric}")) { s.3 = true; } } pub fn reset(&mut self) { self.state.clear(); } } pub fn warning_text(device: &str, metric: &str, value: f64) -> String { if metric.ends_with("Temperature") { format!("{device} is overheating ({value:.0} °C).") } else { format!("{device} is nearly full ({value:.0}%).") } } #[cfg(test)] mod tests { use super::*; #[test] fn cpu_and_memory_parsers() { let a = parse_stat("cpu 100 0 100 800 0 0 0 0\ncpu0 1\ncpu1 1\n").unwrap(); let b = parse_stat("cpu 140 0 140 820 0 0 0 0\ncpu0 1\ncpu1 1\n").unwrap(); assert_eq!(a.cores, 2); assert!((load_percent(Some(a), b).unwrap() - 80.0).abs() < 1e-9); assert_eq!(load_percent(None, b), None); assert_eq!(load_percent(Some(CpuTimes { cores: 4, ..a }), b), None); let m = parse_meminfo("MemTotal: 16000000 kB\nMemFree: 1 kB\nMemAvailable: 4000000 kB\n").unwrap(); assert_eq!(m["percent"], 75.0); } #[test] fn nvidia_lines() { let g = parse_nvidia_gpus("0, GPU-abc, NVIDIA GeForce RTX 4070, Laptop, 8188, 6000, [N/A], 12\n"); assert_eq!(g[0]["name"], "NVIDIA GeForce RTX 4070, Laptop"); assert_eq!(g[0]["temperatureCelsius"], Value::Null); assert_eq!(g[0]["usedBytes"], (8188u64 - 6000) * 1024 * 1024); let apps = parse_nvidia_apps("4242, 512\n4242, 100\nbad\n"); assert_eq!(apps[&4242], 612 * 1024 * 1024); } #[test] fn hwmon_fixture() { let dir = tempfile::tempdir().unwrap(); let h = dir.path().join("class/hwmon/hwmon3"); std::fs::create_dir_all(&h).unwrap(); std::fs::write(h.join("name"), "k10temp\n").unwrap(); std::fs::write(h.join("temp1_input"), "61250\n").unwrap(); std::fs::write(h.join("temp1_label"), "Tctl\n").unwrap(); std::fs::write(h.join("temp3_input"), "70000\n").unwrap(); std::fs::write(h.join("temp3_label"), "Tccd1\n").unwrap(); assert_eq!(cpu_temperature(dir.path()), Some(61.3)); assert_eq!(cpu_temperature(Path::new("/nonexistent")), None); } #[test] fn process_tree_and_cpu() { let stat = "10 (ca pri) S 1 10 10 0 -1 0 0 0 0 0 30 20 0 0 20 0 1 0 500 0"; assert_eq!(parse_proc_stat(10, stat).unwrap(), ProcInfo { pid: 10, ppid: 1, started: 500, cpu_ticks: 50 }); let p = |pid, ppid, started| ProcInfo { pid, ppid, started, cpu_ticks: 0 }; let tree = owned_tree(10, &[p(10, 1, 500), p(11, 10, 600), p(12, 11, 700), p(13, 10, 100), p(14, 2, 900)]); assert_eq!(tree.iter().map(|p| p.pid).collect::>(), vec![10, 11, 12], "a pid reused before its parent started is not ours"); let prev = HashMap::from([((10, 500), 100u64)]); let cur = HashMap::from([((10, 500), 150u64)]); assert_eq!(cpu_percent(&prev, &cur, Duration::from_secs(1), 100, 2), Some(25.0)); let reused = HashMap::from([((10, 999), 150u64)]); assert_eq!(cpu_percent(&prev, &reused, Duration::from_secs(1), 100, 2), None); assert_eq!(private_bytes(Some("Private_Clean: 4 kB\nPrivate_Dirty: 6 kB\n"), None), Some(10240)); assert_eq!(private_bytes(None, Some("RssAnon:\t 8 kB\n")), Some(8192)); } #[test] fn warnings_hysteresis() { let mut w = ResourceWarnings::default(); assert!(!w.update("CPU", "cpuTemperature", Some(96.0), 1)); assert!(!w.update("CPU", "cpuTemperature", Some(97.0), 1), "same timestamp does not count twice"); assert!(w.update("CPU", "cpuTemperature", Some(97.0), 2)); assert!(w.update("CPU", "cpuTemperature", None, 3), "a missing sample is not recovery"); assert!(w.update("CPU", "cpuTemperature", Some(92.0), 4), "above recovery level"); w.dismiss("CPU", "cpuTemperature"); assert!(!w.update("CPU", "cpuTemperature", Some(96.0), 5)); assert!(!w.update("CPU", "cpuTemperature", Some(89.0), 6)); assert_eq!(warning_text("GPU", "vram", 96.4), "GPU is nearly full (96%)."); } }