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        }
108    }
109
110    /// CPU load and frequencies. Temperatures are filled in by the caller.
111    pub fn cpu(&self) -> CpuStats {
112        let cpus = self.system.cpus();
113        let load = System::load_average();
114        CpuStats {
115            model: cpus
116                .first()
117                .map(|c| c.brand().trim().to_owned())
118                .unwrap_or_default(),
119            total_percent: self.system.global_cpu_usage(),
120            per_core_percent: cpus.iter().map(|c| c.cpu_usage()).collect(),
121            per_core_mhz: cpus.iter().map(|c| c.frequency()).collect(),
122            // Windows has no load average (sysinfo reports zeros).
123            load_average: cfg!(unix).then_some([load.one, load.five, load.fifteen]),
124            temperatures: Vec::new(),
125        }
126    }
127
128    /// Memory and swap. `cached_bytes` is filled in by the caller where available.
129    pub fn memory(&self) -> MemoryStats {
130        let s = &self.system;
131        MemoryStats {
132            total_bytes: s.total_memory(),
133            used_bytes: s.used_memory(),
134            available_bytes: s.available_memory(),
135            free_bytes: s.free_memory(),
136            cached_bytes: None,
137            swap_total_bytes: s.total_swap(),
138            swap_used_bytes: s.used_swap(),
139        }
140    }
141
142    /// Network traffic per interface. `elapsed_secs` is the time since the
143    /// previous refresh; rates are zero when it is unknown.
144    pub fn networks(&self, elapsed_secs: Option<f64>) -> Vec<NetworkStats> {
145        let mut networks: Vec<NetworkStats> = self
146            .networks
147            .iter()
148            // Loopback traffic is local IPC, not network activity.
149            .filter(|(name, _)| name.as_str() != "lo")
150            .map(|(name, data)| NetworkStats {
151                name: name.clone(),
152                rx_bytes_per_sec: rate(data.received(), elapsed_secs),
153                tx_bytes_per_sec: rate(data.transmitted(), elapsed_secs),
154                rx_total_bytes: data.total_received(),
155                tx_total_bytes: data.total_transmitted(),
156                // Link state is platform-specific and filled in by the caller.
157                ..Default::default()
158            })
159            .collect();
160        networks.sort_by(|a, b| a.name.cmp(&b.name));
161        networks
162    }
163
164    /// Mounted filesystems, merged by source device so that btrfs subvolumes
165    /// and bind mounts appear once.
166    pub fn filesystems(&self) -> Vec<FilesystemUsage> {
167        let mut by_device: HashMap<String, FilesystemUsage> = HashMap::new();
168        for disk in self.disks.list() {
169            let fs_type = disk.file_system().to_string_lossy().into_owned();
170            if PSEUDO_FILESYSTEMS.contains(&fs_type.as_str()) || disk.total_space() == 0 {
171                continue;
172            }
173            let device = disk.name().to_string_lossy().into_owned();
174            let mount_point = disk.mount_point().to_string_lossy().into_owned();
175            // On Unix the name is the source device, which merges btrfs
176            // subvolumes and bind mounts. On Windows it is the volume label,
177            // often empty or shared, so each drive letter stands alone.
178            let key = if cfg!(windows) || device.is_empty() {
179                mount_point.clone()
180            } else {
181                device.clone()
182            };
183            let entry = by_device.entry(key).or_insert_with(|| FilesystemUsage {
184                device,
185                fs_type,
186                mount_points: Vec::new(),
187                total_bytes: disk.total_space(),
188                available_bytes: disk.available_space(),
189            });
190            entry.mount_points.push(mount_point);
191        }
192        let mut filesystems: Vec<FilesystemUsage> = by_device.into_values().collect();
193        for fs in &mut filesystems {
194            fs.mount_points.sort_by_key(|m| (m.len(), m.clone()));
195        }
196        // Order by the most prominent mount point ("/" first).
197        filesystems.sort_by(|a, b| {
198            let key = |f: &FilesystemUsage| f.mount_points.first().cloned().unwrap_or_default();
199            (key(a).len(), key(a)).cmp(&(key(b).len(), key(b)))
200        });
201        filesystems
202    }
203
204    /// I/O rates per mounted volume, for platforms without per-device
205    /// counters (Linux uses `/proc/diskstats` instead).
206    #[cfg(not(target_os = "linux"))]
207    pub fn volume_io(&self, elapsed_secs: Option<f64>) -> Vec<DiskIo> {
208        let mut volumes: Vec<DiskIo> = self
209            .disks
210            .list()
211            .iter()
212            .filter(|disk| disk.total_space() > 0)
213            .map(|disk| {
214                let usage = disk.usage();
215                // "C:\" -> "C:"; elsewhere the mount point as is.
216                let mount = disk.mount_point().to_string_lossy();
217                let name = mount.trim_end_matches(['\\', '/']);
218                DiskIo {
219                    name: if name.is_empty() {
220                        mount.to_string()
221                    } else {
222                        name.to_owned()
223                    },
224                    read_bytes_per_sec: rate(usage.read_bytes, elapsed_secs),
225                    write_bytes_per_sec: rate(usage.written_bytes, elapsed_secs),
226                    ..Default::default()
227                }
228            })
229            .collect();
230        volumes.sort_by(|a, b| a.name.cmp(&b.name));
231        volumes.dedup_by(|a, b| a.name == b.name);
232        volumes
233    }
234
235    /// Temperatures `sysinfo` can read (on Windows only what WMI exposes,
236    /// often nothing without vendor drivers), as one sensor chip plus the
237    /// readings that look like CPU sensors.
238    #[cfg(not(target_os = "linux"))]
239    pub fn components(&mut self) -> (Vec<SensorChip>, Vec<Temperature>) {
240        self.components.refresh(true);
241        let temperatures: Vec<Temperature> = self
242            .components
243            .list()
244            .iter()
245            .filter_map(|c| {
246                Some(Temperature {
247                    key: format!("system/{}", c.label()),
248                    label: c.label().to_owned(),
249                    celsius: c.temperature()?,
250                    max_celsius: c.max(),
251                    critical_celsius: c.critical(),
252                })
253            })
254            .collect();
255        let cpu: Vec<Temperature> = temperatures
256            .iter()
257            .filter(|t| is_cpu_sensor_label(&t.label))
258            .cloned()
259            .collect();
260        let chips = if temperatures.is_empty() {
261            Vec::new()
262        } else {
263            vec![SensorChip {
264                key: "system".to_owned(),
265                name: "system".to_owned(),
266                temperatures,
267                fans: Vec::new(),
268            }]
269        };
270        (chips, cpu)
271    }
272
273    /// All processes (threads excluded). `elapsed_secs` converts the I/O
274    /// byte counts since the previous refresh into rates.
275    pub fn processes(&mut self, elapsed_secs: Option<f64>) -> Vec<ProcessInfo> {
276        // Resolve uids lazily: refresh the user list only when an unknown uid shows up
277        // (e.g. a user created after rigtop started).
278        let unknown_uid = self.system.processes().values().any(|p| {
279            p.user_id()
280                .is_some_and(|uid| self.users.get_user_by_id(uid).is_none())
281        });
282        if unknown_uid {
283            self.users.refresh();
284        }
285
286        self.system
287            .processes()
288            .values()
289            // With tasks refreshed, sysinfo would also list each thread as
290            // an entry; make sure none slip in. Kernel threads (kworker,
291            // ...) are kept and flagged, like btop does.
292            .filter(|p| p.thread_kind() != Some(ThreadKind::Userland))
293            .map(|p| {
294                let disk = p.disk_usage();
295                let user = p
296                    .user_id()
297                    .map(|uid| {
298                        self.users
299                            .get_user_by_id(uid)
300                            .map(|u| u.name().to_owned())
301                            .unwrap_or_else(|| uid.to_string())
302                    })
303                    .unwrap_or_default();
304                let command = p
305                    .cmd()
306                    .iter()
307                    .map(|arg| arg.to_string_lossy())
308                    .collect::<Vec<_>>()
309                    .join(" ");
310                ProcessInfo {
311                    pid: p.pid().as_u32(),
312                    parent_pid: p.parent().map(|pid| pid.as_u32()),
313                    name: p.name().to_string_lossy().into_owned(),
314                    command,
315                    user,
316                    state: p.status().to_string(),
317                    cpu_percent: p.cpu_usage(),
318                    memory_bytes: p.memory(),
319                    // Filled in from /proc/<pid>/stat on Linux; sysinfo has
320                    // no count without refreshing every thread.
321                    threads: None,
322                    read_bytes_per_sec: rate(disk.read_bytes, elapsed_secs),
323                    write_bytes_per_sec: rate(disk.written_bytes, elapsed_secs),
324                    run_time_secs: p.run_time(),
325                    kernel_thread: p.thread_kind() == Some(ThreadKind::Kernel),
326                }
327            })
328            .collect()
329    }
330}
331
332impl Default for SystemCollector {
333    fn default() -> Self {
334        Self::new()
335    }
336}
337
338/// Whether a sensor label from `sysinfo` describes the CPU (e.g. "CPU",
339/// "CPU Package", "Tctl", "Core 0").
340#[cfg_attr(target_os = "linux", allow(dead_code))]
341fn is_cpu_sensor_label(label: &str) -> bool {
342    let label = label.to_lowercase();
343    ["cpu", "package", "tctl", "tdie", "tccd", "core "]
344        .iter()
345        .any(|word| label.contains(word))
346}
347
348/// Converts a byte count accumulated over `elapsed_secs` into bytes per second.
349fn rate(bytes: u64, elapsed_secs: Option<f64>) -> f64 {
350    match elapsed_secs {
351        Some(secs) if secs > 0.0 => bytes as f64 / secs,
352        _ => 0.0,
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn cpu_sensor_labels() {
362        for label in [
363            "CPU",
364            "CPU Package",
365            "Tctl",
366            "Core 3",
367            "coretemp Package id 0",
368        ] {
369            assert!(is_cpu_sensor_label(label), "{label}");
370        }
371        for label in ["GPU", "nvme Composite", "acpitz"] {
372            assert!(!is_cpu_sensor_label(label), "{label}");
373        }
374    }
375}