use std::{ path::{Path, PathBuf}, sync::{Arc, Mutex, Weak}, thread, time::{Duration, Instant}, }; use sysinfo::{ CpuRefreshKind, MemoryRefreshKind, Pid, ProcessRefreshKind, ProcessesToUpdate, RefreshKind, System, }; #[cfg(target_os = "linux")] mod drm; #[cfg(target_os = "macos")] mod mac; #[cfg(any(target_os = "linux", target_os = "windows"))] mod nvidia; mod threads; #[cfg(target_os = "windows")] mod windows; const INTERVAL: Duration = Duration::from_secs(1); const IDLE_AFTER: Duration = Duration::from_secs(3); pub use common::stats::{Gpu, GpuMachine, Memory, Storage, Threads, Usage}; pub use threads::{Group, tick}; #[derive(Clone, Copy, PartialEq, Eq)] pub enum Wake { Always, OnDemand, } struct Shared { latest: Option, requested: Instant, } pub struct Monitor { shared: Arc>, } impl Monitor { pub fn new(wake: Wake, disk: Option) -> Self { let shared = Arc::new(Mutex::new(Shared { latest: None, requested: Instant::now(), })); let worker = Arc::downgrade(&shared); let _ = thread::Builder::new() .name("usage".to_string()) .spawn(move || run(worker, wake, disk)); Self { shared } } pub fn latest(&self) -> Option { let mut shared = self.shared.lock().ok()?; shared.requested = Instant::now(); shared.latest.clone() } } pub(crate) fn mb(bytes: u64) -> u32 { (bytes / (1024 * 1024)) as u32 } fn run(shared: Weak>, wake: Wake, disk: Option) { let mut sampler: Option = None; loop { thread::sleep(INTERVAL); let Some(shared) = shared.upgrade() else { return; }; let Ok(requested) = shared.lock().map(|shared| shared.requested) else { return; }; let wanted = wake == Wake::Always || requested.elapsed() < IDLE_AFTER; let usage = if wanted { if sampler.is_none() { sampler = Sampler::new(); } sampler .as_mut() .and_then(|sampler| sampler.sample(disk.as_deref())) } else { sampler = None; None }; if let Ok(mut shared) = shared.lock() { shared.latest = usage; } } } struct Sampler { system: System, pid: Pid, cores: f32, host: String, os: String, cpu_model: String, primed: bool, gpu: GpuSampler, threads: threads::Sampler, } impl Sampler { fn new() -> Option { let system = System::new_with_specifics( RefreshKind::nothing().with_cpu(CpuRefreshKind::nothing().with_usage()), ) .ok()?; let cpu_model = system .cpus() .first() .map(|cpu| cpu.brand().trim().to_string()) .unwrap_or_default(); Some(Self { host: System::host_name().unwrap_or_default(), os: os(), cores: system.cpus().len().max(1) as f32, system, pid: Pid::from_u32(std::process::id()), cpu_model, primed: false, gpu: GpuSampler::default(), threads: threads::Sampler::default(), }) } fn sample(&mut self, disk: Option<&Path>) -> Option { self.system.refresh_cpu_usage(); self.system .refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram()); self.system.refresh_processes_specifics( ProcessesToUpdate::Some(&[self.pid]), true, ProcessRefreshKind::nothing().with_cpu().with_memory(), ); if !std::mem::replace(&mut self.primed, true) { return None; } let process = self.system.process(self.pid)?; let total = self.system.total_memory(); let threads = self.threads.sample(self.cores); Some(Usage { host: self.host.clone(), os: self.os.clone(), cpu_model: self.cpu_model.clone(), machine: self.system.global_cpu_usage(), total: process.cpu_usage() / self.cores, threads, memory: Memory { own_mb: mb(process.memory()), used_mb: mb(total.saturating_sub(self.system.available_memory())), total_mb: mb(total), }, storage: disk.and_then(storage), gpu: self.gpu.sample(), }) } } #[derive(Default)] struct GpuSampler { #[cfg(any(target_os = "linux", target_os = "windows"))] nvidia: nvidia::Sampler, #[cfg(target_os = "linux")] native: drm::Sampler, #[cfg(target_os = "windows")] native: windows::Sampler, #[cfg(target_os = "macos")] native: mac::Sampler, } impl GpuSampler { #[cfg(any(target_os = "linux", target_os = "windows"))] fn sample(&mut self) -> Option { self.nvidia.sample().or_else(|| self.native.sample()) } #[cfg(target_os = "macos")] fn sample(&mut self) -> Option { self.native.sample() } #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))] fn sample(&mut self) -> Option { None } } fn os() -> String { #[cfg(target_os = "windows")] let kernel = windows::build(); #[cfg(not(target_os = "windows"))] let kernel = System::kernel_version().ok(); let name = System::long_os_version().unwrap_or_default(); match kernel { Some(kernel) => format!("{name} {kernel}"), None => name, } } fn storage(path: &Path) -> Option { let path = path.ancestors().find_map(|path| path.canonicalize().ok())?; let disks = sysinfo::Disks::new_with_refreshed_list().ok()?; let disk = disks .iter() .filter(|disk| path.starts_with(disk.mount_point())) .max_by_key(|disk| disk.mount_point().as_os_str().len())?; Some(Storage { used_mb: mb(disk.total_space().saturating_sub(disk.available_space())), total_mb: mb(disk.total_space()), }) }