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 ProcessInfo {
329 pid: p.pid().as_u32(),
330 parent_pid: p.parent().map(|pid| pid.as_u32()),
331 name: p.name().to_string_lossy().into_owned(),
332 command,
333 user,
334 state: p.status().to_string(),
335 cpu_percent: p.cpu_usage(),
336 memory_bytes: p.memory(),
337 threads: None,
340 nice: None,
342 read_bytes_per_sec: rate(disk.read_bytes, elapsed_secs),
343 write_bytes_per_sec: rate(disk.written_bytes, elapsed_secs),
344 run_time_secs: p.run_time(),
345 kernel_thread: p.thread_kind() == Some(ThreadKind::Kernel),
346 container: None,
348 }
349 })
350 .collect()
351 }
352}
353
354impl Default for SystemCollector {
355 fn default() -> Self {
356 Self::new()
357 }
358}
359
360#[cfg_attr(target_os = "linux", allow(dead_code))]
363fn is_cpu_sensor_label(label: &str) -> bool {
364 let label = label.to_lowercase();
365 ["cpu", "package", "tctl", "tdie", "tccd", "core "]
366 .iter()
367 .any(|word| label.contains(word))
368}
369
370#[cfg(target_os = "macos")]
373fn macos_cached_bytes() -> Option<u64> {
374 use std::sync::OnceLock;
375
376 static HOST: OnceLock<libc::mach_port_t> = OnceLock::new();
378 #[allow(deprecated)]
380 let host = *HOST.get_or_init(|| unsafe { libc::mach_host_self() });
381
382 let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
384 let mut count = libc::HOST_VM_INFO64_COUNT;
385 let result = unsafe {
388 libc::host_statistics64(
389 host,
390 libc::HOST_VM_INFO64,
391 (&mut stats as *mut libc::vm_statistics64).cast(),
392 &mut count,
393 )
394 };
395 if result != libc::KERN_SUCCESS {
396 return None;
397 }
398 let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
400 let page_size = u64::try_from(page_size).ok().filter(|&size| size > 0)?;
401 Some(u64::from(stats.external_page_count) * page_size)
402}
403
404fn rate(bytes: u64, elapsed_secs: Option<f64>) -> f64 {
406 match elapsed_secs {
407 Some(secs) if secs > 0.0 => bytes as f64 / secs,
408 _ => 0.0,
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 #[test]
417 fn cpu_sensor_labels() {
418 for label in [
419 "CPU",
420 "CPU Package",
421 "Tctl",
422 "Core 3",
423 "coretemp Package id 0",
424 ] {
425 assert!(is_cpu_sensor_label(label), "{label}");
426 }
427 for label in ["GPU", "nvme Composite", "acpitz"] {
428 assert!(!is_cpu_sensor_label(label), "{label}");
429 }
430 }
431
432 #[cfg(target_os = "macos")]
433 #[test]
434 fn macos_memory_adds_up() {
435 let memory = SystemCollector::new().memory();
436 assert!(memory.total_bytes > 0);
437 assert!(memory.used_bytes + memory.available_bytes <= memory.total_bytes);
438 let cached = memory.cached_bytes.expect("host_statistics64 answers");
439 assert!(cached > 0 && cached < memory.total_bytes, "{cached}");
440 }
441}