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    /// Temperatures, fans and CPU power from LibreHardwareMonitor.
118    #[cfg(windows)]
119    lhm: crate::lhm::LhmReader,
120}
121
122impl LocalSource {
123    /// Creates a source with the default configuration. See [`LocalSource::with_config`].
124    pub fn new() -> Self {
125        Self::with_config(&Config::default())
126    }
127
128    /// Creates a source and takes a warm-up sample, so that the first
129    /// [`DataSource::poll`] (after at least [`MIN_POLL_INTERVAL`]) already
130    /// has rates.
131    ///
132    /// Only collection-related settings (the SMART directory) are used here;
133    /// display settings such as sensor labels are applied by front-ends.
134    pub fn with_config(config: &Config) -> Self {
135        let mut source = Self {
136            system: SystemCollector::new(),
137            nvml: NvmlCollector::new(),
138            smart: SmartReader::new(&config.smart.dir),
139            last_poll: None,
140            #[cfg(target_os = "linux")]
141            roots: SysRoots::default(),
142            #[cfg(target_os = "linux")]
143            rapl: RaplMeter::new(),
144            #[cfg(target_os = "linux")]
145            diskstats: DiskStatsMeter::new(),
146            #[cfg(target_os = "linux")]
147            net_links: NetLinkReader::new(),
148            // The copy made by the root collector first, then btrfs-progs'
149            // own file in case rigtop runs as root.
150            #[cfg(windows)]
151            lhm: crate::lhm::LhmReader::new(&config.lhm.url),
152            #[cfg(target_os = "linux")]
153            scrub_dirs: vec![
154                config.btrfs.scrub_dir.clone(),
155                linux::btrfs::BTRFS_PROGS_STATUS_DIR.into(),
156            ],
157        };
158        // The warm-up result itself is meaningless (no previous sample).
159        let _ = source.collect();
160        source
161    }
162
163    /// Why NVIDIA GPUs are unavailable, if NVML failed to initialize.
164    pub fn gpu_unavailable_reason(&self) -> Option<&str> {
165        self.nvml.init_error()
166    }
167
168    fn collect(&mut self) -> Snapshot {
169        let now = Instant::now();
170        let elapsed = self
171            .last_poll
172            .map(|prev| now.saturating_duration_since(prev).as_secs_f64());
173        self.last_poll = Some(now);
174
175        self.system.refresh();
176        let processes = self.system.processes(elapsed);
177        let gpus = self.nvml.collect();
178        let gpus_w = sum_present(gpus.iter().map(|g| g.power_w));
179
180        let mut snapshot = Snapshot {
181            timestamp_ms: SystemTime::now()
182                .duration_since(UNIX_EPOCH)
183                .map(|d| d.as_millis() as u64)
184                .unwrap_or(0),
185            host: self.system.host(),
186            cpu: self.system.cpu(),
187            memory: self.system.memory(),
188            networks: self.system.networks(elapsed),
189            filesystems: self.system.filesystems(),
190            process_count: processes.len(),
191            processes,
192            gpus,
193            smart: self.smart.read(),
194            power: PowerStats {
195                gpus_w,
196                ..Default::default()
197            },
198            ..Default::default()
199        };
200
201        #[cfg(target_os = "linux")]
202        self.collect_linux(&mut snapshot, now);
203        #[cfg(not(target_os = "linux"))]
204        self.collect_portable(&mut snapshot, elapsed);
205
206        let power = &mut snapshot.power;
207        power.total_w = sum_present([power.cpu_package_w, power.gpus_w]);
208        snapshot
209    }
210
211    /// Adds what `sysinfo` offers beyond the basics on non-Linux platforms:
212    /// per-volume I/O, temperatures and (on Windows) link speeds.
213    #[cfg(not(target_os = "linux"))]
214    fn collect_portable(&mut self, snapshot: &mut Snapshot, elapsed: Option<f64>) {
215        snapshot.disks = self.system.volume_io(elapsed);
216        let (chips, cpu_temperatures) = self.system.components();
217        snapshot.sensors = chips;
218        snapshot.cpu.temperatures = cpu_temperatures;
219        #[cfg(windows)]
220        {
221            crate::windows::annotate_links(&mut snapshot.networks);
222            // LibreHardwareMonitor, when running, knows far more than the
223            // ACPI thermal zones sysinfo can see.
224            match self.lhm.read(Instant::now()) {
225                Some(lhm) => {
226                    if !lhm.chips.is_empty() {
227                        snapshot.sensors = lhm.chips;
228                    }
229                    if !lhm.cpu_temperatures.is_empty() {
230                        snapshot.cpu.temperatures = lhm.cpu_temperatures;
231                    }
232                    snapshot.power.cpu_package_w = lhm.cpu_package_w;
233                }
234                None => snapshot.lhm_error = self.lhm.problem().map(str::to_owned),
235            }
236        }
237    }
238
239    /// Adds sensors, power, per-device I/O and RAID state from `/sys` and `/proc`.
240    #[cfg(target_os = "linux")]
241    fn collect_linux(&mut self, snapshot: &mut Snapshot, now: Instant) {
242        let chips = linux::hwmon::read_chips(&self.roots);
243
244        snapshot.cpu.temperatures = chips
245            .iter()
246            .filter(|c| linux::hwmon::is_cpu_chip(&c.chip))
247            .flat_map(|c| c.chip.temperatures.iter().cloned())
248            .collect();
249        snapshot.memory.cached_bytes = linux::meminfo::read_cached_bytes(&self.roots);
250        snapshot.power.cpu_package_w = self.rapl.sample(&self.roots, now);
251        // amdgpu power is treated as the integrated GPU (Ryzen iGPU).
252        // Discrete AMD GPUs are not distinguished yet.
253        snapshot.power.igpu_w = sum_present(
254            chips
255                .iter()
256                .filter(|c| c.chip.name == "amdgpu")
257                .flat_map(|c| c.power_w.iter().map(|(_, w)| Some(*w))),
258        );
259
260        let mut disks = self.diskstats.sample(&self.roots, now);
261        for disk in &mut disks {
262            disk.temperature_c = nvme_temperature(&chips, &disk.name);
263        }
264        snapshot.disks = disks;
265
266        let mounts = linux::mounts::read_mounts(&self.roots);
267        snapshot.raid.btrfs = linux::btrfs::read_filesystems(&self.roots, &mounts);
268        for fs in &mut snapshot.raid.btrfs {
269            fs.scrub = linux::btrfs::read_scrub(&self.scrub_dirs, &fs.fsid);
270        }
271        self.net_links
272            .annotate(&self.roots, &mut snapshot.networks, now);
273        snapshot.raid.md = linux::mdstat::read_arrays(&self.roots);
274
275        snapshot.sensors = chips.into_iter().map(|c| c.chip).collect();
276    }
277}
278
279impl Default for LocalSource {
280    fn default() -> Self {
281        Self::new()
282    }
283}
284
285impl DataSource for LocalSource {
286    fn poll(&mut self) -> Result<Snapshot, SourceError> {
287        Ok(self.collect())
288    }
289
290    fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError> {
291        send_signal(pid, signal).map_err(|source| SourceError::Signal { pid, source })
292    }
293}
294
295/// Sends a signal to a local process.
296#[cfg(unix)]
297fn send_signal(pid: u32, signal: ProcessSignal) -> std::io::Result<()> {
298    // pid 0 and negative values address process groups in kill(2); never
299    // let a bad pid turn into "signal everything".
300    let pid = libc::pid_t::try_from(pid)
301        .ok()
302        .filter(|p| *p > 0)
303        .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
304    let sig = match signal {
305        ProcessSignal::Terminate => libc::SIGTERM,
306        ProcessSignal::Kill => libc::SIGKILL,
307    };
308    // SAFETY: kill(2) has no memory-safety preconditions.
309    if unsafe { libc::kill(pid, sig) } == 0 {
310        Ok(())
311    } else {
312        Err(std::io::Error::last_os_error())
313    }
314}
315
316#[cfg(windows)]
317use crate::windows::send_signal;
318
319/// Sends a signal to a local process (not implemented on this platform yet).
320#[cfg(not(any(unix, windows)))]
321fn send_signal(_pid: u32, _signal: ProcessSignal) -> std::io::Result<()> {
322    Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
323}
324
325/// Sums the values that are present; `None` if none are.
326fn sum_present(values: impl IntoIterator<Item = Option<f32>>) -> Option<f32> {
327    values
328        .into_iter()
329        .flatten()
330        .fold(None, |acc, v| Some(acc.unwrap_or(0.0) + v))
331}
332
333/// Finds the composite temperature of the NVMe controller backing `disk`
334/// (hwmon chip key `nvme:nvme0` for disk `nvme0n1`).
335#[cfg(target_os = "linux")]
336fn nvme_temperature(chips: &[linux::hwmon::HwmonChip], disk: &str) -> Option<f32> {
337    chips.iter().find_map(|c| {
338        let controller = c.chip.key.strip_prefix("nvme:")?;
339        device_matches_disk(controller, disk).then_some(())?;
340        // The first channel is the "Composite" temperature the drive reports.
341        c.chip.temperatures.first().map(|t| t.celsius)
342    })
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    #[cfg(unix)]
350    #[test]
351    fn signal_rejects_group_pids_and_reports_missing_process() {
352        assert_eq!(
353            send_signal(0, ProcessSignal::Terminate).unwrap_err().kind(),
354            std::io::ErrorKind::InvalidInput
355        );
356        assert_eq!(
357            send_signal(u32::MAX, ProcessSignal::Kill)
358                .unwrap_err()
359                .kind(),
360            std::io::ErrorKind::InvalidInput
361        );
362        // A child that has been reaped no longer exists: ESRCH.
363        let mut child = std::process::Command::new("true").spawn().unwrap();
364        let pid = child.id();
365        child.wait().unwrap();
366        let err = send_signal(pid, ProcessSignal::Terminate).unwrap_err();
367        assert_eq!(err.raw_os_error(), Some(libc::ESRCH));
368    }
369
370    #[cfg(unix)]
371    #[test]
372    fn signal_terminates_a_child_process() {
373        let mut child = std::process::Command::new("sleep")
374            .arg("30")
375            .spawn()
376            .unwrap();
377        send_signal(child.id(), ProcessSignal::Kill).unwrap();
378        let status = child.wait().unwrap();
379        assert!(!status.success());
380    }
381
382    #[test]
383    fn sum_present_ignores_missing_values() {
384        assert_eq!(sum_present([None, None]), None);
385        assert_eq!(sum_present([Some(1.5), None, Some(2.0)]), Some(3.5));
386    }
387
388    #[cfg(target_os = "linux")]
389    #[test]
390    fn nvme_temperature_matches_controller_exactly() {
391        use crate::linux::hwmon::HwmonChip;
392        use crate::snapshot::{SensorChip, Temperature};
393
394        let chip = |key: &str, celsius: f32| HwmonChip {
395            chip: SensorChip {
396                key: key.to_owned(),
397                name: "nvme".to_owned(),
398                temperatures: vec![Temperature {
399                    label: "Composite".to_owned(),
400                    celsius,
401                    ..Default::default()
402                }],
403                fans: Vec::new(),
404            },
405            power_w: Vec::new(),
406        };
407        let chips = vec![chip("nvme:nvme1", 40.0), chip("nvme:nvme10", 50.0)];
408        assert_eq!(nvme_temperature(&chips, "nvme10n1"), Some(50.0));
409        assert_eq!(nvme_temperature(&chips, "nvme1n1"), Some(40.0));
410        assert_eq!(nvme_temperature(&chips, "sda"), None);
411    }
412}