1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! Main statistics collection and management
use crate::core::{
cpu::CpuStats, engine::EngineStats, gpu::GpuStats, memory::MemoryStats,
platform_info::BoardInfo, power::PowerStats, process::ProcessStats,
temperature::TemperatureStats,
};
use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::time::Duration;
/// Complete system snapshot
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Snapshot {
/// CPU statistics
pub cpu: CpuStats,
/// GPU statistics
pub gpus: std::collections::HashMap<String, crate::core::gpu::GpuInfo>,
/// Memory statistics
pub memory: MemoryStats,
/// Power statistics
pub power: PowerStats,
/// Temperature statistics
pub temperature: TemperatureStats,
/// Fan statistics, or `None` when the fan query failed. An empty map means
/// no fans were reported; a failed query is not that, and is not fatal to
/// the rest of the snapshot either.
pub fans: Option<std::collections::HashMap<String, crate::core::fan::FanInfo>>,
/// Board information
pub board: BoardInfo,
/// Process statistics
pub processes: ProcessStats,
/// Engine statistics, or `None` where the platform does not read them. An empty
/// `EngineStats` means no engines were found, which is not the same thing.
pub engines: Option<EngineStats>,
/// Uptime in seconds
pub uptime: Duration,
}
/// Main IronMonitor interface
pub struct IronMonitor {
/// Update interval
interval: Duration,
/// Last snapshot
last_snapshot: Option<Snapshot>,
/// Platform information (cached)
board_info: BoardInfo,
}
impl IronMonitor {
/// Create a new IronMonitor instance
///
/// # Arguments
///
/// * `interval` - Update interval in seconds (default: 1.0)
///
/// # Example
///
/// ```no_run
/// use ironmonitor::IronMonitor;
///
/// let stats = IronMonitor::new().unwrap();
/// ```
pub fn new() -> Result<Self> {
Self::with_interval(1.0)
}
/// Create a new IronMonitor instance with custom interval
///
/// # Arguments
///
/// * `interval` - Update interval in seconds
///
/// # Example
///
/// ```no_run
/// use ironmonitor::IronMonitor;
///
/// let stats = IronMonitor::with_interval(0.5).unwrap();
/// ```
pub fn with_interval(interval: f64) -> Result<Self> {
let interval = Duration::from_secs_f64(interval);
// Detect platform information once
let board_info = detect_platform_info()?;
Ok(Self {
interval,
last_snapshot: None,
board_info,
})
}
/// Get current snapshot of all statistics
///
/// # Example
///
/// ```no_run
/// use ironmonitor::IronMonitor;
///
/// let mut stats = IronMonitor::new().unwrap();
/// let snapshot = stats.snapshot().unwrap();
/// println!("CPU cores: {}", snapshot.cpu.cores.len());
/// ```
pub fn snapshot(&mut self) -> Result<Snapshot> {
// Read all stats
let cpu = read_cpu_stats()?;
let gpu_stats = read_gpu_stats()?;
let memory = read_memory_stats()?;
let power = read_power_stats()?;
let temperature = read_temperature_stats()?;
// Read fan stats
let fans = read_fan_stats().ok();
// Read process stats
let processes = read_process_stats()?;
// Read engine stats. Where they are not read the field is `None`, so the rest of
// the snapshot still comes back.
let engines = read_engine_stats().ok();
// Read uptime
let uptime = read_uptime()?;
let snapshot = Snapshot {
cpu,
gpus: gpu_stats.gpus().clone(),
memory,
power,
temperature,
fans,
board: self.board_info.clone(),
processes,
engines,
uptime,
};
self.last_snapshot = Some(snapshot.clone());
Ok(snapshot)
}
/// Read CPU statistics alone.
///
/// [`Self::snapshot`] needs every reader to succeed, so on a platform where any
/// one of them is unimplemented it returns an error and the rest are
/// unreachable. macOS is that platform today: CPU, memory, uptime and board
/// info are implemented while GPU, power and temperature are not. These
/// accessors expose what does work without the others having to pretend.
pub fn cpu(&self) -> Result<CpuStats> {
read_cpu_stats()
}
/// Read memory statistics alone. See [`Self::cpu`].
pub fn memory(&self) -> Result<MemoryStats> {
read_memory_stats()
}
/// Read system uptime alone. See [`Self::cpu`].
pub fn uptime(&self) -> Result<Duration> {
read_uptime()
}
/// Get the update interval
pub fn interval(&self) -> Duration {
self.interval
}
/// Get board information
pub fn board_info(&self) -> &BoardInfo {
&self.board_info
}
/// Get last snapshot (if available)
pub fn last_snapshot(&self) -> Option<&Snapshot> {
self.last_snapshot.as_ref()
}
}
/// Seconds since boot, without building a [`IronMonitor`].
///
/// [`IronMonitor::uptime`] needs an instance, and constructing one collects board
/// information a caller who only wants uptime has no use for. The agent tool
/// surface reported `uptime_seconds: 0` with the comment "would need
/// platform-specific impl" while `read_uptime` had one on all three platforms;
/// the missing piece was a way to reach it, not the reader.
pub fn uptime() -> Result<Duration> {
read_uptime()
}
// Platform-specific implementations
#[cfg(target_os = "linux")]
fn read_cpu_stats() -> Result<CpuStats> {
crate::platform::linux::read_cpu_stats()
}
#[cfg(target_os = "linux")]
fn read_gpu_stats() -> Result<GpuStats> {
crate::platform::linux::read_gpu_stats()
}
#[cfg(target_os = "linux")]
fn read_memory_stats() -> Result<MemoryStats> {
crate::platform::linux::read_memory_stats()
}
#[cfg(target_os = "linux")]
fn read_power_stats() -> Result<PowerStats> {
crate::platform::linux::read_power_stats()
}
#[cfg(target_os = "linux")]
fn read_temperature_stats() -> Result<TemperatureStats> {
crate::platform::linux::read_temperature_stats()
}
#[cfg(target_os = "linux")]
fn detect_platform_info() -> Result<BoardInfo> {
crate::platform::linux::detect_platform()
}
#[cfg(target_os = "linux")]
fn read_uptime() -> Result<Duration> {
use std::fs;
let uptime_str = fs::read_to_string("/proc/uptime")?;
let uptime_secs: f64 = uptime_str
.split_whitespace()
.next()
.ok_or_else(|| crate::error::IronError::Parse("Invalid uptime format".to_string()))?
.parse()
.map_err(|e| crate::error::IronError::Parse(format!("Failed to parse uptime: {}", e)))?;
Ok(Duration::from_secs_f64(uptime_secs))
}
#[cfg(target_os = "linux")]
fn read_process_stats() -> Result<ProcessStats> {
crate::core::process::linux::read_process_stats()
}
#[cfg(target_os = "linux")]
fn read_engine_stats() -> Result<EngineStats> {
crate::core::engine::linux::read_engine_stats()
}
#[cfg(windows)]
fn read_cpu_stats() -> Result<CpuStats> {
crate::platform::windows::read_cpu_stats()
}
#[cfg(windows)]
fn read_gpu_stats() -> Result<GpuStats> {
crate::platform::windows::read_gpu_stats()
}
#[cfg(windows)]
fn read_memory_stats() -> Result<MemoryStats> {
crate::platform::windows::read_memory_stats()
}
#[cfg(windows)]
fn read_power_stats() -> Result<PowerStats> {
crate::platform::windows::read_power_stats()
}
#[cfg(windows)]
fn read_temperature_stats() -> Result<TemperatureStats> {
crate::platform::windows::read_temperature_stats()
}
#[cfg(windows)]
fn detect_platform_info() -> Result<BoardInfo> {
crate::platform::windows::detect_platform()
}
#[cfg(windows)]
fn read_uptime() -> Result<Duration> {
Ok(crate::platform::windows::get_system_uptime())
}
#[cfg(windows)]
fn read_process_stats() -> Result<ProcessStats> {
crate::platform::windows::read_process_stats()
}
#[cfg(windows)]
fn read_engine_stats() -> Result<EngineStats> {
// Windows has no engine concept like Jetson's. This returned an empty `EngineStats`,
// which the CLI printed as zero engine groups. Nothing was read, so it is an error.
Err(crate::error::IronError::UnsupportedPlatform(
"engine statistics are not read on Windows".to_string(),
))
}
/// Read fan stats. A value that cannot be read is `None`, never zero.
#[cfg(target_os = "linux")]
fn read_fan_stats() -> Result<std::collections::HashMap<String, crate::core::fan::FanInfo>> {
use crate::core::fan::FanInfo;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
let mut fans = HashMap::new();
// Look for fans in hwmon
let hwmon_path = Path::new("/sys/class/hwmon");
if let Ok(entries) = fs::read_dir(hwmon_path) {
for entry in entries.flatten() {
let hwmon_dir = entry.path();
// Get device name. When `name` is unreadable the sysfs directory name
// (`hwmonN`) keys the fans instead. This used to be the literal "unknown",
// which gave every such device the same keys, so one overwrote the others.
let name = fs::read_to_string(hwmon_dir.join("name"))
.map(|s| s.trim().to_string())
.unwrap_or_else(|_| entry.file_name().to_string_lossy().into_owned());
// Look for fan inputs (fan1_input, fan2_input, etc.)
for i in 1..=10 {
let fan_input = hwmon_dir.join(format!("fan{}_input", i));
if !fan_input.exists() {
continue;
}
// Read RPM. Unreadable means no RPM, not 0 RPM.
let rpm = fs::read_to_string(&fan_input)
.ok()
.and_then(|s| s.trim().parse::<u32>().ok());
// Speed comes only from the PWM duty cycle. The old fallback derived
// it from RPM against an assumed 5000 RPM ceiling, which the fan never
// reported.
let pwm_path = hwmon_dir.join(format!("pwm{}", i));
let speed = if pwm_path.exists() {
fs::read_to_string(&pwm_path)
.ok()
.and_then(|s| s.trim().parse::<u32>().ok())
.map(|pwm| pwm * 100 / 255) // PWM is 0-255
} else {
None
};
fans.insert(
format!("{}-fan{}", name, i),
FanInfo {
speed,
rpm: rpm.map(|r| vec![r]),
// No profile: hwmon does not report an auto/manual mode, and
// "auto" was a constant standing in for one.
profile: None,
governor: None,
control: None,
},
);
}
}
}
// Also check for Jetson-style thermal cooling devices
let cooling_path = Path::new("/sys/class/thermal");
if let Ok(entries) = fs::read_dir(cooling_path) {
for entry in entries.flatten() {
let path = entry.path();
let name = path.file_name().unwrap_or_default().to_string_lossy();
if !name.starts_with("cooling_device") {
continue;
}
// Read current state and max state. Either one unread leaves the speed
// unknown; a max of zero has no percentage.
let cur_state = fs::read_to_string(path.join("cur_state"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok());
let max_state = fs::read_to_string(path.join("max_state"))
.ok()
.and_then(|s| s.trim().parse::<u32>().ok());
let speed = match (cur_state, max_state) {
(Some(cur), Some(max)) => cur.checked_mul(100).and_then(|v| v.checked_div(max)),
_ => None,
};
// Get device type. An unreadable type cannot be classified, so the
// device is skipped rather than assumed to be a fan.
let device_type = match fs::read_to_string(path.join("type")) {
Ok(s) => s.trim().to_string(),
Err(_) => continue,
};
if device_type.contains("fan") || device_type.contains("pwm") {
fans.insert(
format!("{}", name),
FanInfo {
speed,
rpm: None,
// "thermal" named the source, not a mode the device reported.
profile: None,
governor: None,
control: Some(device_type),
},
);
}
}
}
Ok(fans)
}
/// Read fan stats on Windows using WMI
#[cfg(windows)]
fn read_fan_stats() -> Result<std::collections::HashMap<String, crate::core::fan::FanInfo>> {
use crate::core::fan::FanInfo;
use serde::Deserialize;
use std::collections::HashMap;
use wmi::{COMLibrary, WMIConnection};
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32Fan {
name: Option<String>,
device_id: Option<String>,
}
let mut fans = HashMap::new();
// Try WMI fan class
if let Ok(com_con) = COMLibrary::new() {
if let Ok(wmi_con) = WMIConnection::with_namespace_path("root\\CIMV2", com_con) {
// Try Win32_Fan class (may not be populated on all systems). No rows
// means no fans; a failed query is an error, not an empty list.
let wmi_fans: Vec<Win32Fan> = wmi_con
.raw_query("SELECT Name, DeviceID FROM Win32_Fan")
.map_err(|e| {
crate::error::IronError::System(format!("WMI query `Win32_Fan`: {e}"))
})?;
for fan in wmi_fans.iter() {
// The map is keyed by name. A fan with neither a Name nor a DeviceID
// is skipped rather than given an invented one: a positional
// "Fan{idx}" used to be made up here and named nothing the hardware
// reported.
let Some(name) = fan.name.clone().or_else(|| fan.device_id.clone()) else {
continue;
};
// Win32_Fan reports no speed, RPM or profile. Its `ActiveCooling` boolean
// used to be written as the profile "active" or "idle"; it says whether the
// fan is working, not what mode it is in, and FanInfo has no field for it,
// so it is not read here.
fans.insert(
name.clone(),
FanInfo {
speed: None,
rpm: None,
profile: None,
governor: None,
control: None,
},
);
}
}
// Try OpenHardwareMonitor/LibreHardwareMonitor for detailed fan info
if let Ok(lhm_con) =
WMIConnection::with_namespace_path("root\\LibreHardwareMonitor", com_con)
{
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
#[allow(dead_code)]
struct LhmSensor {
name: String,
sensor_type: String,
value: f32,
parent: String,
}
let lhm_fans: Vec<LhmSensor> = lhm_con
.raw_query(
"SELECT Name, SensorType, Value, Parent FROM Sensor WHERE SensorType = 'Fan'",
)
.map_err(|e| {
crate::error::IronError::System(format!(
"WMI query `LibreHardwareMonitor Fan`: {e}"
))
})?;
for fan in lhm_fans {
let name = format!(
"{}-{}",
fan.parent.split('/').next_back().unwrap_or("MB"),
fan.name
);
fans.insert(
name,
FanInfo {
// The sensor reports RPM only; a percentage would need a ceiling
// this code made up.
speed: None,
rpm: Some(vec![fan.value as u32]),
profile: None,
governor: None,
control: None,
},
);
}
}
}
Ok(fans)
}
/// Read fan stats on macOS
#[cfg(target_os = "macos")]
fn read_fan_stats() -> Result<std::collections::HashMap<String, crate::core::fan::FanInfo>> {
use crate::core::fan::FanInfo;
use std::collections::HashMap;
use std::process::Command;
let mut fans = HashMap::new();
// Try using smcFanControl or similar if available
// For now, try iStats gem if available
if let Ok(output) = Command::new("istats").args(["fan", "speed"]).output() {
let stdout = String::from_utf8_lossy(&output.stdout);
for line in stdout.lines() {
if let Some(rpm_str) = line.split_whitespace().last() {
if let Ok(rpm) = rpm_str.replace("RPM", "").trim().parse::<u32>() {
fans.insert(
"CPU Fan".to_string(),
FanInfo {
speed: None,
rpm: Some(vec![rpm]),
profile: None,
governor: None,
control: None,
},
);
break;
}
}
}
}
Ok(fans)
}
// Platform implementations for macOS.
//
// `stats.rs` has carried Linux and Windows implementations of these since the
// beginning and never had macOS ones, so `IronMonitor` could not be built there at all —
// the manifest bug meant nothing ever tried, and the gap went unnoticed.
//
// These report `UnsupportedPlatform` rather than guessing. Writing real ones means
// sysctl and IOKit work that has to be verified on actual hardware; a plausible
// implementation that returned made-up numbers would be worse than an honest
// refusal, because callers cannot tell fabricated telemetry from measured
// telemetry. `UnifiedMonitor` (see `lib.rs`) has working macOS paths and is the
// type to use there today.
#[cfg(target_os = "macos")]
mod macos_stats {
use super::*;
use crate::core::cpu::{CpuCore, CpuTotal};
use crate::core::memory::{RamInfo, SwapInfo};
use crate::core::platform_info::{HardwareInfo, LibraryVersions, PlatformInfo};
use crate::error::IronError;
fn unsupported(what: &str) -> IronError {
IronError::UnsupportedPlatform(format!(
"{what} is not implemented for macOS in `stats::IronMonitor`; use `UnifiedMonitor`"
))
}
pub(super) fn read_cpu_stats() -> Result<CpuStats> {
use crate::platform::macos;
// Only the CPU brand string. This fell back to `hw.model`, the machine
// identifier ("Mac14,2"), which is not a CPU model; the platform reader
// dropped that fallback for the same reason. Empty is unread.
let model = macos::sysctl_string("machdep.cpu.brand_string").filter(|s| !s.is_empty());
// `host_processor_info` is preferred over parsing `top`: it is the only
// source of per-core figures and of nice time. Its whole-CPU and per-core
// splits are differences between two readings, shared with the platform reader
// through `current_total_usage`, so the two agree.
if let Ok((total, per_core)) = macos::current_total_usage() {
let cores = per_core
.iter()
.enumerate()
.map(|(id, usage)| CpuCore {
id,
online: None,
// macOS exposes no governor.
governor: None,
frequency: None,
// Each core's own split over the same window as the total. `None`
// for a core that did not move, rather than its since-boot share.
user: usage.map(|u| u.user),
nice: usage.map(|u| u.nice),
system: usage.map(|u| u.system),
idle: usage.map(|u| u.idle),
model: model.clone(),
})
.collect();
return Ok(CpuStats {
cores,
total: CpuTotal {
user: total.user,
nice: Some(total.nice),
system: total.system,
idle: total.idle,
},
});
}
// Fallback: `top -l 2`, where the second sample covers the interval and the
// first is the since-boot average. It reports one aggregate and no nice
// time. Reached only if the Mach call fails, and it keeps a failure there
// from turning into no CPU data.
let usage = macos::cpu_usage().ok_or_else(|| {
unsupported("CPU statistics: host_processor_info failed and `top` was not understood")
})?;
let count = macos::sysctl_u64("hw.logicalcpu")
.ok_or_else(|| unsupported("CPU statistics: hw.logicalcpu was not read"))?
as usize;
let cores = (0..count)
.map(|id| CpuCore {
id,
online: None,
governor: None,
frequency: None,
// One aggregate copied into every core would present an average as
// a per-core measurement.
user: None,
nice: None,
system: None,
idle: None,
model: model.clone(),
})
.collect();
Ok(CpuStats {
cores,
total: CpuTotal {
user: usage.user,
// `top` does not separate nice time, so none is reported. This was
// a literal 0.0. Only reachable on the fallback path.
nice: None,
system: usage.system,
idle: usage.idle,
},
})
}
pub(super) fn read_gpu_stats() -> Result<GpuStats> {
Err(unsupported("GPU statistics"))
}
pub(super) fn read_memory_stats() -> Result<MemoryStats> {
use crate::platform::macos;
let vm = macos::vm_stat()
.ok_or_else(|| unsupported("memory statistics: `vm_stat` was not understood"))?;
// hw.memsize is the installed RAM. Summing vm_stat's pages gives a slightly
// different figure — the kernel's own footprint is not in the page counts —
// so the installed size is the one to report as total.
// Installed RAM only. The page-count sum used to stand in when `hw.memsize` was
// unreadable, and it leaves out the kernel's own footprint, so it reported a
// smaller total than the machine has. Unread is an error, as it is for CPU.
let total = macos::sysctl_u64("hw.memsize")
.ok_or_else(|| unsupported("memory statistics: hw.memsize was not read"))?;
// Swap being unreadable is different from swap being off: the first is
// unknown, the second is a real zero. `SwapInfo` carries that
// distinction as of 6.0.0, so the value passes through as `Option`
// rather than collapsing to a zero with a comment apologising for it.
// This was the third place in the crate working around the same missing
// type.
let swap = macos::swap_usage();
Ok(MemoryStats {
// KB throughout, which every field of `RamInfo` and `SwapInfo`
// documents. This reader assigned bytes to all of them — a factor of
// 1024 — while `platform::macos::read_memory_stats` divided
// correctly, so the same machine reported two different sizes
// depending on which entry point a caller used.
ram: RamInfo {
total: total / 1024,
used: vm.used_bytes() / 1024,
free: Some(vm.free_bytes() / 1024),
// macOS has no buffer cache distinct from the file cache, so
// there is no figure to report rather than a figure of zero.
buffers: None,
cached: Some(vm.cached_bytes() / 1024),
// Not read here.
shared: None,
lfb: None,
},
swap: SwapInfo {
total: swap.map(|s| s.total / 1024),
used: swap.map(|s| s.used / 1024),
cached: None,
},
emc: None,
iram: None,
})
}
pub(super) fn read_power_stats() -> Result<PowerStats> {
Err(unsupported("power statistics"))
}
pub(super) fn read_temperature_stats() -> Result<TemperatureStats> {
Err(unsupported("temperature statistics"))
}
pub(super) fn detect_platform_info() -> Result<BoardInfo> {
use crate::platform::macos;
// `IronMonitor::with_interval` calls this in its constructor, so a failure here
// makes the whole type unconstructible — which is what kept CPU and memory
// out of reach on macOS even after they were implemented.
let machine = macos::sysctl_string("hw.machine").unwrap_or_default();
let model = macos::sysctl_string("hw.model").unwrap_or_default();
let release = macos::sysctl_string("kern.osrelease").unwrap_or_default();
let product = macos::sysctl_string("kern.osproductversion");
Ok(BoardInfo {
platform: PlatformInfo {
machine,
system: "Darwin".to_string(),
// The marketing version (26.x) rather than the Darwin kernel
// version, which `release` already carries.
distribution: product.map(|v| format!("macOS {v}")),
release,
},
hardware: HardwareInfo {
model,
p_number: None,
module: None,
soc: macos::sysctl_string("machdep.cpu.brand_string"),
cuda_arch: None,
codename: None,
serial_number: macos::sysctl_string("hw.serialnumber"),
l4t: None,
jetpack: None,
},
libraries: LibraryVersions {
cuda: None,
cudnn: None,
tensorrt: None,
other: std::collections::HashMap::new(),
},
})
}
pub(super) fn read_uptime() -> Result<Duration> {
use crate::platform::macos;
// kern.boottime prints `{ sec = 1754500000, usec = 123456 } ...`
let raw = macos::sysctl_string("kern.boottime").ok_or_else(|| unsupported("uptime"))?;
let boot_secs: u64 = raw
.split("sec = ")
.nth(1)
.and_then(|s| s.split(|c: char| !c.is_ascii_digit()).next())
.and_then(|s| s.parse().ok())
.ok_or_else(|| unsupported("uptime: kern.boottime was not understood"))?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
// A boot time in the future means the two clocks disagree; reporting a
// saturated zero is better than a wrapped duration of 584 million years.
Ok(Duration::from_secs(now.saturating_sub(boot_secs)))
}
pub(super) fn read_process_stats() -> Result<ProcessStats> {
Err(unsupported("process statistics"))
}
pub(super) fn read_engine_stats() -> Result<EngineStats> {
Err(unsupported("engine statistics"))
}
}
#[cfg(target_os = "macos")]
use macos_stats::{
detect_platform_info, read_cpu_stats, read_engine_stats, read_gpu_stats, read_memory_stats,
read_power_stats, read_process_stats, read_temperature_stats, read_uptime,
};
/// The platform CPU reader, for the rest of the crate.
///
/// One wrapper rather than making each platform's reader visible: the macOS
/// implementations are `pub(super)` inside a nested module and cannot be
/// re-exported, and three callers outside this module need a reader that works
/// everywhere. Until 6.0.0 they used `CpuStats::new()` instead, which returns
/// 100% idle — `UnifiedMonitor::snapshot_cpu`, the health checks and the
/// Prometheus exporter all published that as a measurement.
pub(crate) fn platform_cpu_stats() -> Result<CpuStats> {
read_cpu_stats()
}
/// The platform memory reader. See [`platform_cpu_stats`].
pub(crate) fn platform_memory_stats() -> Result<MemoryStats> {
read_memory_stats()
}