1use 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
23pub const MIN_POLL_INTERVAL: Duration = sysinfo::MINIMUM_CPU_UPDATE_INTERVAL;
26
27#[derive(Debug, thiserror::Error)]
29pub enum SourceError {
30 #[error("I/O error: {0}")]
32 Io(#[from] std::io::Error),
33 #[error("source disconnected: {0}")]
35 Disconnected(String),
36 #[error("remote: {0}")]
38 Remote(String),
39 #[error("cannot signal process {pid}: {source}")]
41 Signal {
42 pid: u32,
44 source: std::io::Error,
46 },
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
51pub enum ProcessSignal {
52 Terminate,
54 Kill,
56}
57
58pub trait DataSource {
60 fn poll(&mut self) -> Result<Snapshot, SourceError>;
66
67 fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError>;
70
71 fn set_interval(&mut self, _interval: Duration) {}
75
76 fn set_process_limit(&mut self, _limit: Option<usize>) {}
79}
80
81impl<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
100pub 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 #[cfg(target_os = "linux")]
116 scrub_dirs: Vec<std::path::PathBuf>,
117 #[cfg(target_os = "linux")]
119 drm_gpus: linux::drm::DrmGpuReader,
120 #[cfg(windows)]
122 lhm: crate::lhm::LhmReader,
123}
124
125impl LocalSource {
126 pub fn new() -> Self {
128 Self::with_config(&Config::default())
129 }
130
131 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 #[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 let _ = source.collect();
165 source
166 }
167
168 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 #[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 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 #[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 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 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 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#[cfg(unix)]
312fn send_signal(pid: u32, signal: ProcessSignal) -> std::io::Result<()> {
313 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 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#[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
340fn 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#[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 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 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}