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 per_core_celsius: Vec::new(),
128 }
129 }
130
131 pub fn memory(&self) -> MemoryStats {
133 let s = &self.system;
134 let available_bytes = if cfg!(target_os = "macos") {
139 s.total_memory().saturating_sub(s.used_memory())
140 } else {
141 s.available_memory()
142 };
143 #[cfg(target_os = "macos")]
144 let cached_bytes = macos_cached_bytes();
145 #[cfg(not(target_os = "macos"))]
146 let cached_bytes = None;
147 MemoryStats {
148 total_bytes: s.total_memory(),
149 used_bytes: s.used_memory(),
150 available_bytes,
151 free_bytes: s.free_memory(),
152 cached_bytes,
153 swap_total_bytes: s.total_swap(),
154 swap_used_bytes: s.used_swap(),
155 oom_kills: Vec::new(),
156 }
157 }
158
159 pub fn networks(&self, elapsed_secs: Option<f64>) -> Vec<NetworkStats> {
162 let mut networks: Vec<NetworkStats> = self
163 .networks
164 .iter()
165 .filter(|(name, _)| name.as_str() != "lo")
167 .map(|(name, data)| NetworkStats {
168 name: name.clone(),
169 rx_bytes_per_sec: rate(data.received(), elapsed_secs),
170 tx_bytes_per_sec: rate(data.transmitted(), elapsed_secs),
171 rx_total_bytes: data.total_received(),
172 tx_total_bytes: data.total_transmitted(),
173 ..Default::default()
175 })
176 .collect();
177 networks.sort_by(|a, b| a.name.cmp(&b.name));
178 networks
179 }
180
181 pub fn filesystems(&self) -> Vec<FilesystemUsage> {
184 let mut by_device: HashMap<String, FilesystemUsage> = HashMap::new();
185 for disk in self.disks.list() {
186 let fs_type = disk.file_system().to_string_lossy().into_owned();
187 if PSEUDO_FILESYSTEMS.contains(&fs_type.as_str()) || disk.total_space() == 0 {
188 continue;
189 }
190 let device = disk.name().to_string_lossy().into_owned();
191 let mount_point = disk.mount_point().to_string_lossy().into_owned();
192 let key = if cfg!(windows) || device.is_empty() {
196 mount_point.clone()
197 } else {
198 device.clone()
199 };
200 let entry = by_device.entry(key).or_insert_with(|| FilesystemUsage {
201 device,
202 fs_type,
203 mount_points: Vec::new(),
204 total_bytes: disk.total_space(),
205 available_bytes: disk.available_space(),
206 full_in_secs: None,
207 });
208 entry.mount_points.push(mount_point);
209 }
210 let mut filesystems: Vec<FilesystemUsage> = by_device.into_values().collect();
211 for fs in &mut filesystems {
212 fs.mount_points.sort_by_key(|m| (m.len(), m.clone()));
213 }
214 filesystems.sort_by(|a, b| {
216 let key = |f: &FilesystemUsage| f.mount_points.first().cloned().unwrap_or_default();
217 (key(a).len(), key(a)).cmp(&(key(b).len(), key(b)))
218 });
219 filesystems
220 }
221
222 #[cfg(not(target_os = "linux"))]
225 pub fn volume_io(&self, elapsed_secs: Option<f64>) -> Vec<DiskIo> {
226 let mut volumes: Vec<DiskIo> = self
227 .disks
228 .list()
229 .iter()
230 .filter(|disk| disk.total_space() > 0)
231 .map(|disk| {
232 let usage = disk.usage();
233 let mount = disk.mount_point().to_string_lossy();
235 let name = mount.trim_end_matches(['\\', '/']);
236 DiskIo {
237 name: if name.is_empty() {
238 mount.to_string()
239 } else {
240 name.to_owned()
241 },
242 read_bytes_per_sec: rate(usage.read_bytes, elapsed_secs),
243 write_bytes_per_sec: rate(usage.written_bytes, elapsed_secs),
244 ..Default::default()
245 }
246 })
247 .collect();
248 volumes.sort_by(|a, b| a.name.cmp(&b.name));
249 volumes.dedup_by(|a, b| a.name == b.name);
250 volumes
251 }
252
253 #[cfg(not(target_os = "linux"))]
257 pub fn components(&mut self) -> (Vec<SensorChip>, Vec<Temperature>) {
258 self.components.refresh(true);
259 let temperatures: Vec<Temperature> = self
260 .components
261 .list()
262 .iter()
263 .filter_map(|c| {
264 Some(Temperature {
265 key: format!("system/{}", c.label()),
266 label: c.label().to_owned(),
267 celsius: c.temperature()?,
268 max_celsius: c.max(),
269 critical_celsius: c.critical(),
270 })
271 })
272 .collect();
273 let cpu: Vec<Temperature> = temperatures
274 .iter()
275 .filter(|t| is_cpu_sensor_label(&t.label))
276 .cloned()
277 .collect();
278 let chips = if temperatures.is_empty() {
279 Vec::new()
280 } else {
281 vec![SensorChip {
282 key: "system".to_owned(),
283 name: "system".to_owned(),
284 temperatures,
285 fans: Vec::new(),
286 }]
287 };
288 (chips, cpu)
289 }
290
291 pub fn processes(&mut self, elapsed_secs: Option<f64>) -> Vec<ProcessInfo> {
294 let unknown_uid = self.system.processes().values().any(|p| {
297 p.user_id()
298 .is_some_and(|uid| self.users.get_user_by_id(uid).is_none())
299 });
300 if unknown_uid {
301 self.users.refresh();
302 }
303
304 self.system
305 .processes()
306 .values()
307 .filter(|p| p.thread_kind() != Some(ThreadKind::Userland))
311 .map(|p| {
312 let disk = p.disk_usage();
313 let user = p
314 .user_id()
315 .map(|uid| {
316 self.users
317 .get_user_by_id(uid)
318 .map(|u| u.name().to_owned())
319 .unwrap_or_else(|| uid.to_string())
320 })
321 .unwrap_or_default();
322 let command = p
323 .cmd()
324 .iter()
325 .map(|arg| arg.to_string_lossy())
326 .collect::<Vec<_>>()
327 .join(" ");
328 let name = p.name().to_string_lossy();
329 let leading: Vec<_> = p
330 .cmd()
331 .iter()
332 .take(2)
333 .map(|a| a.to_string_lossy())
334 .collect();
335 let leading: Vec<&str> = leading.iter().map(|a| a.as_ref()).collect();
336 ProcessInfo {
337 pid: p.pid().as_u32(),
338 parent_pid: p.parent().map(|pid| pid.as_u32()),
339 name: full_name(&name, &leading),
340 command,
341 user,
342 state: p.status().to_string(),
343 cpu_percent: p.cpu_usage(),
344 memory_bytes: p.memory(),
345 threads: None,
348 nice: None,
350 read_bytes_per_sec: rate(disk.read_bytes, elapsed_secs),
351 write_bytes_per_sec: rate(disk.written_bytes, elapsed_secs),
352 run_time_secs: p.run_time(),
353 kernel_thread: p.thread_kind() == Some(ThreadKind::Kernel),
354 container: None,
356 }
357 })
358 .collect()
359 }
360}
361
362impl Default for SystemCollector {
363 fn default() -> Self {
364 Self::new()
365 }
366}
367
368#[cfg_attr(target_os = "linux", allow(dead_code))]
371fn is_cpu_sensor_label(label: &str) -> bool {
372 let label = label.to_lowercase();
373 ["cpu", "package", "tctl", "tdie", "tccd", "core "]
374 .iter()
375 .any(|word| label.contains(word))
376}
377
378#[cfg(target_os = "macos")]
381fn macos_cached_bytes() -> Option<u64> {
382 use std::sync::OnceLock;
383
384 static HOST: OnceLock<libc::mach_port_t> = OnceLock::new();
386 #[allow(deprecated)]
388 let host = *HOST.get_or_init(|| unsafe { libc::mach_host_self() });
389
390 let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
392 let mut count = libc::HOST_VM_INFO64_COUNT;
393 let result = unsafe {
396 libc::host_statistics64(
397 host,
398 libc::HOST_VM_INFO64,
399 (&mut stats as *mut libc::vm_statistics64).cast(),
400 &mut count,
401 )
402 };
403 if result != libc::KERN_SUCCESS {
404 return None;
405 }
406 let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
408 let page_size = u64::try_from(page_size).ok().filter(|&size| size > 0)?;
409 Some(u64::from(stats.external_page_count) * page_size)
410}
411
412fn rate(bytes: u64, elapsed_secs: Option<f64>) -> f64 {
414 match elapsed_secs {
415 Some(secs) if secs > 0.0 => bytes as f64 / secs,
416 _ => 0.0,
417 }
418}
419
420const COMM_LEN: usize = 15;
423
424fn full_name(name: &str, leading: &[&str]) -> String {
430 let file = |arg: &str| {
431 arg.rsplit(['/', '\\'])
432 .next()
433 .unwrap_or_default()
434 .trim()
435 .to_owned()
436 };
437 if name == "MainThread"
438 && let Some(program) = leading.first().map(|a| file(a)).filter(|f| !f.is_empty())
439 {
440 return program;
441 }
442 if cfg!(target_os = "linux") && name.len() == COMM_LEN {
444 for arg in leading {
445 let file = file(arg);
446 if file.len() > name.len() && file.starts_with(name) {
447 return file;
448 }
449 }
450 }
451 name.to_owned()
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457
458 #[test]
459 fn names_cut_short_or_renamed_take_the_program_file() {
460 let linux = cfg!(target_os = "linux");
461 let cut = full_name(
462 "gnome-keyring-d",
463 &["/usr/bin/gnome-keyring-daemon", "--start"],
464 );
465 assert_eq!(
466 cut,
467 if linux {
468 "gnome-keyring-daemon"
469 } else {
470 "gnome-keyring-d"
471 }
472 );
473 let script = full_name(
474 "networkd-dispat",
475 &["/usr/bin/python3", "/usr/bin/networkd-dispatcher"],
476 );
477 assert_eq!(
478 script,
479 if linux {
480 "networkd-dispatcher"
481 } else {
482 "networkd-dispat"
483 }
484 );
485 assert_eq!(
486 full_name("MainThread", &["/usr/local/bin/node", "server.js"]),
487 "node"
488 );
489 assert_eq!(full_name("python3", &["/usr/bin/python3.12"]), "python3");
491 assert_eq!(
494 full_name(
495 "Isolated Web Co",
496 &["/usr/lib/firefox/firefox", "-contentproc"]
497 ),
498 "Isolated Web Co"
499 );
500 assert_eq!(
501 full_name("postgres", &["postgres: checkpointer"]),
502 "postgres"
503 );
504 assert_eq!(full_name("kworker/0:1H-ev", &[]), "kworker/0:1H-ev");
506 assert_eq!(full_name("MainThread", &[]), "MainThread");
507 }
508
509 #[test]
510 fn cpu_sensor_labels() {
511 for label in [
512 "CPU",
513 "CPU Package",
514 "Tctl",
515 "Core 3",
516 "coretemp Package id 0",
517 ] {
518 assert!(is_cpu_sensor_label(label), "{label}");
519 }
520 for label in ["GPU", "nvme Composite", "acpitz"] {
521 assert!(!is_cpu_sensor_label(label), "{label}");
522 }
523 }
524
525 #[cfg(target_os = "macos")]
526 #[test]
527 fn macos_memory_adds_up() {
528 let memory = SystemCollector::new().memory();
529 assert!(memory.total_bytes > 0);
530 assert!(memory.used_bytes + memory.available_bytes <= memory.total_bytes);
531 let cached = memory.cached_bytes.expect("host_statistics64 answers");
532 assert!(cached > 0 && cached < memory.total_bytes, "{cached}");
533 }
534}