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(windows)]
119 lhm: crate::lhm::LhmReader,
120}
121
122impl LocalSource {
123 pub fn new() -> Self {
125 Self::with_config(&Config::default())
126 }
127
128 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 #[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 let _ = source.collect();
160 source
161 }
162
163 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_or_soc_w().1, power.gpus_w]);
208 snapshot
209 }
210
211 #[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 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 #[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 snapshot.power.igpu_w = sum_present(
254 chips
255 .iter()
256 .filter(|c| c.is_apu)
257 .flat_map(|c| c.power_w.iter().map(|(_, w)| Some(*w))),
258 );
259 snapshot.power.battery = linux::battery::read_battery(&self.roots);
260
261 let mut disks = self.diskstats.sample(&self.roots, now);
262 for disk in &mut disks {
263 disk.temperature_c = nvme_temperature(&chips, &disk.name);
264 }
265 snapshot.disks = disks;
266
267 let mounts = linux::mounts::read_mounts(&self.roots);
268 snapshot.raid.btrfs = linux::btrfs::read_filesystems(&self.roots, &mounts);
269 for fs in &mut snapshot.raid.btrfs {
270 fs.scrub = linux::btrfs::read_scrub(&self.scrub_dirs, &fs.fsid);
271 }
272 self.net_links
273 .annotate(&self.roots, &mut snapshot.networks, now);
274 snapshot.raid.md = linux::mdstat::read_arrays(&self.roots);
275 for process in &mut snapshot.processes {
277 process.threads = linux::procstat::thread_count(&self.roots, process.pid);
278 }
279
280 snapshot.sensors = chips.into_iter().map(|c| c.chip).collect();
281 }
282}
283
284impl Default for LocalSource {
285 fn default() -> Self {
286 Self::new()
287 }
288}
289
290impl DataSource for LocalSource {
291 fn poll(&mut self) -> Result<Snapshot, SourceError> {
292 Ok(self.collect())
293 }
294
295 fn signal_process(&mut self, pid: u32, signal: ProcessSignal) -> Result<(), SourceError> {
296 send_signal(pid, signal).map_err(|source| SourceError::Signal { pid, source })
297 }
298}
299
300#[cfg(unix)]
302fn send_signal(pid: u32, signal: ProcessSignal) -> std::io::Result<()> {
303 let pid = libc::pid_t::try_from(pid)
306 .ok()
307 .filter(|p| *p > 0)
308 .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
309 let sig = match signal {
310 ProcessSignal::Terminate => libc::SIGTERM,
311 ProcessSignal::Kill => libc::SIGKILL,
312 };
313 if unsafe { libc::kill(pid, sig) } == 0 {
315 Ok(())
316 } else {
317 Err(std::io::Error::last_os_error())
318 }
319}
320
321#[cfg(windows)]
322use crate::windows::send_signal;
323
324#[cfg(not(any(unix, windows)))]
326fn send_signal(_pid: u32, _signal: ProcessSignal) -> std::io::Result<()> {
327 Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
328}
329
330fn sum_present(values: impl IntoIterator<Item = Option<f32>>) -> Option<f32> {
332 values
333 .into_iter()
334 .flatten()
335 .fold(None, |acc, v| Some(acc.unwrap_or(0.0) + v))
336}
337
338#[cfg(target_os = "linux")]
341fn nvme_temperature(chips: &[linux::hwmon::HwmonChip], disk: &str) -> Option<f32> {
342 chips.iter().find_map(|c| {
343 let controller = c.chip.key.strip_prefix("nvme:")?;
344 device_matches_disk(controller, disk).then_some(())?;
345 c.chip.temperatures.first().map(|t| t.celsius)
347 })
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353
354 #[cfg(unix)]
355 #[test]
356 fn signal_rejects_group_pids_and_reports_missing_process() {
357 assert_eq!(
358 send_signal(0, ProcessSignal::Terminate).unwrap_err().kind(),
359 std::io::ErrorKind::InvalidInput
360 );
361 assert_eq!(
362 send_signal(u32::MAX, ProcessSignal::Kill)
363 .unwrap_err()
364 .kind(),
365 std::io::ErrorKind::InvalidInput
366 );
367 let mut child = std::process::Command::new("true").spawn().unwrap();
369 let pid = child.id();
370 child.wait().unwrap();
371 let err = send_signal(pid, ProcessSignal::Terminate).unwrap_err();
372 assert_eq!(err.raw_os_error(), Some(libc::ESRCH));
373 }
374
375 #[cfg(unix)]
376 #[test]
377 fn signal_terminates_a_child_process() {
378 let mut child = std::process::Command::new("sleep")
379 .arg("30")
380 .spawn()
381 .unwrap();
382 send_signal(child.id(), ProcessSignal::Kill).unwrap();
383 let status = child.wait().unwrap();
384 assert!(!status.success());
385 }
386
387 #[test]
388 fn sum_present_ignores_missing_values() {
389 assert_eq!(sum_present([None, None]), None);
390 assert_eq!(sum_present([Some(1.5), None, Some(2.0)]), Some(3.5));
391 }
392
393 #[cfg(target_os = "linux")]
394 #[test]
395 fn nvme_temperature_matches_controller_exactly() {
396 use crate::linux::hwmon::HwmonChip;
397 use crate::snapshot::{SensorChip, Temperature};
398
399 let chip = |key: &str, celsius: f32| HwmonChip {
400 chip: SensorChip {
401 key: key.to_owned(),
402 name: "nvme".to_owned(),
403 temperatures: vec![Temperature {
404 label: "Composite".to_owned(),
405 celsius,
406 ..Default::default()
407 }],
408 fans: Vec::new(),
409 },
410 power_w: Vec::new(),
411 is_apu: false,
412 };
413 let chips = vec![chip("nvme:nvme1", 40.0), chip("nvme:nvme10", 50.0)];
414 assert_eq!(nvme_temperature(&chips, "nvme10n1"), Some(50.0));
415 assert_eq!(nvme_temperature(&chips, "nvme1n1"), Some(40.0));
416 assert_eq!(nvme_temperature(&chips, "sda"), None);
417 }
418}