Skip to main content

rigtop_core/
snapshot.rs

1//! Serializable snapshot of everything rigtop displays.
2//!
3//! A [`Snapshot`] is the single unit of data exchanged between a data source
4//! (local collectors, or a remote `rigtop --agent` over SSH) and a front-end
5//! (TUI or GUI). Every type here derives `Serialize`/`Deserialize` so that the
6//! same structure can be streamed over the wire unchanged.
7//!
8//! Conventions:
9//! - Sizes are in bytes, rates in bytes per second.
10//! - Temperatures are in degrees Celsius, power in watts, fan speed in RPM.
11//! - Percentages are in the range `0.0..=100.0` (per-core values are not summed).
12//! - Values that a platform or device cannot provide are `None` (or an empty
13//!   list) rather than zero, so that front-ends can hide them.
14//! - Every struct is `#[serde(default)]`: fields missing from the input take
15//!   their default, so a client can read snapshots from an older or newer
16//!   `rigtop --agent` as long as fields are only added.
17
18use serde::{Deserialize, Serialize};
19
20/// One full measurement of a host.
21#[derive(Debug, Clone, Default, Serialize, Deserialize)]
22#[serde(default)]
23pub struct Snapshot {
24    /// Wall-clock time of the measurement, in milliseconds since the Unix epoch.
25    pub timestamp_ms: u64,
26    /// Static-ish information about the host.
27    pub host: HostInfo,
28    /// CPU load, frequency and temperature.
29    pub cpu: CpuStats,
30    /// Physical memory and swap.
31    pub memory: MemoryStats,
32    /// Discrete and integrated GPUs that could be queried.
33    pub gpus: Vec<GpuStats>,
34    /// Raw hardware sensor chips (temperatures and fans), grouped by chip.
35    pub sensors: Vec<SensorChip>,
36    /// Power draw summary.
37    pub power: PowerStats,
38    /// I/O activity per physical block device.
39    pub disks: Vec<DiskIo>,
40    /// Capacity of mounted filesystems.
41    pub filesystems: Vec<FilesystemUsage>,
42    /// Software RAID state (btrfs and mdadm).
43    pub raid: RaidStats,
44    /// SMART health per drive, from files written by a privileged timer.
45    pub smart: Vec<SmartDevice>,
46    /// Network interface traffic.
47    pub networks: Vec<NetworkStats>,
48    /// Process list. May be truncated by the source (see [`Snapshot::truncate_processes`]).
49    pub processes: Vec<ProcessInfo>,
50    /// Total number of processes on the host, even if `processes` was truncated.
51    pub process_count: usize,
52    /// Windows: why LibreHardwareMonitor, the source of temperatures, fans
53    /// and CPU power, could not be read. `None` when it was read, when it is
54    /// disabled in the configuration, and on other platforms.
55    pub lhm_error: Option<String>,
56}
57
58impl Snapshot {
59    /// Keeps only the `limit` processes with the highest CPU usage.
60    ///
61    /// Used to reduce the payload when a host is shown in an overview rather
62    /// than in detail. Kernel threads are dropped first: the overview does not
63    /// show them, and busy `kworker`s would otherwise take places in the top
64    /// `limit` and leave the list short. `process_count` keeps the original
65    /// total.
66    pub fn truncate_processes(&mut self, limit: usize) {
67        self.processes.retain(|p| !p.kernel_thread);
68        if self.processes.len() <= limit {
69            return;
70        }
71        // Partial sort is enough: only the top `limit` entries matter.
72        self.processes
73            .select_nth_unstable_by(limit, |a, b| b.cpu_percent.total_cmp(&a.cpu_percent));
74        self.processes.truncate(limit);
75        self.processes
76            .sort_unstable_by(|a, b| b.cpu_percent.total_cmp(&a.cpu_percent));
77    }
78}
79
80/// Host identification and uptime.
81#[derive(Debug, Clone, Default, Serialize, Deserialize)]
82#[serde(default)]
83pub struct HostInfo {
84    /// Host name as reported by the OS.
85    pub hostname: String,
86    /// Human readable OS name and version (e.g. "Linux 26.04 Ubuntu").
87    pub os: String,
88    /// Kernel version string.
89    pub kernel: String,
90    /// Seconds since boot.
91    pub uptime_secs: u64,
92}
93
94/// CPU-wide and per-core statistics.
95#[derive(Debug, Clone, Default, Serialize, Deserialize)]
96#[serde(default)]
97pub struct CpuStats {
98    /// Brand string of the first CPU (e.g. "AMD Ryzen 9 9950X3D 16-Core Processor").
99    pub model: String,
100    /// Usage across all logical cores.
101    pub total_percent: f32,
102    /// Usage of each logical core, in OS order.
103    pub per_core_percent: Vec<f32>,
104    /// Current frequency of each logical core in MHz.
105    pub per_core_mhz: Vec<u64>,
106    /// 1, 5 and 15 minute load averages; `None` on platforms without them
107    /// (Windows).
108    pub load_average: Option<[f64; 3]>,
109    /// CPU temperature readings, e.g. `Tctl`, `Tccd1`, `Tccd2` on AMD or
110    /// `Package id 0`, `Core 0`.. on Intel.
111    pub temperatures: Vec<Temperature>,
112}
113
114/// Physical memory and swap usage.
115#[derive(Debug, Clone, Default, Serialize, Deserialize)]
116#[serde(default)]
117pub struct MemoryStats {
118    /// Installed (visible) memory.
119    pub total_bytes: u64,
120    /// Memory in use by processes (total minus available).
121    pub used_bytes: u64,
122    /// Memory that can be allocated without swapping.
123    pub available_bytes: u64,
124    /// Completely unused memory.
125    pub free_bytes: u64,
126    /// Page cache and reclaimable slab, where the platform reports it.
127    pub cached_bytes: Option<u64>,
128    /// Total swap space.
129    pub swap_total_bytes: u64,
130    /// Swap space in use.
131    pub swap_used_bytes: u64,
132}
133
134/// A single GPU.
135#[derive(Debug, Clone, Default, Serialize, Deserialize)]
136#[serde(default)]
137pub struct GpuStats {
138    /// Position in the GPU list: NVIDIA GPUs first (their NVML index),
139    /// then AMD and Intel ones.
140    pub index: u32,
141    /// Vendor name ("NVIDIA", "AMD", ...).
142    pub vendor: String,
143    /// Marketing name of the device.
144    pub name: String,
145    /// Integrated graphics (an APU or Intel iGPU), whose power is part of
146    /// the CPU package and not reported here.
147    pub integrated: bool,
148    /// Core utilization (unknown for Intel without privileges).
149    pub utilization_percent: Option<f32>,
150    /// Memory controller utilization.
151    pub memory_utilization_percent: Option<f32>,
152    /// VRAM in use.
153    pub memory_used_bytes: Option<u64>,
154    /// Total VRAM.
155    pub memory_total_bytes: Option<u64>,
156    /// Core temperature.
157    pub temperature_c: Option<f32>,
158    /// Current board power draw.
159    pub power_w: Option<f32>,
160    /// Enforced power limit.
161    pub power_limit_w: Option<f32>,
162    /// Fan speed as a percentage of the maximum (first fan).
163    pub fan_percent: Option<f32>,
164    /// Graphics clock in MHz.
165    pub clock_mhz: Option<u32>,
166    /// Processes currently using this GPU.
167    pub processes: Vec<GpuProcess>,
168}
169
170/// GPU usage attributed to one process.
171#[derive(Debug, Clone, Default, Serialize, Deserialize)]
172#[serde(default)]
173pub struct GpuProcess {
174    /// OS process id.
175    pub pid: u32,
176    /// VRAM used by the process, if the driver reports it.
177    pub memory_bytes: Option<u64>,
178    /// Streaming multiprocessor (core) utilization by the process.
179    pub sm_percent: Option<f32>,
180}
181
182/// A hardware monitoring chip (a Linux hwmon device) and its readings.
183#[derive(Debug, Clone, Default, Serialize, Deserialize)]
184#[serde(default)]
185pub struct SensorChip {
186    /// Stable identifier, `"<driver name>:<device name>"`
187    /// (e.g. `"nct6686:nct6683.2592"`, `"nvme:nvme0"`).
188    ///
189    /// Unlike `hwmonN`, this survives reboots, so it is used as the key for
190    /// user-defined labels.
191    pub key: String,
192    /// Driver-provided chip name (e.g. `"k10temp"`, `"nvme"`, `"spd5118"`).
193    pub name: String,
194    /// Temperature channels.
195    pub temperatures: Vec<Temperature>,
196    /// Fan channels.
197    pub fans: Vec<Fan>,
198}
199
200/// One temperature channel.
201#[derive(Debug, Clone, Default, Serialize, Deserialize)]
202#[serde(default)]
203pub struct Temperature {
204    /// Stable key `"<chip key>/temp<N>"` used to look up user-defined names.
205    /// Empty for readings that do not come from a hwmon chip.
206    pub key: String,
207    /// Driver label (e.g. `"Tccd1"`), or a generic `"temp<N>"` when none exists.
208    pub label: String,
209    /// Current reading.
210    pub celsius: f32,
211    /// High threshold, if exposed.
212    pub max_celsius: Option<f32>,
213    /// Critical threshold, if exposed.
214    pub critical_celsius: Option<f32>,
215}
216
217/// One fan channel.
218#[derive(Debug, Clone, Default, Serialize, Deserialize)]
219#[serde(default)]
220pub struct Fan {
221    /// Stable key `"<chip key>/fan<N>"` used to look up user-defined names.
222    pub key: String,
223    /// Driver label, or a generic `"fan<N>"` when none exists.
224    pub label: String,
225    /// Current speed (0 when stopped or not connected).
226    pub rpm: u32,
227}
228
229/// Power draw summary.
230///
231/// There is no portable way to measure whole-system power without external
232/// hardware, so the total is the sum of the CPU package and discrete GPUs,
233/// which dominate consumption on typical workstations.
234#[derive(Debug, Clone, Default, Serialize, Deserialize)]
235#[serde(default)]
236pub struct PowerStats {
237    /// CPU package power (RAPL on Linux). `None` before the second sample or
238    /// when RAPL is unavailable.
239    pub cpu_package_w: Option<f32>,
240    /// Sum of power reported by discrete GPUs.
241    pub gpus_w: Option<f32>,
242    /// Power an AMD APU's graphics driver reports (amdgpu `PPT`). Per the
243    /// kernel documentation it covers the whole SoC, CPU cores included, so
244    /// it overlaps the CPU package and only stands in for it when RAPL cannot
245    /// be read (see [`PowerStats::cpu_or_soc_w`]).
246    pub igpu_w: Option<f32>,
247    /// `cpu_package_w` (or `igpu_w` without it) `+ gpus_w`, counting only the
248    /// parts that are available.
249    pub total_w: Option<f32>,
250    /// Laptop battery, if there is one.
251    pub battery: Option<BatteryStats>,
252}
253
254/// Below this, an APU reading is not whole-SoC power: desktop Ryzen CPUs
255/// with a small iGPU report only a few milliwatts there, while a laptop
256/// APU's SoC never idles under a watt.
257const MIN_SOC_W: f32 = 1.0;
258
259impl PowerStats {
260    /// The CPU figure to show: `("CPU", RAPL)`, else `("SoC", APU PPT)`.
261    pub fn cpu_or_soc_w(&self) -> (&'static str, Option<f32>) {
262        match (self.cpu_package_w, self.igpu_w) {
263            (Some(w), _) => ("CPU", Some(w)),
264            (None, Some(w)) if w >= MIN_SOC_W => ("SoC", Some(w)),
265            _ => ("CPU", None),
266        }
267    }
268}
269
270/// Charge and power of the system's batteries (summed when there are
271/// several), from `/sys/class/power_supply` on Linux.
272#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
273#[serde(default)]
274pub struct BatteryStats {
275    /// Charge in percent.
276    pub percent: Option<f32>,
277    /// Kernel status: `Charging`, `Discharging`, `Full`, `Not charging`...
278    pub status: String,
279    /// Charge or discharge power (not signed; see `status`).
280    pub power_w: Option<f32>,
281}
282
283impl BatteryStats {
284    /// Short form for status lines: `72% -12W` while discharging, `+20W`
285    /// while charging.
286    pub fn summary(&self) -> String {
287        let percent = self
288            .percent
289            .map_or("--%".to_owned(), |p| format!("{p:.0}%"));
290        let sign = match self.status.as_str() {
291            "Discharging" => "-",
292            "Charging" => "+",
293            _ => return percent,
294        };
295        match self.power_w {
296            Some(w) if w >= 0.5 => format!("{percent} {sign}{w:.0}W"),
297            _ => percent,
298        }
299    }
300}
301
302/// I/O activity of a block device.
303#[derive(Debug, Clone, Default, Serialize, Deserialize)]
304#[serde(default)]
305pub struct DiskIo {
306    /// Kernel device name (e.g. `"nvme0n1"`, `"sda"`).
307    pub name: String,
308    /// Read throughput.
309    pub read_bytes_per_sec: f64,
310    /// Write throughput.
311    pub write_bytes_per_sec: f64,
312    /// Fraction of time the device had I/O in flight, where the platform
313    /// reports it (Linux).
314    pub busy_percent: Option<f32>,
315    /// Drive temperature (NVMe composite sensor), if available.
316    pub temperature_c: Option<f32>,
317}
318
319/// Capacity of one filesystem.
320///
321/// Filesystems mounted at several places (e.g. btrfs subvolumes) appear once,
322/// with all mount points listed.
323#[derive(Debug, Clone, Default, Serialize, Deserialize)]
324#[serde(default)]
325pub struct FilesystemUsage {
326    /// Source device (e.g. `"/dev/nvme1n1p1"`).
327    pub device: String,
328    /// Filesystem type (e.g. `"btrfs"`, `"ext4"`).
329    pub fs_type: String,
330    /// All mount points of this filesystem, shortest first.
331    pub mount_points: Vec<String>,
332    /// Total size.
333    pub total_bytes: u64,
334    /// Space available to unprivileged users.
335    pub available_bytes: u64,
336}
337
338/// Returns true if `device` (a disk such as `"sda"`, or an NVMe controller
339/// such as `"nvme0"`) is the drive behind the block device `disk`
340/// (`"sda"`, `"nvme0n1"`).
341///
342/// `"nvme1"` does not match `"nvme10n1"`: after the controller name only the
343/// namespace suffix (`n<N>`) may follow.
344pub fn device_matches_disk(device: &str, disk: &str) -> bool {
345    match disk.strip_prefix(device) {
346        Some("") => true,
347        Some(rest) => device.starts_with("nvme") && rest.starts_with('n'),
348        None => false,
349    }
350}
351
352/// SMART health of one drive, parsed from `smartctl -j -a` output.
353///
354/// Fields a drive or protocol does not report are `None` (NVMe drives have
355/// no sector reallocation counters, ATA drives no "percentage used").
356#[derive(Debug, Clone, Default, Serialize, Deserialize)]
357#[serde(default)]
358pub struct SmartDevice {
359    /// Kernel device name (`"nvme0"`, `"sda"`). See [`device_matches_disk`].
360    pub device: String,
361    /// Protocol reported by smartctl (`"NVMe"`, `"ATA"`, `"SCSI"`).
362    pub protocol: String,
363    /// Drive model.
364    pub model: String,
365    /// Overall health self-assessment; `None` if smartctl could not tell.
366    pub passed: Option<bool>,
367    /// Current drive temperature.
368    pub temperature_c: Option<f32>,
369    /// Accumulated power-on time.
370    pub power_on_hours: Option<u64>,
371    /// NVMe wear estimate (may exceed 100).
372    pub percentage_used: Option<u32>,
373    /// NVMe spare capacity left.
374    pub available_spare_percent: Option<u32>,
375    /// NVMe spare threshold below which the drive reports a warning.
376    pub available_spare_threshold_percent: Option<u32>,
377    /// NVMe critical warning bit field (0 when healthy).
378    pub critical_warning: Option<u32>,
379    /// NVMe unrecovered data integrity errors.
380    pub media_errors: Option<u64>,
381    /// ATA attribute 5 (Reallocated_Sector_Ct), raw value.
382    pub reallocated_sectors: Option<u64>,
383    /// ATA attribute 197 (Current_Pending_Sector), raw value.
384    pub pending_sectors: Option<u64>,
385    /// ATA attribute 198 (Offline_Uncorrectable), raw value.
386    pub offline_uncorrectable: Option<u64>,
387    /// Total host writes, where the drive reports them.
388    pub data_written_bytes: Option<u64>,
389    /// When smartctl ran, in milliseconds since the Unix epoch. Lets front-ends
390    /// flag stale results (e.g. the timer stopped running).
391    pub collected_at_ms: Option<u64>,
392    /// Error reported by smartctl (e.g. the device could not be opened).
393    pub error: Option<String>,
394}
395
396impl SmartDevice {
397    /// Returns true if anything in the SMART data calls for attention.
398    pub fn needs_attention(&self) -> bool {
399        let positive = |v: Option<u64>| v.is_some_and(|v| v > 0);
400        let spare_low = match (
401            self.available_spare_percent,
402            self.available_spare_threshold_percent,
403        ) {
404            (Some(spare), Some(threshold)) => spare < threshold,
405            _ => false,
406        };
407        self.passed == Some(false)
408            || self.error.is_some()
409            || self.critical_warning.is_some_and(|w| w != 0)
410            || positive(self.media_errors)
411            || positive(self.reallocated_sectors)
412            || positive(self.pending_sectors)
413            || positive(self.offline_uncorrectable)
414            || self.percentage_used.is_some_and(|p| p >= 100)
415            || spare_low
416    }
417}
418
419/// Software RAID state.
420#[derive(Debug, Clone, Default, Serialize, Deserialize)]
421#[serde(default)]
422pub struct RaidStats {
423    /// Mounted btrfs filesystems.
424    pub btrfs: Vec<BtrfsFilesystem>,
425    /// Linux md (mdadm) arrays.
426    pub md: Vec<MdArray>,
427}
428
429/// A btrfs filesystem as seen in `/sys/fs/btrfs/<fsid>`.
430#[derive(Debug, Clone, Default, Serialize, Deserialize)]
431#[serde(default)]
432pub struct BtrfsFilesystem {
433    /// Filesystem UUID.
434    pub fsid: String,
435    /// Filesystem label (may be empty).
436    pub label: String,
437    /// Mount points found in the mount table for this filesystem.
438    pub mount_points: Vec<String>,
439    /// Member block devices (e.g. `"nvme0n1"`, `"nvme1n1p1"`).
440    pub devices: Vec<String>,
441    /// Per-device error counters, keyed by btrfs device id. Each carries its
442    /// device name when it could be looked up (see [`BtrfsDeviceStats::name`]);
443    /// the list is not aligned with `devices`.
444    pub device_stats: Vec<BtrfsDeviceStats>,
445    /// Allocation per block group type (data, metadata, system).
446    pub allocations: Vec<BtrfsAllocation>,
447    /// Result of the most recent scrub, if it is known. Error counters in
448    /// `device_stats` only grow when data is read, so the scrub time tells
449    /// when all data was last verified.
450    pub scrub: Option<BtrfsScrub>,
451}
452
453/// Outcome of the last btrfs scrub (summed over devices).
454#[derive(Debug, Clone, Default, Serialize, Deserialize)]
455#[serde(default)]
456pub struct BtrfsScrub {
457    /// Start time, in milliseconds since the Unix epoch.
458    pub started_at_ms: u64,
459    /// Run time in seconds.
460    pub duration_secs: u64,
461    /// `"finished"`, `"canceled"` or `"unfinished"` (running or interrupted).
462    pub state: String,
463    /// Bytes verified.
464    pub bytes_scrubbed: u64,
465    /// Read, checksum, verify and superblock errors found.
466    pub errors: u64,
467    /// Errors that were repaired from a good copy.
468    pub corrected: u64,
469    /// Errors that could not be repaired.
470    pub uncorrectable: u64,
471}
472
473impl BtrfsFilesystem {
474    /// Returns true if any member is missing or has a non-zero error counter.
475    pub fn has_problems(&self) -> bool {
476        self.device_stats
477            .iter()
478            .any(|d| d.missing || d.total_errors() > 0)
479    }
480}
481
482/// Error counters of one btrfs member device.
483#[derive(Debug, Clone, Default, Serialize, Deserialize)]
484#[serde(default)]
485pub struct BtrfsDeviceStats {
486    /// btrfs device id (1-based).
487    pub devid: u64,
488    /// Device name (e.g. `"nvme0n1"`), from the `BTRFS_IOC_DEV_INFO` ioctl
489    /// on a mount point; empty when unknown (not mounted, device missing).
490    pub name: String,
491    /// Size of the device as btrfs uses it.
492    pub size_bytes: Option<u64>,
493    /// Space allocated on the device.
494    pub used_bytes: Option<u64>,
495    /// Whether the device is missing from the filesystem.
496    pub missing: bool,
497    /// Write I/O errors.
498    pub write_errs: u64,
499    /// Read I/O errors.
500    pub read_errs: u64,
501    /// Flush errors.
502    pub flush_errs: u64,
503    /// Checksum mismatches.
504    pub corruption_errs: u64,
505    /// Generation mismatches (stale data).
506    pub generation_errs: u64,
507}
508
509impl BtrfsDeviceStats {
510    /// Name for display: the device name, else `devid N`.
511    pub fn label(&self) -> String {
512        if self.name.is_empty() {
513            format!("devid {}", self.devid)
514        } else {
515            self.name.clone()
516        }
517    }
518
519    /// Sum of all error counters.
520    pub fn total_errors(&self) -> u64 {
521        self.write_errs
522            + self.read_errs
523            + self.flush_errs
524            + self.corruption_errs
525            + self.generation_errs
526    }
527}
528
529/// Space allocation of one btrfs block group type and RAID profile.
530#[derive(Debug, Clone, Default, Serialize, Deserialize)]
531#[serde(default)]
532pub struct BtrfsAllocation {
533    /// Block group type: `"data"`, `"metadata"` or `"system"`.
534    pub kind: String,
535    /// RAID profile (e.g. `"single"`, `"raid0"`, `"raid1c3"`).
536    pub profile: String,
537    /// Space allocated to this profile (logical size).
538    pub total_bytes: u64,
539    /// Space used within the allocation (logical size).
540    pub used_bytes: u64,
541}
542
543/// One Linux md array parsed from `/proc/mdstat`.
544#[derive(Debug, Clone, Default, Serialize, Deserialize)]
545#[serde(default)]
546pub struct MdArray {
547    /// Array name (e.g. `"md0"`).
548    pub name: String,
549    /// Whether the array is active.
550    pub active: bool,
551    /// Whether the array is read-only (`active (read-only)` / `(auto-read-only)`).
552    pub read_only: bool,
553    /// RAID level (e.g. `"raid1"`); empty for inactive arrays.
554    pub level: String,
555    /// Member devices.
556    pub members: Vec<MdMember>,
557    /// Number of devices the array should have (`[n/m]` -> n).
558    pub expected_devices: Option<u32>,
559    /// Number of devices currently in sync (`[n/m]` -> m).
560    pub working_devices: Option<u32>,
561    /// Ongoing resync/recovery/reshape/check, if any.
562    pub sync: Option<MdSync>,
563}
564
565impl MdArray {
566    /// Returns true if the array runs with fewer devices than expected or has a failed member.
567    pub fn is_degraded(&self) -> bool {
568        let short = match (self.expected_devices, self.working_devices) {
569            (Some(expected), Some(working)) => working < expected,
570            _ => false,
571        };
572        short || self.members.iter().any(|m| m.faulty)
573    }
574}
575
576/// A member device of an md array.
577#[derive(Debug, Clone, Default, Serialize, Deserialize)]
578#[serde(default)]
579pub struct MdMember {
580    /// Device name (e.g. `"sda1"`).
581    pub name: String,
582    /// Role number within the array.
583    pub role: u32,
584    /// Marked faulty `(F)`.
585    pub faulty: bool,
586    /// Spare device `(S)`.
587    pub spare: bool,
588}
589
590/// Progress of an md background operation.
591#[derive(Debug, Clone, Default, Serialize, Deserialize)]
592#[serde(default)]
593pub struct MdSync {
594    /// Operation name: `"resync"`, `"recovery"`, `"reshape"` or `"check"`.
595    pub action: String,
596    /// Completion percentage.
597    pub percent: f32,
598    /// Estimated minutes until completion.
599    pub finish_minutes: Option<f32>,
600    /// Current speed in KiB/s.
601    pub speed_kib_per_sec: Option<u64>,
602}
603
604/// Traffic of one network interface.
605#[derive(Debug, Clone, Default, Serialize, Deserialize)]
606#[serde(default)]
607pub struct NetworkStats {
608    /// Interface name (e.g. `"enp9s0"`).
609    pub name: String,
610    /// Receive throughput.
611    pub rx_bytes_per_sec: f64,
612    /// Transmit throughput.
613    pub tx_bytes_per_sec: f64,
614    /// Bytes received since the interface came up.
615    pub rx_total_bytes: u64,
616    /// Bytes transmitted since the interface came up.
617    pub tx_total_bytes: u64,
618    /// Negotiated link speed in Mbit/s (wired links), if known.
619    pub link_speed_mbps: Option<u32>,
620    /// Whether the link is up, if the OS reports it.
621    pub link_up: Option<bool>,
622    /// Wi-Fi link details, for wireless interfaces.
623    pub wireless: Option<WirelessLink>,
624}
625
626/// State of a Wi-Fi link.
627#[derive(Debug, Clone, Default, Serialize, Deserialize)]
628#[serde(default)]
629pub struct WirelessLink {
630    /// Current receive bit rate in Mbit/s.
631    pub rx_bitrate_mbps: Option<f32>,
632    /// Current transmit bit rate in Mbit/s.
633    pub tx_bitrate_mbps: Option<f32>,
634    /// Signal strength in dBm.
635    pub signal_dbm: Option<i32>,
636}
637
638/// One process.
639#[derive(Debug, Clone, Default, Serialize, Deserialize)]
640#[serde(default)]
641pub struct ProcessInfo {
642    /// Process id.
643    pub pid: u32,
644    /// Parent process id.
645    pub parent_pid: Option<u32>,
646    /// Short name (executable name).
647    pub name: String,
648    /// Full command line joined by spaces.
649    pub command: String,
650    /// Owner user name (or numeric uid when it cannot be resolved).
651    pub user: String,
652    /// Scheduling state (e.g. "Run", "Sleep", "Zombie").
653    pub state: String,
654    /// CPU usage; 100 means one full core, so multi-threaded processes may exceed 100.
655    pub cpu_percent: f32,
656    /// Resident memory.
657    pub memory_bytes: u64,
658    /// Number of threads, where known.
659    pub threads: Option<u32>,
660    /// Disk read throughput.
661    pub read_bytes_per_sec: f64,
662    /// Disk write throughput.
663    pub write_bytes_per_sec: f64,
664    /// Seconds since the process started.
665    pub run_time_secs: u64,
666    /// Kernel thread (e.g. `kworker`), which front-ends may hide.
667    pub kernel_thread: bool,
668}
669
670#[cfg(test)]
671mod tests {
672    use super::*;
673
674    fn process(pid: u32, cpu: f32) -> ProcessInfo {
675        ProcessInfo {
676            pid,
677            cpu_percent: cpu,
678            ..Default::default()
679        }
680    }
681
682    #[test]
683    fn cpu_power_falls_back_to_a_laptop_apu_only() {
684        let power = |cpu: Option<f32>, igpu: Option<f32>| PowerStats {
685            cpu_package_w: cpu,
686            igpu_w: igpu,
687            ..Default::default()
688        };
689        assert_eq!(
690            power(Some(30.0), Some(6.0)).cpu_or_soc_w(),
691            ("CPU", Some(30.0))
692        );
693        assert_eq!(power(None, Some(6.0)).cpu_or_soc_w(), ("SoC", Some(6.0)));
694        // A desktop Ryzen iGPU's few milliwatts are not the SoC.
695        assert_eq!(power(None, Some(0.007)).cpu_or_soc_w(), ("CPU", None));
696        assert_eq!(power(None, None).cpu_or_soc_w(), ("CPU", None));
697    }
698
699    #[test]
700    fn truncate_keeps_top_cpu_processes_in_order() {
701        let mut snapshot = Snapshot {
702            processes: vec![
703                process(1, 5.0),
704                process(2, 50.0),
705                process(3, 0.0),
706                process(4, 20.0),
707            ],
708            process_count: 4,
709            ..Default::default()
710        };
711        snapshot.truncate_processes(2);
712        let pids: Vec<u32> = snapshot.processes.iter().map(|p| p.pid).collect();
713        assert_eq!(pids, vec![2, 4]);
714        // The total is preserved for display ("2 of 4 processes").
715        assert_eq!(snapshot.process_count, 4);
716    }
717
718    #[test]
719    fn truncate_leaves_out_kernel_threads() {
720        let kworker = |pid: u32, cpu: f32| ProcessInfo {
721            kernel_thread: true,
722            ..process(pid, cpu)
723        };
724        let mut snapshot = Snapshot {
725            processes: vec![
726                kworker(1, 9.0),
727                process(2, 5.0),
728                kworker(3, 8.0),
729                process(4, 1.0),
730                process(5, 0.0),
731            ],
732            process_count: 5,
733            ..Default::default()
734        };
735        snapshot.truncate_processes(3);
736        let pids: Vec<u32> = snapshot.processes.iter().map(|p| p.pid).collect();
737        assert_eq!(pids, vec![2, 4, 5], "busy kworkers take no places");
738        assert_eq!(snapshot.process_count, 5);
739    }
740
741    #[test]
742    fn snapshot_round_trips_through_json() {
743        let snapshot = Snapshot {
744            timestamp_ms: 42,
745            processes: vec![process(7, 1.5)],
746            ..Default::default()
747        };
748        let json = serde_json::to_string(&snapshot).unwrap();
749        let back: Snapshot = serde_json::from_str(&json).unwrap();
750        assert_eq!(back.timestamp_ms, 42);
751        assert_eq!(back.processes[0].pid, 7);
752    }
753
754    #[test]
755    fn device_matching_handles_nvme_namespaces() {
756        assert!(device_matches_disk("sda", "sda"));
757        assert!(device_matches_disk("nvme0", "nvme0n1"));
758        assert!(device_matches_disk("nvme1", "nvme1n1"));
759        assert!(!device_matches_disk("nvme1", "nvme10n1"));
760        assert!(!device_matches_disk("sd", "sda"));
761        assert!(!device_matches_disk("sda", "sdb"));
762    }
763
764    #[test]
765    fn smart_attention_flags() {
766        let healthy = SmartDevice {
767            passed: Some(true),
768            media_errors: Some(0),
769            available_spare_percent: Some(100),
770            available_spare_threshold_percent: Some(10),
771            ..Default::default()
772        };
773        assert!(!healthy.needs_attention());
774        let worn = SmartDevice {
775            available_spare_percent: Some(5),
776            ..healthy.clone()
777        };
778        assert!(worn.needs_attention());
779        let reallocated = SmartDevice {
780            reallocated_sectors: Some(8),
781            ..healthy
782        };
783        assert!(reallocated.needs_attention());
784    }
785
786    #[test]
787    fn md_array_degraded_detection() {
788        let mut array = MdArray {
789            expected_devices: Some(2),
790            working_devices: Some(2),
791            ..Default::default()
792        };
793        assert!(!array.is_degraded());
794        array.working_devices = Some(1);
795        assert!(array.is_degraded());
796    }
797}