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 if !lhm.smart.is_empty() {
239 snapshot.smart = lhm.smart;
240 }
241 }
242 None => snapshot.lhm_error = self.lhm.problem().map(str::to_owned),
243 }
244 }
245 }
246
247 #[cfg(target_os = "linux")]
249 fn collect_linux(&mut self, snapshot: &mut Snapshot, now: Instant) {
250 let chips = linux::hwmon::read_chips(&self.roots);
251
252 snapshot.cpu.temperatures = chips
253 .iter()
254 .filter(|c| linux::hwmon::is_cpu_chip(&c.chip))
255 .flat_map(|c| c.chip.temperatures.iter().cloned())
256 .collect();
257 snapshot.memory.cached_bytes = linux::meminfo::read_cached_bytes(&self.roots);
258 snapshot.power.cpu_package_w = self.rapl.sample(&self.roots, now);
259 snapshot.power.igpu_w = sum_present(
262 chips
263 .iter()
264 .filter(|c| c.is_apu)
265 .flat_map(|c| c.power_w.iter().map(|(_, w)| Some(*w))),
266 );
267 snapshot.power.battery = linux::battery::read_battery(&self.roots);
268
269 let first = snapshot.gpus.len() as u32;
271 snapshot.gpus.extend(self.drm_gpus.read(&self.roots, first));
272 snapshot.power.gpus_w = sum_present(snapshot.gpus.iter().map(|g| g.power_w));
273
274 let mut disks = self.diskstats.sample(&self.roots, now);
275 for disk in &mut disks {
276 disk.temperature_c = nvme_temperature(&chips, &disk.name);
277 }
278 snapshot.disks = disks;
279
280 let mounts = linux::mounts::read_mounts(&self.roots);
281 snapshot.raid.btrfs = linux::btrfs::read_filesystems(&self.roots, &mounts);
282 for fs in &mut snapshot.raid.btrfs {
283 fs.scrub = linux::btrfs::read_scrub(&self.scrub_dirs, &fs.fsid);
284 }
285 self.net_links
286 .annotate(&self.roots, &mut snapshot.networks, now);
287 snapshot.raid.md = linux::mdstat::read_arrays(&self.roots);
288 for process in &mut snapshot.processes {
290 process.threads = linux::procstat::thread_count(&self.roots, process.pid);
291 }
292
293 snapshot.sensors = chips.into_iter().map(|c| c.chip).collect();
294 }
295}
296
297impl Default for LocalSource {
298 fn default() -> Self {
299 Self::new()
300 }
301}
302
303impl DataSource for LocalSource {
304 fn poll(&mut self) -> Result<Snapshot, SourceError> {
305 Ok(self.collect())
306 }
307
308 fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError> {
309 send_signal(pid, signal).map_err(|source| SourceError::Signal { pid, source })
310 }
311
312 fn set_process_limit(&mut self, limit: Option<usize>) {
315 self.nvml.set_process_utilization(limit.is_none());
316 }
317}
318
319#[cfg(unix)]
321fn send_signal(pid: u32, signal: ProcessSignal) -> std::io::Result<()> {
322 let pid = libc::pid_t::try_from(pid)
325 .ok()
326 .filter(|p| *p > 0)
327 .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
328 let sig = match signal {
329 ProcessSignal::Terminate => libc::SIGTERM,
330 ProcessSignal::Kill => libc::SIGKILL,
331 };
332 if unsafe { libc::kill(pid, sig) } == 0 {
334 Ok(())
335 } else {
336 Err(std::io::Error::last_os_error())
337 }
338}
339
340#[cfg(windows)]
341use crate::windows::send_signal;
342
343#[cfg(not(any(unix, windows)))]
345fn send_signal(_pid: u32, _signal: ProcessSignal) -> std::io::Result<()> {
346 Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
347}
348
349fn sum_present(values: impl IntoIterator<Item = Option<f32>>) -> Option<f32> {
351 values
352 .into_iter()
353 .flatten()
354 .fold(None, |acc, v| Some(acc.unwrap_or(0.0) + v))
355}
356
357#[cfg(target_os = "linux")]
360fn nvme_temperature(chips: &[linux::hwmon::HwmonChip], disk: &str) -> Option<f32> {
361 chips.iter().find_map(|c| {
362 let controller = c.chip.key.strip_prefix("nvme:")?;
363 device_matches_disk(controller, disk).then_some(())?;
364 c.chip.temperatures.first().map(|t| t.celsius)
366 })
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372
373 #[cfg(unix)]
374 #[test]
375 fn signal_rejects_group_pids_and_reports_missing_process() {
376 assert_eq!(
377 send_signal(0, ProcessSignal::Terminate).unwrap_err().kind(),
378 std::io::ErrorKind::InvalidInput
379 );
380 assert_eq!(
381 send_signal(u32::MAX, ProcessSignal::Kill)
382 .unwrap_err()
383 .kind(),
384 std::io::ErrorKind::InvalidInput
385 );
386 let mut child = std::process::Command::new("true").spawn().unwrap();
388 let pid = child.id();
389 child.wait().unwrap();
390 let err = send_signal(pid, ProcessSignal::Terminate).unwrap_err();
391 assert_eq!(err.raw_os_error(), Some(libc::ESRCH));
392 }
393
394 #[cfg(unix)]
395 #[test]
396 fn signal_terminates_a_child_process() {
397 let mut child = std::process::Command::new("sleep")
398 .arg("30")
399 .spawn()
400 .unwrap();
401 send_signal(child.id(), ProcessSignal::Kill).unwrap();
402 let status = child.wait().unwrap();
403 assert!(!status.success());
404 }
405
406 #[test]
407 fn sum_present_ignores_missing_values() {
408 assert_eq!(sum_present([None, None]), None);
409 assert_eq!(sum_present([Some(1.5), None, Some(2.0)]), Some(3.5));
410 }
411
412 #[cfg(target_os = "linux")]
413 #[test]
414 fn nvme_temperature_matches_controller_exactly() {
415 use crate::linux::hwmon::HwmonChip;
416 use crate::snapshot::{SensorChip, Temperature};
417
418 let chip = |key: &str, celsius: f32| HwmonChip {
419 chip: SensorChip {
420 key: key.to_owned(),
421 name: "nvme".to_owned(),
422 temperatures: vec![Temperature {
423 label: "Composite".to_owned(),
424 celsius,
425 ..Default::default()
426 }],
427 fans: Vec::new(),
428 },
429 power_w: Vec::new(),
430 is_apu: false,
431 };
432 let chips = vec![chip("nvme:nvme1", 40.0), chip("nvme:nvme10", 50.0)];
433 assert_eq!(nvme_temperature(&chips, "nvme10n1"), Some(50.0));
434 assert_eq!(nvme_temperature(&chips, "nvme1n1"), Some(40.0));
435 assert_eq!(nvme_temperature(&chips, "sda"), None);
436 }
437}