Skip to main content

rigtop_core/
source.rs

1//! Data sources: anything that can produce [`Snapshot`]s.
2//!
3//! Front-ends only talk to the [`DataSource`] trait. The local machine is one
4//! implementation ([`LocalSource`]); a remote host reached through
5//! `ssh host rigtop --agent` will be another, so remote monitoring needs no
6//! changes in the front-ends.
7
8use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
9
10use crate::config::Config;
11use crate::gpu::NvmlCollector;
12use crate::smart::SmartReader;
13#[cfg(target_os = "linux")]
14use crate::snapshot::device_matches_disk;
15use crate::snapshot::{PowerStats, Snapshot};
16use crate::system::SystemCollector;
17
18#[cfg(target_os = "linux")]
19use crate::linux::{
20    self, SysRoots, diskstats::DiskStatsMeter, net::NetLinkReader, rapl::RaplMeter,
21};
22
23/// Shortest sensible interval between two polls. CPU usage is computed from
24/// the difference between polls and is inaccurate below this.
25pub const MIN_POLL_INTERVAL: Duration = sysinfo::MINIMUM_CPU_UPDATE_INTERVAL;
26
27/// Errors a data source can report.
28#[derive(Debug, thiserror::Error)]
29pub enum SourceError {
30    /// Reading from the underlying channel failed.
31    #[error("I/O error: {0}")]
32    Io(#[from] std::io::Error),
33    /// The source is no longer available (e.g. the SSH connection closed).
34    #[error("source disconnected: {0}")]
35    Disconnected(String),
36    /// The remote agent reported a problem or does not speak our protocol.
37    #[error("remote: {0}")]
38    Remote(String),
39    /// Sending a signal to a process failed (no such process, permission denied, ...).
40    #[error("cannot signal process {pid}: {source}")]
41    Signal {
42        /// Target process id.
43        pid: u32,
44        /// Underlying OS error.
45        source: std::io::Error,
46    },
47}
48
49/// Signals a front-end can send to a process.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
51pub enum ProcessSignal {
52    /// Ask the process to exit (SIGTERM).
53    Terminate,
54    /// Force the process to exit (SIGKILL).
55    Kill,
56}
57
58/// A producer of snapshots, local or remote.
59pub trait DataSource {
60    /// Takes a new measurement.
61    ///
62    /// Rates (CPU %, throughput, power) cover the time since the previous
63    /// call, so callers should poll at a steady interval of at least
64    /// [`MIN_POLL_INTERVAL`].
65    fn poll(&mut self) -> Result<Snapshot, SourceError>;
66
67    /// Sends `signal` to process `pid` on the monitored host, with the
68    /// privileges of the user the source runs as.
69    fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError>;
70
71    /// Tells the source how often it will be polled. Remote sources forward
72    /// this to the agent, which samples on its own schedule; local sources
73    /// need nothing.
74    fn set_interval(&mut self, _interval: Duration) {}
75
76    /// Limits snapshots to the top `limit` processes by CPU (`None`: all).
77    /// Remote sources use this to save bandwidth for hosts in an overview.
78    fn set_process_limit(&mut self, _limit: Option<usize>) {}
79}
80
81/// Boxed sources, so front-ends can choose local or remote at run time.
82impl<T: DataSource + ?Sized> DataSource for Box<T> {
83    fn poll(&mut self) -> Result<Snapshot, SourceError> {
84        (**self).poll()
85    }
86
87    fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError> {
88        (**self).signal_process(pid, signal)
89    }
90
91    fn set_interval(&mut self, interval: Duration) {
92        (**self).set_interval(interval);
93    }
94
95    fn set_process_limit(&mut self, limit: Option<usize>) {
96        (**self).set_process_limit(limit);
97    }
98}
99
100/// Collects snapshots of the machine rigtop runs on.
101pub struct LocalSource {
102    system: SystemCollector,
103    nvml: NvmlCollector,
104    smart: SmartReader,
105    last_poll: Option<Instant>,
106    #[cfg(target_os = "linux")]
107    roots: SysRoots,
108    #[cfg(target_os = "linux")]
109    rapl: RaplMeter,
110    #[cfg(target_os = "linux")]
111    diskstats: DiskStatsMeter,
112    #[cfg(target_os = "linux")]
113    net_links: NetLinkReader,
114    /// Directories searched for btrfs scrub status files, in order.
115    #[cfg(target_os = "linux")]
116    scrub_dirs: Vec<std::path::PathBuf>,
117}
118
119impl LocalSource {
120    /// Creates a source with the default configuration. See [`LocalSource::with_config`].
121    pub fn new() -> Self {
122        Self::with_config(&Config::default())
123    }
124
125    /// Creates a source and takes a warm-up sample, so that the first
126    /// [`DataSource::poll`] (after at least [`MIN_POLL_INTERVAL`]) already
127    /// has rates.
128    ///
129    /// Only collection-related settings (the SMART directory) are used here;
130    /// display settings such as sensor labels are applied by front-ends.
131    pub fn with_config(config: &Config) -> Self {
132        let mut source = Self {
133            system: SystemCollector::new(),
134            nvml: NvmlCollector::new(),
135            smart: SmartReader::new(&config.smart.dir),
136            last_poll: None,
137            #[cfg(target_os = "linux")]
138            roots: SysRoots::default(),
139            #[cfg(target_os = "linux")]
140            rapl: RaplMeter::new(),
141            #[cfg(target_os = "linux")]
142            diskstats: DiskStatsMeter::new(),
143            #[cfg(target_os = "linux")]
144            net_links: NetLinkReader::new(),
145            // The copy made by the root collector first, then btrfs-progs'
146            // own file in case rigtop runs as root.
147            #[cfg(target_os = "linux")]
148            scrub_dirs: vec![
149                config.btrfs.scrub_dir.clone(),
150                linux::btrfs::BTRFS_PROGS_STATUS_DIR.into(),
151            ],
152        };
153        // The warm-up result itself is meaningless (no previous sample).
154        let _ = source.collect();
155        source
156    }
157
158    /// Why NVIDIA GPUs are unavailable, if NVML failed to initialize.
159    pub fn gpu_unavailable_reason(&self) -> Option<&str> {
160        self.nvml.init_error()
161    }
162
163    fn collect(&mut self) -> Snapshot {
164        let now = Instant::now();
165        let elapsed = self
166            .last_poll
167            .map(|prev| now.saturating_duration_since(prev).as_secs_f64());
168        self.last_poll = Some(now);
169
170        self.system.refresh();
171        let processes = self.system.processes(elapsed);
172        let gpus = self.nvml.collect();
173        let gpus_w = sum_present(gpus.iter().map(|g| g.power_w));
174
175        let mut snapshot = Snapshot {
176            timestamp_ms: SystemTime::now()
177                .duration_since(UNIX_EPOCH)
178                .map(|d| d.as_millis() as u64)
179                .unwrap_or(0),
180            host: self.system.host(),
181            cpu: self.system.cpu(),
182            memory: self.system.memory(),
183            networks: self.system.networks(elapsed),
184            filesystems: self.system.filesystems(),
185            process_count: processes.len(),
186            processes,
187            gpus,
188            smart: self.smart.read(),
189            power: PowerStats {
190                gpus_w,
191                ..Default::default()
192            },
193            ..Default::default()
194        };
195
196        #[cfg(target_os = "linux")]
197        self.collect_linux(&mut snapshot, now);
198        #[cfg(not(target_os = "linux"))]
199        self.collect_portable(&mut snapshot, elapsed);
200
201        let power = &mut snapshot.power;
202        power.total_w = sum_present([power.cpu_package_w, power.gpus_w]);
203        snapshot
204    }
205
206    /// Adds what `sysinfo` offers beyond the basics on non-Linux platforms:
207    /// per-volume I/O, temperatures and (on Windows) link speeds.
208    #[cfg(not(target_os = "linux"))]
209    fn collect_portable(&mut self, snapshot: &mut Snapshot, elapsed: Option<f64>) {
210        snapshot.disks = self.system.volume_io(elapsed);
211        let (chips, cpu_temperatures) = self.system.components();
212        snapshot.sensors = chips;
213        snapshot.cpu.temperatures = cpu_temperatures;
214        #[cfg(windows)]
215        crate::windows::annotate_links(&mut snapshot.networks);
216    }
217
218    /// Adds sensors, power, per-device I/O and RAID state from `/sys` and `/proc`.
219    #[cfg(target_os = "linux")]
220    fn collect_linux(&mut self, snapshot: &mut Snapshot, now: Instant) {
221        let chips = linux::hwmon::read_chips(&self.roots);
222
223        snapshot.cpu.temperatures = chips
224            .iter()
225            .filter(|c| linux::hwmon::is_cpu_chip(&c.chip))
226            .flat_map(|c| c.chip.temperatures.iter().cloned())
227            .collect();
228        snapshot.memory.cached_bytes = linux::meminfo::read_cached_bytes(&self.roots);
229        snapshot.power.cpu_package_w = self.rapl.sample(&self.roots, now);
230        // amdgpu power is treated as the integrated GPU (Ryzen iGPU).
231        // Discrete AMD GPUs are not distinguished yet.
232        snapshot.power.igpu_w = sum_present(
233            chips
234                .iter()
235                .filter(|c| c.chip.name == "amdgpu")
236                .flat_map(|c| c.power_w.iter().map(|(_, w)| Some(*w))),
237        );
238
239        let mut disks = self.diskstats.sample(&self.roots, now);
240        for disk in &mut disks {
241            disk.temperature_c = nvme_temperature(&chips, &disk.name);
242        }
243        snapshot.disks = disks;
244
245        let mounts = linux::mounts::read_mounts(&self.roots);
246        snapshot.raid.btrfs = linux::btrfs::read_filesystems(&self.roots, &mounts);
247        for fs in &mut snapshot.raid.btrfs {
248            fs.scrub = linux::btrfs::read_scrub(&self.scrub_dirs, &fs.fsid);
249        }
250        self.net_links
251            .annotate(&self.roots, &mut snapshot.networks, now);
252        snapshot.raid.md = linux::mdstat::read_arrays(&self.roots);
253
254        snapshot.sensors = chips.into_iter().map(|c| c.chip).collect();
255    }
256}
257
258impl Default for LocalSource {
259    fn default() -> Self {
260        Self::new()
261    }
262}
263
264impl DataSource for LocalSource {
265    fn poll(&mut self) -> Result<Snapshot, SourceError> {
266        Ok(self.collect())
267    }
268
269    fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError> {
270        send_signal(pid, signal).map_err(|source| SourceError::Signal { pid, source })
271    }
272}
273
274/// Sends a signal to a local process.
275#[cfg(unix)]
276fn send_signal(pid: u32, signal: ProcessSignal) -> std::io::Result<()> {
277    // pid 0 and negative values address process groups in kill(2); never
278    // let a bad pid turn into "signal everything".
279    let pid = libc::pid_t::try_from(pid)
280        .ok()
281        .filter(|p| *p > 0)
282        .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
283    let sig = match signal {
284        ProcessSignal::Terminate => libc::SIGTERM,
285        ProcessSignal::Kill => libc::SIGKILL,
286    };
287    // SAFETY: kill(2) has no memory-safety preconditions.
288    if unsafe { libc::kill(pid, sig) } == 0 {
289        Ok(())
290    } else {
291        Err(std::io::Error::last_os_error())
292    }
293}
294
295#[cfg(windows)]
296use crate::windows::send_signal;
297
298/// Sends a signal to a local process (not implemented on this platform yet).
299#[cfg(not(any(unix, windows)))]
300fn send_signal(_pid: u32, _signal: ProcessSignal) -> std::io::Result<()> {
301    Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
302}
303
304/// Sums the values that are present; `None` if none are.
305fn sum_present(values: impl IntoIterator<Item = Option<f32>>) -> Option<f32> {
306    values
307        .into_iter()
308        .flatten()
309        .fold(None, |acc, v| Some(acc.unwrap_or(0.0) + v))
310}
311
312/// Finds the composite temperature of the NVMe controller backing `disk`
313/// (hwmon chip key `nvme:nvme0` for disk `nvme0n1`).
314#[cfg(target_os = "linux")]
315fn nvme_temperature(chips: &[linux::hwmon::HwmonChip], disk: &str) -> Option<f32> {
316    chips.iter().find_map(|c| {
317        let controller = c.chip.key.strip_prefix("nvme:")?;
318        device_matches_disk(controller, disk).then_some(())?;
319        // The first channel is the "Composite" temperature the drive reports.
320        c.chip.temperatures.first().map(|t| t.celsius)
321    })
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[cfg(unix)]
329    #[test]
330    fn signal_rejects_group_pids_and_reports_missing_process() {
331        assert_eq!(
332            send_signal(0, ProcessSignal::Terminate).unwrap_err().kind(),
333            std::io::ErrorKind::InvalidInput
334        );
335        assert_eq!(
336            send_signal(u32::MAX, ProcessSignal::Kill)
337                .unwrap_err()
338                .kind(),
339            std::io::ErrorKind::InvalidInput
340        );
341        // A child that has been reaped no longer exists: ESRCH.
342        let mut child = std::process::Command::new("true").spawn().unwrap();
343        let pid = child.id();
344        child.wait().unwrap();
345        let err = send_signal(pid, ProcessSignal::Terminate).unwrap_err();
346        assert_eq!(err.raw_os_error(), Some(libc::ESRCH));
347    }
348
349    #[cfg(unix)]
350    #[test]
351    fn signal_terminates_a_child_process() {
352        let mut child = std::process::Command::new("sleep")
353            .arg("30")
354            .spawn()
355            .unwrap();
356        send_signal(child.id(), ProcessSignal::Kill).unwrap();
357        let status = child.wait().unwrap();
358        assert!(!status.success());
359    }
360
361    #[test]
362    fn sum_present_ignores_missing_values() {
363        assert_eq!(sum_present([None, None]), None);
364        assert_eq!(sum_present([Some(1.5), None, Some(2.0)]), Some(3.5));
365    }
366
367    #[cfg(target_os = "linux")]
368    #[test]
369    fn nvme_temperature_matches_controller_exactly() {
370        use crate::linux::hwmon::HwmonChip;
371        use crate::snapshot::{SensorChip, Temperature};
372
373        let chip = |key: &str, celsius: f32| HwmonChip {
374            chip: SensorChip {
375                key: key.to_owned(),
376                name: "nvme".to_owned(),
377                temperatures: vec![Temperature {
378                    label: "Composite".to_owned(),
379                    celsius,
380                    ..Default::default()
381                }],
382                fans: Vec::new(),
383            },
384            power_w: Vec::new(),
385        };
386        let chips = vec![chip("nvme:nvme1", 40.0), chip("nvme:nvme10", 50.0)];
387        assert_eq!(nvme_temperature(&chips, "nvme10n1"), Some(50.0));
388        assert_eq!(nvme_temperature(&chips, "nvme1n1"), Some(40.0));
389        assert_eq!(nvme_temperature(&chips, "sda"), None);
390    }
391}