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