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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
//! S.M.A.R.T. disk health monitoring — drive health, temperature, wear, predictions.
//!
//! # Platform Support
//!
//! - **Linux**: Reads `/sys/block/*/device/`, `/sys/class/nvme/*/`, `smartctl` output
//! - **Windows**: Uses WMI (`MSFT_PhysicalDisk`, `MSFT_StorageReliabilityCounter`)
//! - **macOS**: Uses `smartmontools` or `diskutil info`
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::smart::SmartMonitor;
//!
//! let monitor = SmartMonitor::new().unwrap();
//! for disk in monitor.disks() {
//! println!("{}: health={:?}", disk.device, disk.health);
//! // Every counter is `Option`: `None` means the platform would not report it,
//! // which on Windows is the unelevated case. It does not mean zero.
//! match disk.temperature_celsius {
//! Some(c) => println!(" temperature: {c}°C"),
//! None => println!(" temperature: not reported (needs elevation on Windows)"),
//! }
//! if let Some(hours) = disk.power_on_hours {
//! println!(" power-on hours: {hours}");
//! }
//! if let Some(wear) = disk.wear_leveling_percent {
//! println!(" SSD wear: {wear}%");
//! }
//! }
//! ```
use crate::error::IronError;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
/// How stale a shared collector run may be before [`SmartMonitor::cached_disks`]
/// takes another.
///
/// Chosen to be long enough to cover one pass over every drive — the burst this
/// exists to collapse — and short enough that two polls a caller would consider
/// separate are not served the same reading. `docs/DISK_MONITORING.md` suggests
/// polling SMART about once a minute, so at this age a caller polling at any
/// reasonable rate still gets a fresh sweep every time.
pub const CACHE_MAX_AGE: Duration = Duration::from_secs(2);
/// One shared collector run. See [`SmartMonitor::cached_disks`].
static SMART_CACHE: OnceLock<Mutex<SmartCache>> = OnceLock::new();
struct SmartCache {
/// When the run was taken. `None` before the first one.
taken: Option<Instant>,
disks: Arc<[SmartDiskInfo]>,
}
impl SmartCache {
fn empty() -> Self {
Self {
taken: None,
disks: Arc::from(Vec::new()),
}
}
}
/// Overall disk health assessment
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiskHealth {
/// All attributes within normal ranges
Good,
/// Some attributes approaching thresholds
Warning,
/// Critical attributes exceeded, failure likely
Critical,
/// S.M.A.R.T. test failed
Failed,
/// Health could not be determined
Unknown,
}
/// Drive media type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DriveMediaType {
SSD,
HDD,
NVMe,
Hybrid,
Unknown,
}
/// A single S.M.A.R.T. attribute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmartAttribute {
/// Attribute ID (e.g., 5 = Reallocated Sectors)
pub id: u16,
/// Attribute name
pub name: String,
/// Current normalized value (1-253, higher = better)
pub value: u64,
/// Worst recorded value
pub worst: u64,
/// Threshold for failure, or `None` where the platform did not report one.
///
/// Not zero: the Windows ATA path cannot reach `SMART READ THRESHOLDS`
/// through its ioctl, and used to write `0` here, which is a constant
/// rather than this drive's threshold.
pub threshold: Option<u64>,
/// Raw value
pub raw_value: u64,
/// Whether this attribute is pre-fail (true) or old-age (false)
pub pre_fail: bool,
}
/// S.M.A.R.T. data for a single disk
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SmartDiskInfo {
/// Device path (e.g., "/dev/sda", "\\.\PhysicalDrive0")
pub device: String,
/// Device model name
pub model: String,
/// Serial number
pub serial: String,
/// Firmware version
pub firmware: String,
/// Drive media type
pub media_type: DriveMediaType,
/// Capacity in bytes, or `None` where it was not read.
///
/// **This field sat one line above the comment explaining why it should
/// have been `Option`**, and was missed by the pass that wrote it. Four
/// construction sites set it to a literal `0` and the Windows one used
/// `item["Size"].as_u64().unwrap_or(0)`.
pub capacity_bytes: Option<u64>,
/// Overall health assessment. This is the collector's own grade, inferred from
/// the counters below by `infer_health`, and is not a drive's verdict. The
/// drive's verdict is in [`Self::smart_passed`].
pub health: DiskHealth,
/// The drive's own SMART overall-health verdict: `smart_status.passed` from
/// `smartctl -j`, which is what `smartctl -H` prints as PASSED or FAILED.
/// `None` where it was not read. Unlike `health`, this is not computed here.
#[serde(default)]
pub smart_passed: Option<bool>,
// Every counter below is `Option` because "the platform would not tell us" and
// "the drive reports zero" are different facts, and this struct used to render
// both as `0`.
//
// On Windows these come from `Get-StorageReliabilityCounter`, which requires
// elevation: unelevated it fails with `PermissionDenied`. That failure was
// being swallowed and replaced with zeros, so IronMonitor reported every drive as
// healthy with a temperature of 0 °C and zero power-on hours — an access
// error presented as a measurement.
/// Current temperature in Celsius, if the platform reported one
pub temperature_celsius: Option<u32>,
/// Power-on hours
pub power_on_hours: Option<u64>,
/// Power cycle count
pub power_cycle_count: Option<u64>,
/// Reallocated sector count (HDD/SSD)
pub reallocated_sectors: Option<u64>,
/// Pending sector count
pub pending_sectors: Option<u64>,
/// Uncorrectable error count
pub uncorrectable_errors: Option<u64>,
/// SSD wear leveling percentage used (0-100, None for HDD)
pub wear_leveling_percent: Option<f32>,
/// Total bytes written (lifetime). From ATA Total_LBAs_Written, which assumes
/// 512-byte LBAs: the logical sector size is not read on the ATA path, so a
/// 4Kn drive's value is an undercount by eight.
pub total_bytes_written: Option<u64>,
/// Total bytes read (lifetime). From ATA Total_LBAs_Read, under the same
/// 512-byte LBA assumption as `total_bytes_written`.
pub total_bytes_read: Option<u64>,
/// NVMe percentage used (0-100, None for SATA)
pub nvme_percentage_used: Option<u8>,
/// NVMe available spare percentage
pub nvme_available_spare: Option<u8>,
/// NVMe available spare threshold, percent (`spare_thresh`). Read from the
/// same `nvme smart-log` run as the spare itself.
#[serde(default)]
pub nvme_available_spare_threshold: Option<u8>,
/// NVMe controller busy time, in minutes (`controller_busy_time`).
#[serde(default)]
pub nvme_controller_busy_time_minutes: Option<u64>,
/// NVMe unsafe shutdown count (`unsafe_shutdowns`).
#[serde(default)]
pub nvme_unsafe_shutdowns: Option<u64>,
/// NVMe critical warning bit flags (`critical_warning`).
#[serde(default)]
pub nvme_critical_warning: Option<u8>,
/// NVMe host read commands issued (`host_read_commands`).
#[serde(default)]
pub nvme_host_read_commands: Option<u64>,
/// NVMe host write commands issued (`host_write_commands`).
#[serde(default)]
pub nvme_host_write_commands: Option<u64>,
/// All raw S.M.A.R.T. attributes
pub attributes: Vec<SmartAttribute>,
/// Estimated remaining life percentage (0-100)
pub estimated_life_remaining: Option<f32>,
/// Estimated days until failure (if predictable)
pub estimated_days_remaining: Option<u32>,
}
/// Monitor for S.M.A.R.T. disk health
pub struct SmartMonitor {
disks: Vec<SmartDiskInfo>,
}
impl SmartMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self { disks: Vec::new() };
monitor.refresh()?;
Ok(monitor)
}
/// Re-read every drive's SMART data.
///
/// Returns `Err` when the enumeration failed, and `Ok` with an empty list
/// only when it succeeded and found nothing. The two are not the same
/// finding for a health reader, and until 6.0.0 they were the same value.
pub fn refresh(&mut self) -> Result<(), IronError> {
self.disks.clear();
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
// Run inference on all collected disks
for disk in &mut self.disks {
Self::infer_health(disk);
}
Ok(())
}
pub fn disks(&self) -> &[SmartDiskInfo] {
&self.disks
}
/// The whole drive list from a collector run no older than [`CACHE_MAX_AGE`],
/// shared process-wide.
///
/// A collector run is expensive and enumerates *every* drive: on Windows one
/// PowerShell invocation, on Linux one `smartctl` invocation per drive. The
/// [`crate::disk::DiskDevice`] trait is per-device, so its implementations
/// each ran a full sweep to pick one entry out of it — `smart_info()` across N
/// disks cost N sweeps, and because `health()`, `smart_info()` and
/// `nvme_info()` each did it, a single pass over a four-drive machine spawned
/// a subprocess a dozen times on Windows and around fifty on Linux.
///
/// The cache is keyed on nothing but time, because the collector takes no
/// arguments — there is one answer, and the only question is how old it may
/// be. [`CACHE_MAX_AGE`] is far below any sensible SMART polling interval
/// (`docs/DISK_MONITORING.md` suggests a minute), so this collapses the burst
/// within one pass without making consecutive polls return the same reading.
///
/// Callers wanting a guaranteed-fresh sweep should construct a
/// [`SmartMonitor`] directly; this deliberately does not.
pub fn cached_disks() -> Arc<[SmartDiskInfo]> {
let cache = SMART_CACHE.get_or_init(|| Mutex::new(SmartCache::empty()));
// A poisoned lock means some other caller panicked mid-refresh. The cached
// list is a plain value and cannot have been left inconsistent by that, so
// recovering is better than propagating a panic into disk enumeration.
let mut cache = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(taken) = cache.taken {
if taken.elapsed() < CACHE_MAX_AGE {
return Arc::clone(&cache.disks);
}
}
// The refresh happens with the lock held, so concurrent callers wait and
// then share this result rather than each spawning their own sweep. That
// is the entire point: the contended case is exactly the one that used to
// be most expensive.
let disks: Arc<[SmartDiskInfo]> = match Self::new() {
Ok(monitor) => monitor.disks.into(),
// A failed sweep is cached too, for the same window. Retrying it once
// per call would reproduce the cost this exists to remove, on the
// machines least able to afford it.
Err(_) => Arc::from(Vec::new()),
};
cache.taken = Some(Instant::now());
cache.disks = Arc::clone(&disks);
disks
}
/// Get disks with health warnings or worse.
pub fn unhealthy_disks(&self) -> Vec<&SmartDiskInfo> {
self.disks
.iter()
.filter(|d| {
matches!(
d.health,
DiskHealth::Warning | DiskHealth::Critical | DiskHealth::Failed
)
})
.collect()
}
/// Get the hottest disk temperature, if any disk reported one.
pub fn max_temperature(&self) -> Option<u32> {
self.disks
.iter()
.filter_map(|d| d.temperature_celsius)
.max()
}
/// Infer health status and remaining life from raw attributes.
///
/// Scoring only reflects evidence that was actually read. Previously every
/// counter was a plain integer, so a drive whose counters could not be read at
/// all arrived here as zeros, took no penalties, scored 100 and was declared
/// `Good` — a confident verdict derived from nothing. Where no factor applies,
/// this now leaves whatever the platform itself reported (Windows supplies a
/// `HealthStatus`) rather than overwriting it with a computed judgement.
fn infer_health(disk: &mut SmartDiskInfo) {
// A drive reporting its own failure is not something a score can talk out
// of. Every other verdict below is inferred from counters; this one was
// read from the drive, and its attributes can still look clean — SMART
// predicts failure from thresholds this code cannot see. Without this,
// `Failed` from `IOCTL_STORAGE_PREDICT_FAILURE` is scored back to `Good`.
if disk.health == DiskHealth::Failed {
return;
}
let mut score: f32 = 100.0;
let mut had_evidence = false;
// Factor 1: Reallocated sectors (very bad for HDDs, concerning for SSDs)
if let Some(reallocated) = disk.reallocated_sectors.filter(|n| *n > 0) {
had_evidence = true;
let penalty = match disk.media_type {
DriveMediaType::HDD => (reallocated as f32 * 2.0).min(40.0),
_ => (reallocated as f32 * 0.5).min(20.0),
};
score -= penalty;
}
// Factor 2: Pending sectors
if let Some(pending) = disk.pending_sectors.filter(|n| *n > 0) {
had_evidence = true;
score -= (pending as f32 * 3.0).min(30.0);
}
// Factor 3: Uncorrectable errors
if let Some(errors) = disk.uncorrectable_errors.filter(|n| *n > 0) {
had_evidence = true;
score -= (errors as f32 * 5.0).min(40.0);
}
// Factor 4: Temperature (above 55°C is concerning, above 70°C is critical)
if let Some(temp) = disk.temperature_celsius {
had_evidence = true;
if temp > 70 {
score -= 20.0;
} else if temp > 55 {
score -= 5.0;
}
}
// Factor 5: SSD wear leveling
if let Some(wear) = disk.wear_leveling_percent {
had_evidence = true;
if wear > 90.0 {
score -= 30.0;
} else if wear > 75.0 {
score -= 10.0;
}
}
// Factor 6: NVMe percentage used
if let Some(pct) = disk.nvme_percentage_used {
had_evidence = true;
if pct > 90 {
score -= 30.0;
} else if pct > 75 {
score -= 10.0;
}
}
// Factor 7: NVMe available spare
if let Some(spare) = disk.nvme_available_spare {
had_evidence = true;
if spare < 10 {
score -= 25.0;
} else if spare < 25 {
score -= 10.0;
}
}
// Factor 8: Power-on hours (age penalty)
// HDDs: 30k+ hours is old; SSDs: 50k+ hours is old
let age_threshold = match disk.media_type {
DriveMediaType::HDD => 30_000,
_ => 50_000,
};
if let Some(hours) = disk.power_on_hours {
had_evidence = true;
if hours > age_threshold * 2 {
score -= 15.0;
} else if hours > age_threshold {
score -= 5.0;
}
}
// With nothing to go on, keep the platform's own verdict and publish no
// life estimate. A score of 100 here would mean "no penalties applied",
// which is not the same as "healthy".
if !had_evidence {
return;
}
// Determine health from score
disk.health = if score >= 80.0 {
DiskHealth::Good
} else if score >= 50.0 {
DiskHealth::Warning
} else if score >= 20.0 {
DiskHealth::Critical
} else {
DiskHealth::Failed
};
// Estimate remaining life
disk.estimated_life_remaining = Some(score.max(0.0));
// Estimate days remaining via wear rate extrapolation
if let Some(hours) = disk.power_on_hours.filter(|h| *h > 100) {
if let Some(wear) = disk.wear_leveling_percent {
if wear > 5.0 {
let hours_per_percent = hours as f32 / wear;
let remaining_percent = 100.0 - wear;
let remaining_hours = hours_per_percent * remaining_percent;
disk.estimated_days_remaining = Some((remaining_hours / 24.0) as u32);
}
} else if let Some(pct) = disk.nvme_percentage_used {
if pct > 5 {
let hours_per_percent = hours as f32 / pct as f32;
let remaining_percent = 100.0 - pct as f32;
let remaining_hours = hours_per_percent * remaining_percent;
disk.estimated_days_remaining = Some((remaining_hours / 24.0) as u32);
}
}
}
// Check SMART attributes for pre-fail conditions
for attr in &disk.attributes {
// An unread threshold cannot trip, and is not a threshold of zero.
if attr.pre_fail && matches!(attr.threshold, Some(t) if t > 0 && attr.value <= t) {
disk.health = DiskHealth::Critical;
}
}
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), IronError> {
// NVMe drives from /sys/class/nvme
let nvme_base = std::path::Path::new("/sys/class/nvme");
if nvme_base.exists() {
if let Ok(entries) = std::fs::read_dir(nvme_base) {
for entry in entries.flatten() {
let ctrl_name = entry.file_name().to_string_lossy().to_string();
let base = entry.path();
let model = Self::read_sys(&base.join("model"));
let serial = Self::read_sys(&base.join("serial"));
let firmware = Self::read_sys(&base.join("firmware_rev"));
// Try to read smart-log from namespace
let device = format!("/dev/{}", ctrl_name);
let mut disk = SmartDiskInfo {
device,
model,
serial,
firmware,
media_type: DriveMediaType::NVMe,
capacity_bytes: None,
smart_passed: None,
health: DiskHealth::Unknown,
temperature_celsius: None,
power_on_hours: None,
power_cycle_count: None,
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: None,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
// Try nvme smart-log
if let Ok(output) = std::process::Command::new("nvme")
.args(["smart-log", &format!("/dev/{}n1", ctrl_name), "-o", "json"])
.output()
{
if let Ok(text) = String::from_utf8(output.stdout) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
Self::apply_nvme_smart_log(&mut disk, &val);
}
}
}
self.disks.push(disk);
}
}
}
// SATA/SCSI drives from /sys/block
// A listing that fails is an error. It used to be skipped, which read
// as a host with no SATA or SCSI drives.
let entries = std::fs::read_dir("/sys/block")
.map_err(|e| IronError::System(format!("cannot read /sys/block: {e}")))?;
{
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if !name.starts_with("sd") && !name.starts_with("hd") {
continue;
}
let base = entry.path();
let device = format!("/dev/{}", name);
// Detect rotational (1=HDD, 0=SSD). Any other value, including a
// sysfs file that could not be read, is not a medium we know.
let rotational = Self::read_sys(&base.join("queue/rotational"));
let media_type = match rotational.as_str() {
"0" => DriveMediaType::SSD,
"1" => DriveMediaType::HDD,
_ => DriveMediaType::Unknown,
};
// sysfs counts 512-byte sectors. An unreadable size is no size,
// not a zero-byte disk.
let capacity_bytes = Self::read_sys(&base.join("size"))
.parse::<u64>()
.ok()
.map(|sectors| sectors * 512);
let model = Self::read_sys(&base.join("device/model"));
let serial = Self::read_sys(&base.join("device/serial"))
.chars()
.filter(|c| !c.is_whitespace() || *c == ' ')
.collect::<String>()
.trim()
.to_string();
let mut disk = SmartDiskInfo {
device: device.clone(),
model,
serial,
firmware: Self::read_sys(&base.join("device/firmware_rev")),
media_type,
capacity_bytes,
smart_passed: None,
health: DiskHealth::Unknown,
temperature_celsius: None,
power_on_hours: None,
power_cycle_count: None,
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: None,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
// Try smartctl for detailed attributes
if let Ok(output) = std::process::Command::new("smartctl")
.args(["-H", "-A", "-j", &device])
.output()
{
if let Ok(text) = String::from_utf8(output.stdout) {
Self::parse_smartctl_json(&text, &mut disk);
}
}
self.disks.push(disk);
}
}
Ok(())
}
/// Fill an NVMe disk from the JSON that `nvme smart-log -o json` prints.
///
/// Every key is optional. `nvme-cli` omits what the drive did not report, and
/// an omitted key stays `None` here rather than becoming zero.
#[cfg(any(target_os = "linux", test))]
fn apply_nvme_smart_log(disk: &mut SmartDiskInfo, val: &serde_json::Value) {
// Absent keys stay `None`: `nvme smart-log` omits
// what the drive did not report, and the previous
// `.unwrap_or(0)` turned every omission into a
// reading of zero.
disk.temperature_celsius = val["temperature"]
.as_u64()
.or_else(|| val["composite_temperature"].as_u64())
.map(|t| if t > 273 { (t - 273) as u32 } else { t as u32 });
disk.power_on_hours = val["power_on_hours"].as_u64();
disk.power_cycle_count = val["power_cycles"].as_u64();
disk.nvme_percentage_used = val["percent_used"].as_u64().map(|v| v as u8);
disk.nvme_available_spare = val["avail_spare"].as_u64().map(|v| v as u8);
// Percentages are one byte; a value that does not fit is not a reading.
disk.nvme_available_spare_threshold = val["spare_thresh"]
.as_u64()
.and_then(|v| u8::try_from(v).ok());
disk.nvme_controller_busy_time_minutes = val["controller_busy_time"].as_u64();
disk.nvme_unsafe_shutdowns = val["unsafe_shutdowns"].as_u64();
disk.nvme_critical_warning = val["critical_warning"]
.as_u64()
.and_then(|v| u8::try_from(v).ok());
disk.nvme_host_read_commands = val["host_read_commands"].as_u64();
disk.nvme_host_write_commands = val["host_write_commands"].as_u64();
disk.uncorrectable_errors = val["media_errors"].as_u64();
// NVMe reports data units of 512 bytes, in
// thousands.
disk.total_bytes_written = val["data_units_written"]
.as_u64()
.map(|units| units * 512_000);
disk.total_bytes_read = val["data_units_read"].as_u64().map(|units| units * 512_000);
}
#[cfg(any(target_os = "linux", test))]
fn parse_smartctl_json(text: &str, disk: &mut SmartDiskInfo) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(text) {
// The drive's own verdict. Absent when smartctl did not print one, and
// then it stays None rather than being read as a pass.
disk.smart_passed = val["smart_status"]["passed"].as_bool();
if let Some(attrs) = val["ata_smart_attributes"]["table"].as_array() {
for attr in attrs {
// An attribute missing any of these is left out rather than
// filled with zeros: a `value` of 0 is a reading, and a drive
// that did not publish one has not said it.
let (
Some(id),
Some(name),
Some(value),
Some(worst),
Some(thresh),
Some(raw_val),
Some(pre_fail),
) = (
attr["id"].as_u64(),
attr["name"].as_str(),
attr["value"].as_u64(),
attr["worst"].as_u64(),
attr["thresh"].as_u64(),
attr["raw"]["value"].as_u64(),
attr["flags"]["prefailure"].as_bool(),
)
else {
continue;
};
let id = id as u16;
let name = name.to_string();
// Each arm here means the drive actually published that
// attribute, so `Some` is the truthful wrapper — unlike the
// struct's defaults, which stay `None` for attributes the
// drive never reported.
match id {
5 => disk.reallocated_sectors = Some(raw_val), // Reallocated_Sector_Ct
9 => disk.power_on_hours = Some(raw_val), // Power_On_Hours
12 => disk.power_cycle_count = Some(raw_val), // Power_Cycle_Count
177 | 233 => {
// Wear_Leveling_Count or Media_Wearout_Indicator
disk.wear_leveling_percent = Some(100.0 - value as f32);
}
194 | 190 => disk.temperature_celsius = Some(raw_val as u32), // Temperature
197 => disk.pending_sectors = Some(raw_val), // Current_Pending_Sector
198 => disk.uncorrectable_errors = Some(raw_val), // Offline_Uncorrectable
241 => disk.total_bytes_written = Some(raw_val * 512), // Total_LBAs_Written
242 => disk.total_bytes_read = Some(raw_val * 512), // Total_LBAs_Read
_ => {}
}
disk.attributes.push(SmartAttribute {
id,
name,
value,
worst,
threshold: Some(thresh),
raw_value: raw_val,
pre_fail,
});
}
}
}
}
#[cfg(target_os = "linux")]
fn read_sys(path: &std::path::Path) -> String {
std::fs::read_to_string(path)
.unwrap_or_default()
.trim()
.to_string()
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
// Use Get-PhysicalDisk + Get-StorageReliabilityCounter.
//
// This is the enumeration, not an enrichment: a failure here
// produced an empty disk list, and an empty disk list from a
// health reader reads as "no drives to worry about".
let json = crate::core::command::capture_json(
"powershell",
&[
"-NoProfile",
"-Command",
r#"
Get-PhysicalDisk -ErrorAction Stop | ForEach-Object {
$disk = $_
$rel = $_ | Get-StorageReliabilityCounter -ErrorAction SilentlyContinue
[PSCustomObject]@{
DeviceId = $disk.DeviceId
FriendlyName = $disk.FriendlyName
Model = $disk.Model
SerialNumber = $disk.SerialNumber
FirmwareVersion = $disk.FirmwareVersion
MediaType = $disk.MediaType
BusType = $disk.BusType
Size = $disk.Size
HealthStatus = $disk.HealthStatus
Temperature = if ($rel) { $rel.Temperature } else { $null }
PowerOnHours = if ($rel) { $rel.PowerOnHours } else { $null }
PowerCycleCount = if ($rel) { $rel.StartStopCycleCount } else { $null }
ReadErrorsTotal = if ($rel) { $rel.ReadErrorsTotal } else { $null }
WriteErrorsTotal = if ($rel) { $rel.WriteErrorsTotal } else { $null }
Wear = if ($rel) { $rel.Wear } else { $null }
}
} | ConvertTo-Json -Compress
"#,
],
)?;
// PowerShell prints nothing for an empty result, and it also prints
// nothing when the query failed without a non-zero exit. From here those
// cannot be told apart, so empty output is an error. It used to return
// Ok with no disks, which read as "no drives to worry about".
let Some(val) = json else {
return Err(IronError::System(
"Get-PhysicalDisk printed no output, so the disk list is unknown".to_string(),
));
};
{
{
{
let items = crate::core::command::json_items(&val);
for item in &items {
// Windows answers these separately: MediaType describes the
// storage medium ("SSD"), BusType the transport ("NVMe").
// An NVMe drive therefore reports MediaType=SSD, and
// matching on MediaType alone classified every NVMe drive
// on this machine as a plain SSD — which then made
// `nvme_info()` refuse to answer for them.
let media_str = item["MediaType"].as_str().unwrap_or("");
let bus_str = item["BusType"].as_str().unwrap_or("");
let media_type = if bus_str.eq_ignore_ascii_case("nvme") {
DriveMediaType::NVMe
} else {
match media_str {
"SSD" => DriveMediaType::SSD,
"HDD" => DriveMediaType::HDD,
"NVMe" | "SCM" => DriveMediaType::NVMe,
// Not a medium Windows named. The model string is a
// product name, not a measurement of the medium.
_ => DriveMediaType::Unknown,
}
};
let health_str = item["HealthStatus"].as_str().unwrap_or("");
let health = match health_str {
"Healthy" => DiskHealth::Good,
"Warning" => DiskHealth::Warning,
"Unhealthy" => DiskHealth::Critical,
_ => DiskHealth::Unknown,
};
let wear = item["Wear"].as_u64().map(|w| w as f32);
// `DeviceId` arrives as a JSON *string* ("1"), not a
// number. `as_u64()` returned None for every disk and the
// fallback made them all PhysicalDrive0 — four drives with
// one name, indistinguishable to any caller.
let device_id = item["DeviceId"]
.as_u64()
.or_else(|| item["DeviceId"].as_str()?.trim().parse().ok());
let Some(device_id) = device_id else {
// Without an id there is no way to name the device or
// match it to anything; a placeholder would collide.
continue;
};
let mut disk = SmartDiskInfo {
device: format!(r"\\.\PhysicalDrive{device_id}"),
model: item["Model"].as_str().unwrap_or("").trim().to_string(),
serial: item["SerialNumber"]
.as_str()
.unwrap_or("")
.trim()
.to_string(),
firmware: item["FirmwareVersion"]
.as_str()
.unwrap_or("")
.trim()
.to_string(),
media_type,
capacity_bytes: item["Size"].as_u64(),
smart_passed: None,
health,
// Null throughout when Get-StorageReliabilityCounter
// was unavailable, which is the unelevated case. These
// stay None rather than becoming zero.
temperature_celsius: item["Temperature"].as_u64().map(|t| t as u32),
power_on_hours: item["PowerOnHours"].as_u64(),
power_cycle_count: item["PowerCycleCount"].as_u64(),
// SATA reallocated/pending sector counts are not
// exposed by the Windows storage stack at all; they
// need a SMART passthrough this path does not make.
reallocated_sectors: None,
pending_sectors: None,
// Both counters, or no total. A sum with one side
// treated as zero is a count of half the errors, presented
// as all of them.
uncorrectable_errors: match (
item["ReadErrorsTotal"].as_u64(),
item["WriteErrorsTotal"].as_u64(),
) {
(Some(r), Some(w)) => Some(r + w),
_ => None,
},
wear_leveling_percent: wear,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: wear.map(|w| w as u8),
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
Self::fill_from_ata(&mut disk, device_id as u32);
self.disks.push(disk);
}
}
}
}
Ok(())
}
/// Fill in whatever the drive's own SMART structure reports, for the drives
/// that have one.
///
/// The PowerShell query above reaches its counters through
/// `Get-StorageReliabilityCounter`, which requires elevation and leaves every
/// one of them `None` for a normal user. `IOCTL_STORAGE_PREDICT_FAILURE` does
/// not, so on a SATA drive this is the difference between a full attribute
/// table and nothing at all. It also reaches reallocated and pending sector
/// counts, which the PowerShell path cannot report at any privilege level.
///
/// Only fields the reliability counters left empty are written. Where both can
/// answer, the elevated reading wins: it comes from the same drive by a path
/// that has been verified against hardware, and this one has not.
#[cfg(target_os = "windows")]
fn fill_from_ata(disk: &mut SmartDiskInfo, index: u32) {
// NVMe drives decline this ioctl, and their own log page has already been
// read by `disk::windows`. Asking anyway costs an open and a failed call
// per drive per refresh.
if disk.media_type == DriveMediaType::NVMe {
return;
}
let Ok(ata) = crate::disk::windows_ata::query(index) else {
return;
};
// The drive predicting its own failure outranks whatever HealthStatus
// Windows reported; the reverse is not true, because a drive that does not
// predict failure may still be one Windows has flagged.
if ata.predict_failure == Some(true) {
disk.health = DiskHealth::Failed;
}
let Some(smart) = ata.smart else {
return;
};
disk.temperature_celsius = disk.temperature_celsius.or(smart.temperature_celsius());
disk.power_on_hours = disk.power_on_hours.or(smart.power_on_hours());
disk.power_cycle_count = disk.power_cycle_count.or(smart.power_cycle_count());
disk.reallocated_sectors = disk.reallocated_sectors.or(smart.reallocated_sectors());
disk.pending_sectors = disk.pending_sectors.or(smart.pending_sectors());
disk.uncorrectable_errors = disk.uncorrectable_errors.or(smart.uncorrectable_sectors());
disk.wear_leveling_percent = disk.wear_leveling_percent.or(smart.wear_percent_used());
disk.total_bytes_written = disk.total_bytes_written.or(smart.total_bytes_written());
disk.total_bytes_read = disk.total_bytes_read.or(smart.total_bytes_read());
disk.attributes = smart
.attributes
.iter()
.map(|a| SmartAttribute {
id: u16::from(a.id),
name: a.name(),
value: u64::from(a.value),
worst: u64::from(a.worst),
// Not reachable through this ioctl — see `disk::windows_ata`.
threshold: None,
raw_value: a.raw,
pre_fail: a.pre_fail(),
})
.collect();
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), IronError> {
// Try smartmontools.
//
// `smartctl` is optional software, so its *absence* is not a failure --
// there is simply no SMART source, and `diskutil` below still
// enumerates the drives. A `smartctl` that is installed and exits
// non-zero is a different matter, and both used to be swallowed
// together into an empty disk list.
let scan = match std::process::Command::new("smartctl")
.args(["--scan", "-j"])
.output()
{
Ok(o) if o.status.success() => Some(o.stdout),
Ok(o) => {
return Err(IronError::CommandFailed(format!(
"smartctl --scan exited {}: {}",
o.status,
String::from_utf8_lossy(&o.stderr).trim()
)))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(IronError::CommandFailed(format!("smartctl: {e}"))),
};
if let Some(stdout) = scan {
if let Ok(text) = String::from_utf8(stdout) {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
if let Some(devices) = val["devices"].as_array() {
for dev in devices {
let name = dev["name"].as_str().unwrap_or_default();
if name.is_empty() {
continue;
}
let mut disk = SmartDiskInfo {
device: name.to_string(),
model: String::new(),
serial: String::new(),
firmware: String::new(),
media_type: DriveMediaType::Unknown,
capacity_bytes: None,
smart_passed: None,
health: DiskHealth::Unknown,
temperature_celsius: None,
power_on_hours: None,
power_cycle_count: None,
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: None,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
let dev_type = dev["type"].as_str().unwrap_or("");
disk.media_type = if dev_type.contains("nvme") {
DriveMediaType::NVMe
} else {
DriveMediaType::Unknown
};
// Get info
if let Ok(info_out) = std::process::Command::new("smartctl")
.args(["-i", "-A", "-j", name])
.output()
{
if let Ok(info_text) = String::from_utf8(info_out.stdout) {
if let Ok(info) =
serde_json::from_str::<serde_json::Value>(&info_text)
{
disk.model =
info["model_name"].as_str().unwrap_or("").to_string();
disk.serial = info["serial_number"]
.as_str()
.unwrap_or("")
.to_string();
disk.firmware = info["firmware_version"]
.as_str()
.unwrap_or("")
.to_string();
if let Some(temp) = info["temperature"]["current"].as_u64()
{
disk.temperature_celsius = Some(temp as u32);
}
if let Some(hours) = info["power_on_time"]["hours"].as_u64()
{
disk.power_on_hours = Some(hours);
}
}
}
}
self.disks.push(disk);
}
}
}
}
}
// Fallback: diskutil. Unlike `smartctl` this ships with macOS, so a
// failure to run it is a failure, not an absent optional tool.
if self.disks.is_empty() {
{
// Basic enumeration — just record device names
let text = crate::core::command::capture("diskutil", &["list", "-plist"])?;
// Whole disks only. A slice (`diskNsM`) is not a device of its
// own. The old filter matched the raw XML line, so `<string>`
// tags stayed in the name, and the `disk0`/`disk1` clauses could
// never match a line that ended in `</string>`.
for device in whole_disks_in_plist(&text) {
self.disks.push(SmartDiskInfo {
device,
model: String::new(),
serial: String::new(),
firmware: String::new(),
media_type: DriveMediaType::Unknown,
capacity_bytes: None,
smart_passed: None,
health: DiskHealth::Unknown,
temperature_celsius: None,
power_on_hours: None,
power_cycle_count: None,
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: None,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
});
}
}
}
Ok(())
}
}
/// The whole-disk devices named in the text of `diskutil list -plist`.
///
/// The output is an XML plist, and each name is the text between a `<string>`
/// and its `</string>`. A whole disk is `diskN`, optionally written with a
/// `/dev/` prefix; a slice is `diskNsM` and is not a device of its own. A disk
/// is named in more than one array, so each device is returned once.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn whole_disks_in_plist(plist: &str) -> Vec<String> {
let mut disks: Vec<String> = Vec::new();
for value in plist.split("<string>").skip(1) {
let Some((name, _)) = value.split_once("</string>") else {
continue;
};
let name = name.trim();
let bare = name.strip_prefix("/dev/").unwrap_or(name);
let Some(digits) = bare.strip_prefix("disk") else {
continue;
};
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
let device = format!("/dev/{bare}");
if !disks.contains(&device) {
disks.push(device);
}
}
disks
}
impl Default for SmartMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self { disks: Vec::new() })
}
}
impl std::fmt::Display for DiskHealth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Good => write!(f, "Good"),
Self::Warning => write!(f, "Warning"),
Self::Critical => write!(f, "Critical"),
Self::Failed => write!(f, "Failed"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Constructing the monitor either enumerates or says why it could not.
///
/// See the identically-shaped tests in `camera`, `usb` and the rest: this
/// asserted `is_ok()`, which was true by construction while `refresh` could
/// not fail. A failure must carry a reason, because a reason is the whole
/// difference between "this machine has no drives" and "nobody looked" --
/// and for a health reader the second answer masquerading as the first is
/// the worst way to be wrong.
#[test]
fn test_smart_monitor_creation() {
match SmartMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_smart_monitor_default() {
let monitor = SmartMonitor::default();
let _ = monitor.disks();
let _ = monitor.unhealthy_disks();
let _ = monitor.max_temperature();
}
/// Two calls in quick succession must be served by one collector run. A fresh
/// sweep allocates a new list, so a shared allocation is the cheapest thing a
/// test can observe that distinguishes the two.
#[test]
fn consecutive_calls_share_one_collector_run() {
let first = SmartMonitor::cached_disks();
let second = SmartMonitor::cached_disks();
assert!(Arc::ptr_eq(&first, &second));
}
/// The window has to be shorter than the polling interval the documentation
/// recommends, or a caller polling as advised would be served the same reading
/// twice and never know.
#[test]
fn the_cache_window_is_shorter_than_a_polling_interval() {
assert!(CACHE_MAX_AGE < Duration::from_secs(60));
}
#[test]
fn test_health_inference() {
let mut disk = SmartDiskInfo {
device: "test".into(),
model: "Test SSD".into(),
serial: "ABC".into(),
firmware: "1.0".into(),
media_type: DriveMediaType::SSD,
capacity_bytes: Some(500_000_000_000),
smart_passed: None,
health: DiskHealth::Unknown,
temperature_celsius: Some(35),
power_on_hours: Some(5000),
power_cycle_count: Some(1000),
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: Some(10.0),
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
SmartMonitor::infer_health(&mut disk);
assert_eq!(disk.health, DiskHealth::Good);
assert!(disk.estimated_life_remaining.unwrap() > 80.0);
}
/// A drive that predicts its own failure can still have clean-looking
/// counters: SMART trips on thresholds this code cannot read. Scoring those
/// counters graded such a drive `Good` and discarded the only reading that
/// mattered.
#[test]
fn a_self_reported_failure_survives_inference() {
let mut disk = SmartDiskInfo {
device: r"\\.\PhysicalDrive0".into(),
model: "Test SSD".into(),
serial: "ABC".into(),
firmware: "1.0".into(),
media_type: DriveMediaType::SSD,
capacity_bytes: Some(500_000_000_000),
smart_passed: None,
// What `IOCTL_STORAGE_PREDICT_FAILURE` reporting a prediction sets.
health: DiskHealth::Failed,
temperature_celsius: Some(30),
power_on_hours: Some(100),
power_cycle_count: Some(10),
reallocated_sectors: Some(0),
pending_sectors: Some(0),
uncorrectable_errors: Some(0),
wear_leveling_percent: Some(1.0),
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
SmartMonitor::infer_health(&mut disk);
assert_eq!(disk.health, DiskHealth::Failed);
}
#[test]
fn test_critical_health() {
let mut disk = SmartDiskInfo {
device: "test".into(),
model: "Test HDD".into(),
serial: "DEF".into(),
firmware: "2.0".into(),
media_type: DriveMediaType::HDD,
capacity_bytes: Some(1_000_000_000_000),
smart_passed: None,
health: DiskHealth::Unknown,
temperature_celsius: Some(72),
power_on_hours: Some(80000),
power_cycle_count: Some(5000),
reallocated_sectors: Some(50),
pending_sectors: Some(10),
uncorrectable_errors: Some(5),
wear_leveling_percent: None,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
SmartMonitor::infer_health(&mut disk);
assert!(matches!(
disk.health,
DiskHealth::Critical | DiskHealth::Failed
));
}
#[test]
fn test_serialization() {
let disk = SmartDiskInfo {
device: "/dev/sda".into(),
model: "Samsung".into(),
serial: "S123".into(),
firmware: "1.0".into(),
media_type: DriveMediaType::SSD,
capacity_bytes: Some(500_000_000_000),
smart_passed: None,
health: DiskHealth::Good,
temperature_celsius: Some(35),
power_on_hours: Some(1000),
power_cycle_count: Some(100),
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: Some(5.0),
total_bytes_written: Some(1_000_000_000),
total_bytes_read: Some(2_000_000_000),
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: Some(95.0),
estimated_days_remaining: Some(3650),
};
let json = serde_json::to_string(&disk).unwrap();
assert!(json.contains("Samsung"));
let _: SmartDiskInfo = serde_json::from_str(&json).unwrap();
}
/// A drive whose counters could not be read must not be graded.
///
/// Every counter used to be a plain integer, so a drive whose reliability
/// counters were unavailable — the unelevated Windows case, which is the
/// common one — arrived at `infer_health` as zeros. Zero reallocated sectors,
/// zero errors and zero degrees took no penalties, scored 100, and produced a
/// confident `Good` plus an "estimated life remaining: 100%" derived from no
/// measurement whatsoever.
#[test]
fn a_drive_with_no_readable_counters_is_not_graded_healthy() {
let mut disk = SmartDiskInfo {
device: r"\.\PhysicalDrive0".into(),
model: "Unreadable".into(),
serial: String::new(),
firmware: String::new(),
media_type: DriveMediaType::NVMe,
capacity_bytes: None,
smart_passed: None,
// What the platform itself said; the scorer must not overwrite it.
health: DiskHealth::Unknown,
temperature_celsius: None,
power_on_hours: None,
power_cycle_count: None,
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: None,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
};
SmartMonitor::infer_health(&mut disk);
assert_eq!(
disk.health,
DiskHealth::Unknown,
"a drive with no readable counters was graded from an empty score"
);
assert!(
disk.estimated_life_remaining.is_none(),
"a life estimate was published for a drive nothing was read from"
);
}
fn blank_nvme_disk() -> SmartDiskInfo {
SmartDiskInfo {
device: "/dev/nvme0".into(),
model: "Test NVMe".into(),
serial: "NVME1".into(),
firmware: "1.0".into(),
media_type: DriveMediaType::NVMe,
capacity_bytes: None,
smart_passed: None,
health: DiskHealth::Unknown,
temperature_celsius: None,
power_on_hours: None,
power_cycle_count: None,
reallocated_sectors: None,
pending_sectors: None,
uncorrectable_errors: None,
wear_leveling_percent: None,
total_bytes_written: None,
total_bytes_read: None,
nvme_percentage_used: None,
nvme_available_spare: None,
nvme_available_spare_threshold: None,
nvme_controller_busy_time_minutes: None,
nvme_unsafe_shutdowns: None,
nvme_critical_warning: None,
nvme_host_read_commands: None,
nvme_host_write_commands: None,
attributes: Vec::new(),
estimated_life_remaining: None,
estimated_days_remaining: None,
}
}
/// The drive's own verdict is `smart_status.passed`. A drive that says FAILED
/// must read as FAILED, and a smartctl output without the key must read as
/// unread, not as a pass.
#[test]
fn smartctl_overall_health_verdict_is_read_and_absent_stays_unread() {
let failed =
r#"{"smart_status": {"passed": false}, "ata_smart_attributes": {"table": []}}"#;
let passed = r#"{"smart_status": {"passed": true}}"#;
let absent = r#"{"ata_smart_attributes": {"table": []}}"#;
let mut disk = blank_nvme_disk();
SmartMonitor::parse_smartctl_json(failed, &mut disk);
assert_eq!(disk.smart_passed, Some(false));
let mut disk = blank_nvme_disk();
SmartMonitor::parse_smartctl_json(passed, &mut disk);
assert_eq!(disk.smart_passed, Some(true));
let mut disk = blank_nvme_disk();
SmartMonitor::parse_smartctl_json(absent, &mut disk);
assert_eq!(disk.smart_passed, None);
}
/// Output shaped like `nvme smart-log /dev/nvme0n1 -o json` from nvme-cli. The
/// keys are nvme-cli's own; the values describe a healthy drive.
#[test]
fn nvme_smart_log_json_fills_spare_threshold_busy_time_and_unsafe_shutdowns() {
let text = concat!(
"{\"critical_warning\" : 0,",
"\"temperature\" : 312,",
"\"avail_spare\" : 98,",
"\"spare_thresh\" : 10,",
"\"percent_used\" : 3,",
"\"endurance_group_critical_warning_summary\" : 0,",
"\"data_units_read\" : 9876543,",
"\"data_units_written\" : 4567890,",
"\"host_read_commands\" : 123456789,",
"\"host_write_commands\" : 87654321,",
"\"controller_busy_time\" : 412,",
"\"power_cycles\" : 233,",
"\"power_on_hours\" : 5120,",
"\"unsafe_shutdowns\" : 17,",
"\"media_errors\" : 0,",
"\"num_err_log_entries\" : 0}"
);
let val: serde_json::Value = serde_json::from_str(text).unwrap();
let mut disk = blank_nvme_disk();
SmartMonitor::apply_nvme_smart_log(&mut disk, &val);
assert_eq!(disk.nvme_available_spare, Some(98));
assert_eq!(disk.nvme_available_spare_threshold, Some(10));
assert_eq!(disk.nvme_controller_busy_time_minutes, Some(412));
assert_eq!(disk.nvme_unsafe_shutdowns, Some(17));
assert_eq!(disk.nvme_percentage_used, Some(3));
assert_eq!(disk.nvme_critical_warning, Some(0));
assert_eq!(disk.nvme_host_read_commands, Some(123_456_789));
assert_eq!(disk.nvme_host_write_commands, Some(87_654_321));
}
/// A drive or nvme-cli that omits these keys must leave them unread, not zero.
#[test]
fn nvme_smart_log_keys_that_are_absent_stay_unread() {
let text = concat!("{\"avail_spare\" : 100,", "\"percent_used\" : 0}");
let val: serde_json::Value = serde_json::from_str(text).unwrap();
let mut disk = blank_nvme_disk();
SmartMonitor::apply_nvme_smart_log(&mut disk, &val);
assert_eq!(disk.nvme_available_spare, Some(100));
assert_eq!(disk.nvme_available_spare_threshold, None);
assert_eq!(disk.nvme_controller_busy_time_minutes, None);
assert_eq!(disk.nvme_unsafe_shutdowns, None);
assert_eq!(disk.nvme_critical_warning, None);
assert_eq!(disk.nvme_host_read_commands, None);
assert_eq!(disk.nvme_host_write_commands, None);
}
/// The fallback used to match raw XML lines, so the `<string>` tags stayed
/// in the name and no clause could match. The names are the text between
/// the tags, and a slice is left out.
#[test]
fn diskutil_plist_names_whole_disks_only() {
let plist = concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n",
"<plist version=\"1.0\">\n",
"<dict>\n",
"<key>AllDisks</key>\n",
"<array>\n",
"<string>disk0</string>\n",
"<string>disk0s1</string>\n",
"<string>disk1</string>\n",
"<string>disk1s1</string>\n",
"</array>\n",
"<key>WholeDisks</key>\n",
"<array>\n",
"<string>disk0</string>\n",
"<string>disk1</string>\n",
"</array>\n",
"<key>AllDisksAndPartitions</key>\n",
"<array>\n",
"<dict>\n",
"<key>DeviceIdentifier</key>\n",
"<string>disk0</string>\n",
"</dict>\n",
"</array>\n",
"</dict>\n",
"</plist>\n",
);
assert_eq!(
whole_disks_in_plist(plist),
vec!["/dev/disk0".to_string(), "/dev/disk1".to_string()]
);
}
#[test]
fn diskutil_plist_accepts_dev_prefixed_names_and_rejects_others() {
let plist = concat!(
"<string>/dev/disk2</string>\n",
"<string>/dev/disk2s1</string>\n",
"<string>disk</string>\n",
"<string>diskimage</string>\n",
"<string>/dev/disk12</string>\n",
"<key>DiskUUID</key>\n",
);
assert_eq!(
whole_disks_in_plist(plist),
vec!["/dev/disk2".to_string(), "/dev/disk12".to_string()]
);
assert!(whole_disks_in_plist("<plist version=\"1.0\"></plist>").is_empty());
}
}