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        }
128    }
129
130    /// Memory and swap. On Linux `cached_bytes` is filled in by the caller.
131    pub fn memory(&self) -> MemoryStats {
132        let s = &self.system;
133        // On macOS sysinfo's available memory is the kernel's memory-pressure
134        // headroom (active + inactive + free pages), which overlaps "used"
135        // (Activity Monitor's Memory Used). Show what is left of the total
136        // instead, as Activity Monitor does.
137        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    /// Network traffic per interface. `elapsed_secs` is the time since the
159    /// previous refresh; rates are zero when it is unknown.
160    pub fn networks(&self, elapsed_secs: Option<f64>) -> Vec<NetworkStats> {
161        let mut networks: Vec<NetworkStats> = self
162            .networks
163            .iter()
164            // Loopback traffic is local IPC, not network activity.
165            .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                // Link state is platform-specific and filled in by the caller.
173                ..Default::default()
174            })
175            .collect();
176        networks.sort_by(|a, b| a.name.cmp(&b.name));
177        networks
178    }
179
180    /// Mounted filesystems, merged by source device so that btrfs subvolumes
181    /// and bind mounts appear once.
182    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            // On Unix the name is the source device, which merges btrfs
192            // subvolumes and bind mounts. On Windows it is the volume label,
193            // often empty or shared, so each drive letter stands alone.
194            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        // Order by the most prominent mount point ("/" first).
214        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    /// I/O rates per mounted volume, for platforms without per-device
222    /// counters (Linux uses `/proc/diskstats` instead).
223    #[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                // "C:\" -> "C:"; elsewhere the mount point as is.
233                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    /// Temperatures `sysinfo` can read (on Windows only what WMI exposes,
253    /// often nothing without vendor drivers), as one sensor chip plus the
254    /// readings that look like CPU sensors.
255    #[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    /// All processes (threads excluded). `elapsed_secs` converts the I/O
291    /// byte counts since the previous refresh into rates.
292    pub fn processes(&mut self, elapsed_secs: Option<f64>) -> Vec<ProcessInfo> {
293        // Resolve uids lazily: refresh the user list only when an unknown uid shows up
294        // (e.g. a user created after rigtop started).
295        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            // With tasks refreshed, sysinfo would also list each thread as
307            // an entry; make sure none slip in. Kernel threads (kworker,
308            // ...) are kept and flagged, like btop does.
309            .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                    // Filled in from /proc/<pid>/stat on Linux; sysinfo has
337                    // no count without refreshing every thread.
338                    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                    // Filled in from /proc/<pid>/cgroup on Linux.
344                    container: None,
345                }
346            })
347            .collect()
348    }
349}
350
351impl Default for SystemCollector {
352    fn default() -> Self {
353        Self::new()
354    }
355}
356
357/// Whether a sensor label from `sysinfo` describes the CPU (e.g. "CPU",
358/// "CPU Package", "Tctl", "Core 0").
359#[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/// File-backed pages on macOS (Activity Monitor's "Cached Files"), the
368/// counterpart of Linux's page cache; `None` if the kernel does not answer.
369#[cfg(target_os = "macos")]
370fn macos_cached_bytes() -> Option<u64> {
371    use std::sync::OnceLock;
372
373    // Every mach_host_self() call adds a reference to the port, so keep one.
374    static HOST: OnceLock<libc::mach_port_t> = OnceLock::new();
375    // SAFETY: mach_host_self takes no arguments and returns a port name.
376    #[allow(deprecated)]
377    let host = *HOST.get_or_init(|| unsafe { libc::mach_host_self() });
378
379    // SAFETY: an all-zero vm_statistics64 is valid (plain integers).
380    let mut stats: libc::vm_statistics64 = unsafe { std::mem::zeroed() };
381    let mut count = libc::HOST_VM_INFO64_COUNT;
382    // SAFETY: `stats` is a vm_statistics64 and `count` its size in integers,
383    // as HOST_VM_INFO64 requires.
384    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    // SAFETY: sysconf has no preconditions.
396    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
401/// Converts a byte count accumulated over `elapsed_secs` into bytes per second.
402fn 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}