Skip to main content

rigtop_core/
system.rs

1//! Portable statistics via the `sysinfo` crate: CPU load, memory, processes,
2//! network traffic and filesystem capacity.
3//!
4//! Platform-specific extras (sensors, RAID, per-device I/O) live in
5//! [`crate::linux`] and are merged by [`crate::source::LocalSource`]. On other
6//! platforms this module also provides per-volume I/O and the temperatures
7//! `sysinfo` can see.
8
9use 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
22/// What to refresh for disks: capacity everywhere; per-volume I/O counters
23/// only where `/proc/diskstats` (per physical device) is not available.
24fn 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
33/// Filesystem types that are never interesting in a disk panel.
34const 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
48/// Wraps the `sysinfo` handles that must persist between refreshes
49/// (CPU usage and rates are computed from differences).
50pub struct SystemCollector {
51    system: System,
52    networks: Networks,
53    disks: Disks,
54    users: Users,
55    /// Temperature sensors, where hwmon is not available.
56    #[cfg(not(target_os = "linux"))]
57    components: sysinfo::Components,
58}
59
60impl SystemCollector {
61    /// Creates the collector and takes an initial reading.
62    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    /// Refreshes everything this collector reports.
76    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                // Tasks are on by default and make sysinfo refresh every
89                // thread as well (several /proc reads each), most of the
90                // collection time on busy desktops. Thread counts come from
91                // /proc/<pid>/stat on Linux instead.
92                .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    /// Host name, OS and uptime.
101    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    /// CPU load and frequencies. Temperatures are filled in by the caller.
113    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            // Windows has no load average (sysinfo reports zeros).
125            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    /// Memory and swap. On Linux `cached_bytes` is filled in by the caller.
132    pub fn memory(&self) -> MemoryStats {
133        let s = &self.system;
134        // On macOS sysinfo's available memory is the kernel's memory-pressure
135        // headroom (active + inactive + free pages), which overlaps "used"
136        // (Activity Monitor's Memory Used). Show what is left of the total
137        // instead, as Activity Monitor does.
138        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    /// Network traffic per interface. `elapsed_secs` is the time since the
160    /// previous refresh; rates are zero when it is unknown.
161    pub fn networks(&self, elapsed_secs: Option<f64>) -> Vec<NetworkStats> {
162        let mut networks: Vec<NetworkStats> = self
163            .networks
164            .iter()
165            // Loopback traffic is local IPC, not network activity.
166            .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                // Link state is platform-specific and filled in by the caller.
174                ..Default::default()
175            })
176            .collect();
177        networks.sort_by(|a, b| a.name.cmp(&b.name));
178        networks
179    }
180
181    /// Mounted filesystems, merged by source device so that btrfs subvolumes
182    /// and bind mounts appear once.
183    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            // On Unix the name is the source device, which merges btrfs
193            // subvolumes and bind mounts. On Windows it is the volume label,
194            // often empty or shared, so each drive letter stands alone.
195            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        // Order by the most prominent mount point ("/" first).
215        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    /// I/O rates per mounted volume, for platforms without per-device
223    /// counters (Linux uses `/proc/diskstats` instead).
224    #[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                // "C:\" -> "C:"; elsewhere the mount point as is.
234                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    /// Temperatures `sysinfo` can read (on Windows only what WMI exposes,
254    /// often nothing without vendor drivers), as one sensor chip plus the
255    /// readings that look like CPU sensors.
256    #[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    /// All processes (threads excluded). `elapsed_secs` converts the I/O
292    /// byte counts since the previous refresh into rates.
293    pub fn processes(&mut self, elapsed_secs: Option<f64>) -> Vec<ProcessInfo> {
294        // Resolve uids lazily: refresh the user list only when an unknown uid shows up
295        // (e.g. a user created after rigtop started).
296        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            // With tasks refreshed, sysinfo would also list each thread as
308            // an entry; make sure none slip in. Kernel threads (kworker,
309            // ...) are kept and flagged, like btop does.
310            .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                    // Filled in from /proc/<pid>/stat on Linux; sysinfo has
346                    // no count without refreshing every thread.
347                    threads: None,
348                    // Also from /proc/<pid>/stat on Linux.
349                    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                    // Filled in from /proc/<pid>/cgroup on Linux.
355                    container: None,
356                }
357            })
358            .collect()
359    }
360}
361
362impl Default for SystemCollector {
363    fn default() -> Self {
364        Self::new()
365    }
366}
367
368/// Whether a sensor label from `sysinfo` describes the CPU (e.g. "CPU",
369/// "CPU Package", "Tctl", "Core 0").
370#[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/// File-backed pages on macOS (Activity Monitor's "Cached Files"), the
379/// counterpart of Linux's page cache; `None` if the kernel does not answer.
380#[cfg(target_os = "macos")]
381fn macos_cached_bytes() -> Option<u64> {
382    use std::sync::OnceLock;
383
384    // Every mach_host_self() call adds a reference to the port, so keep one.
385    static HOST: OnceLock<libc::mach_port_t> = OnceLock::new();
386    // SAFETY: mach_host_self takes no arguments and returns a port name.
387    #[allow(deprecated)]
388    let host = *HOST.get_or_init(|| unsafe { libc::mach_host_self() });
389
390    // SAFETY: an all-zero vm_statistics64 is valid (plain integers).
391    let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
392    let mut count = libc::HOST_VM_INFO64_COUNT;
393    // SAFETY: `stats` is a vm_statistics64 and `count` its size in integers,
394    // as HOST_VM_INFO64 requires.
395    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    // SAFETY: sysconf has no preconditions.
407    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
412/// Converts a byte count accumulated over `elapsed_secs` into bytes per second.
413fn 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
420/// Longest process name Linux keeps (`TASK_COMM_LEN` minus the NUL);
421/// longer ones are cut, e.g. `gnome-keyring-d` for `gnome-keyring-daemon`.
422const COMM_LEN: usize = 15;
423
424/// The name to show for a process: its kernel name, unless that is cut
425/// short (Linux keeps 15 bytes) or a thread name its program set for its
426/// main thread (`MainThread` in Node.js), where the file name of the
427/// program in its command line says more. `leading` is the start of the
428/// command line: the program, then (for a script) the script.
429fn 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    // A script's name is the kernel name too: `python3 /usr/bin/networkd-dispatcher`.
443    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        // A name that fits stays, whatever the command line says.
490        assert_eq!(full_name("python3", &["/usr/bin/python3.12"]), "python3");
491        // Programs that rewrite their command line (setproctitle) keep the
492        // kernel name: the line no longer starts with the program.
493        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        // Kernel threads have no command line.
505        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}