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