1use std::collections::HashMap;
10
11use sysinfo::{
12 CpuRefreshKind, DiskRefreshKind, Disks, MemoryRefreshKind, Networks, ProcessRefreshKind,
13 ProcessesToUpdate, System, ThreadKind, UpdateKind, Users,
14};
15
16use crate::snapshot::{
17 CpuStats, FilesystemUsage, HostInfo, MemoryStats, NetworkStats, ProcessInfo,
18};
19#[cfg(not(target_os = "linux"))]
20use crate::snapshot::{DiskIo, SensorChip, Temperature};
21
22fn disk_refresh_kind() -> DiskRefreshKind {
25 let kind = DiskRefreshKind::nothing().with_storage();
26 if cfg!(target_os = "linux") {
27 kind
28 } else {
29 kind.with_io_usage()
30 }
31}
32
33const PSEUDO_FILESYSTEMS: &[&str] = &[
35 "tmpfs",
36 "devtmpfs",
37 "squashfs",
38 "overlay",
39 "efivarfs",
40 "ramfs",
41 "proc",
42 "sysfs",
43 "cgroup2",
44 "fuse.portal",
45 "fuse.snapfuse",
46];
47
48pub struct SystemCollector {
51 system: System,
52 networks: Networks,
53 disks: Disks,
54 users: Users,
55 #[cfg(not(target_os = "linux"))]
57 components: sysinfo::Components,
58}
59
60impl SystemCollector {
61 pub fn new() -> Self {
63 let mut collector = Self {
64 system: System::new(),
65 networks: Networks::new_with_refreshed_list(),
66 disks: Disks::new_with_refreshed_list_specifics(disk_refresh_kind()),
67 users: Users::new_with_refreshed_list(),
68 #[cfg(not(target_os = "linux"))]
69 components: sysinfo::Components::new_with_refreshed_list(),
70 };
71 collector.refresh();
72 collector
73 }
74
75 pub fn refresh(&mut self) {
77 self.system
78 .refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage().with_frequency());
79 self.system
80 .refresh_memory_specifics(MemoryRefreshKind::everything());
81 self.system.refresh_processes_specifics(
82 ProcessesToUpdate::All,
83 true,
84 ProcessRefreshKind::nothing()
85 .with_cpu()
86 .with_memory()
87 .with_disk_usage()
88 .without_tasks()
93 .with_user(UpdateKind::OnlyIfNotSet)
94 .with_cmd(UpdateKind::OnlyIfNotSet),
95 );
96 self.networks.refresh(true);
97 self.disks.refresh_specifics(true, disk_refresh_kind());
98 }
99
100 pub fn host(&self) -> HostInfo {
102 HostInfo {
103 hostname: System::host_name().unwrap_or_default(),
104 os: System::long_os_version().unwrap_or_default(),
105 kernel: System::kernel_version().unwrap_or_default(),
106 uptime_secs: System::uptime(),
107 rigtop_version: env!("CARGO_PKG_VERSION").to_owned(),
108 reboot_required: None,
109 }
110 }
111
112 pub fn cpu(&self) -> CpuStats {
114 let cpus = self.system.cpus();
115 let load = System::load_average();
116 CpuStats {
117 model: cpus
118 .first()
119 .map(|c| c.brand().trim().to_owned())
120 .unwrap_or_default(),
121 total_percent: self.system.global_cpu_usage(),
122 per_core_percent: cpus.iter().map(|c| c.cpu_usage()).collect(),
123 per_core_mhz: cpus.iter().map(|c| c.frequency()).collect(),
124 load_average: cfg!(unix).then_some([load.one, load.five, load.fifteen]),
126 temperatures: Vec::new(),
127 }
128 }
129
130 pub fn memory(&self) -> MemoryStats {
132 let s = &self.system;
133 let available_bytes = if cfg!(target_os = "macos") {
138 s.total_memory().saturating_sub(s.used_memory())
139 } else {
140 s.available_memory()
141 };
142 #[cfg(target_os = "macos")]
143 let cached_bytes = macos_cached_bytes();
144 #[cfg(not(target_os = "macos"))]
145 let cached_bytes = None;
146 MemoryStats {
147 total_bytes: s.total_memory(),
148 used_bytes: s.used_memory(),
149 available_bytes,
150 free_bytes: s.free_memory(),
151 cached_bytes,
152 swap_total_bytes: s.total_swap(),
153 swap_used_bytes: s.used_swap(),
154 oom_kills: Vec::new(),
155 }
156 }
157
158 pub fn networks(&self, elapsed_secs: Option<f64>) -> Vec<NetworkStats> {
161 let mut networks: Vec<NetworkStats> = self
162 .networks
163 .iter()
164 .filter(|(name, _)| name.as_str() != "lo")
166 .map(|(name, data)| NetworkStats {
167 name: name.clone(),
168 rx_bytes_per_sec: rate(data.received(), elapsed_secs),
169 tx_bytes_per_sec: rate(data.transmitted(), elapsed_secs),
170 rx_total_bytes: data.total_received(),
171 tx_total_bytes: data.total_transmitted(),
172 ..Default::default()
174 })
175 .collect();
176 networks.sort_by(|a, b| a.name.cmp(&b.name));
177 networks
178 }
179
180 pub fn filesystems(&self) -> Vec<FilesystemUsage> {
183 let mut by_device: HashMap<String, FilesystemUsage> = HashMap::new();
184 for disk in self.disks.list() {
185 let fs_type = disk.file_system().to_string_lossy().into_owned();
186 if PSEUDO_FILESYSTEMS.contains(&fs_type.as_str()) || disk.total_space() == 0 {
187 continue;
188 }
189 let device = disk.name().to_string_lossy().into_owned();
190 let mount_point = disk.mount_point().to_string_lossy().into_owned();
191 let key = if cfg!(windows) || device.is_empty() {
195 mount_point.clone()
196 } else {
197 device.clone()
198 };
199 let entry = by_device.entry(key).or_insert_with(|| FilesystemUsage {
200 device,
201 fs_type,
202 mount_points: Vec::new(),
203 total_bytes: disk.total_space(),
204 available_bytes: disk.available_space(),
205 full_in_secs: None,
206 });
207 entry.mount_points.push(mount_point);
208 }
209 let mut filesystems: Vec<FilesystemUsage> = by_device.into_values().collect();
210 for fs in &mut filesystems {
211 fs.mount_points.sort_by_key(|m| (m.len(), m.clone()));
212 }
213 filesystems.sort_by(|a, b| {
215 let key = |f: &FilesystemUsage| f.mount_points.first().cloned().unwrap_or_default();
216 (key(a).len(), key(a)).cmp(&(key(b).len(), key(b)))
217 });
218 filesystems
219 }
220
221 #[cfg(not(target_os = "linux"))]
224 pub fn volume_io(&self, elapsed_secs: Option<f64>) -> Vec<DiskIo> {
225 let mut volumes: Vec<DiskIo> = self
226 .disks
227 .list()
228 .iter()
229 .filter(|disk| disk.total_space() > 0)
230 .map(|disk| {
231 let usage = disk.usage();
232 let mount = disk.mount_point().to_string_lossy();
234 let name = mount.trim_end_matches(['\\', '/']);
235 DiskIo {
236 name: if name.is_empty() {
237 mount.to_string()
238 } else {
239 name.to_owned()
240 },
241 read_bytes_per_sec: rate(usage.read_bytes, elapsed_secs),
242 write_bytes_per_sec: rate(usage.written_bytes, elapsed_secs),
243 ..Default::default()
244 }
245 })
246 .collect();
247 volumes.sort_by(|a, b| a.name.cmp(&b.name));
248 volumes.dedup_by(|a, b| a.name == b.name);
249 volumes
250 }
251
252 #[cfg(not(target_os = "linux"))]
256 pub fn components(&mut self) -> (Vec<SensorChip>, Vec<Temperature>) {
257 self.components.refresh(true);
258 let temperatures: Vec<Temperature> = self
259 .components
260 .list()
261 .iter()
262 .filter_map(|c| {
263 Some(Temperature {
264 key: format!("system/{}", c.label()),
265 label: c.label().to_owned(),
266 celsius: c.temperature()?,
267 max_celsius: c.max(),
268 critical_celsius: c.critical(),
269 })
270 })
271 .collect();
272 let cpu: Vec<Temperature> = temperatures
273 .iter()
274 .filter(|t| is_cpu_sensor_label(&t.label))
275 .cloned()
276 .collect();
277 let chips = if temperatures.is_empty() {
278 Vec::new()
279 } else {
280 vec![SensorChip {
281 key: "system".to_owned(),
282 name: "system".to_owned(),
283 temperatures,
284 fans: Vec::new(),
285 }]
286 };
287 (chips, cpu)
288 }
289
290 pub fn processes(&mut self, elapsed_secs: Option<f64>) -> Vec<ProcessInfo> {
293 let unknown_uid = self.system.processes().values().any(|p| {
296 p.user_id()
297 .is_some_and(|uid| self.users.get_user_by_id(uid).is_none())
298 });
299 if unknown_uid {
300 self.users.refresh();
301 }
302
303 self.system
304 .processes()
305 .values()
306 .filter(|p| p.thread_kind() != Some(ThreadKind::Userland))
310 .map(|p| {
311 let disk = p.disk_usage();
312 let user = p
313 .user_id()
314 .map(|uid| {
315 self.users
316 .get_user_by_id(uid)
317 .map(|u| u.name().to_owned())
318 .unwrap_or_else(|| uid.to_string())
319 })
320 .unwrap_or_default();
321 let command = p
322 .cmd()
323 .iter()
324 .map(|arg| arg.to_string_lossy())
325 .collect::<Vec<_>>()
326 .join(" ");
327 ProcessInfo {
328 pid: p.pid().as_u32(),
329 parent_pid: p.parent().map(|pid| pid.as_u32()),
330 name: p.name().to_string_lossy().into_owned(),
331 command,
332 user,
333 state: p.status().to_string(),
334 cpu_percent: p.cpu_usage(),
335 memory_bytes: p.memory(),
336 threads: None,
339 read_bytes_per_sec: rate(disk.read_bytes, elapsed_secs),
340 write_bytes_per_sec: rate(disk.written_bytes, elapsed_secs),
341 run_time_secs: p.run_time(),
342 kernel_thread: p.thread_kind() == Some(ThreadKind::Kernel),
343 container: None,
345 }
346 })
347 .collect()
348 }
349}
350
351impl Default for SystemCollector {
352 fn default() -> Self {
353 Self::new()
354 }
355}
356
357#[cfg_attr(target_os = "linux", allow(dead_code))]
360fn is_cpu_sensor_label(label: &str) -> bool {
361 let label = label.to_lowercase();
362 ["cpu", "package", "tctl", "tdie", "tccd", "core "]
363 .iter()
364 .any(|word| label.contains(word))
365}
366
367#[cfg(target_os = "macos")]
370fn macos_cached_bytes() -> Option<u64> {
371 use std::sync::OnceLock;
372
373 static HOST: OnceLock<libc::mach_port_t> = OnceLock::new();
375 #[allow(deprecated)]
377 let host = *HOST.get_or_init(|| unsafe { libc::mach_host_self() });
378
379 let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
381 let mut count = libc::HOST_VM_INFO64_COUNT;
382 let result = unsafe {
385 libc::host_statistics64(
386 host,
387 libc::HOST_VM_INFO64,
388 (&mut stats as *mut libc::vm_statistics64).cast(),
389 &mut count,
390 )
391 };
392 if result != libc::KERN_SUCCESS {
393 return None;
394 }
395 let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
397 let page_size = u64::try_from(page_size).ok().filter(|&size| size > 0)?;
398 Some(u64::from(stats.external_page_count) * page_size)
399}
400
401fn rate(bytes: u64, elapsed_secs: Option<f64>) -> f64 {
403 match elapsed_secs {
404 Some(secs) if secs > 0.0 => bytes as f64 / secs,
405 _ => 0.0,
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::*;
412
413 #[test]
414 fn cpu_sensor_labels() {
415 for label in [
416 "CPU",
417 "CPU Package",
418 "Tctl",
419 "Core 3",
420 "coretemp Package id 0",
421 ] {
422 assert!(is_cpu_sensor_label(label), "{label}");
423 }
424 for label in ["GPU", "nvme Composite", "acpitz"] {
425 assert!(!is_cpu_sensor_label(label), "{label}");
426 }
427 }
428
429 #[cfg(target_os = "macos")]
430 #[test]
431 fn macos_memory_adds_up() {
432 let memory = SystemCollector::new().memory();
433 assert!(memory.total_bytes > 0);
434 assert!(memory.used_bytes + memory.available_bytes <= memory.total_bytes);
435 let cached = memory.cached_bytes.expect("host_statistics64 answers");
436 assert!(cached > 0 && cached < memory.total_bytes, "{cached}");
437 }
438}