ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
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
//! Block I/O scheduler monitoring and analysis.
//!
//! Detects and reports active I/O schedulers per block device (mq-deadline,
//! BFQ, kyber, none), queue depth, rotational vs SSD classification,
//! I/O stats (IOPS, throughput, latency), and scheduler tuning parameters.
//!
//! ## Platform Support
//!
//! - **Linux**: `/sys/block/*/queue/scheduler`, `/sys/block/*/stat`, `/proc/diskstats`
//! - **Windows**: I/O priority via performance counters
//! - **macOS**: IOKit disk stats

use crate::error::IronError;
use serde::{Deserialize, Serialize};

/// I/O scheduler type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IoSchedulerType {
    /// Multi-Queue Deadline.
    MqDeadline,
    /// Budget Fair Queueing.
    Bfq,
    /// Kyber (low-latency).
    Kyber,
    /// No scheduler (none/noop — direct dispatch).
    None,
    /// Legacy CFQ (pre-5.0 kernels).
    Cfq,
    /// Legacy Deadline.
    Deadline,
    /// Legacy Noop.
    Noop,
    Unknown,
}

impl std::fmt::Display for IoSchedulerType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MqDeadline => write!(f, "mq-deadline"),
            Self::Bfq => write!(f, "bfq"),
            Self::Kyber => write!(f, "kyber"),
            Self::None => write!(f, "none"),
            Self::Cfq => write!(f, "cfq"),
            Self::Deadline => write!(f, "deadline"),
            Self::Noop => write!(f, "noop"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

/// Block device I/O statistics.
///
/// **Every field is `Option` because this struct is built on platforms that
/// cannot populate it at all.** `read_iops_from_stats` below already said so:
/// a `read_time_ms` of zero means "never served a read" *or* "the counters
/// were never populated -- which is every platform but Linux", and it guarded
/// with `== 0` because the type gave it no way to ask which. That guard also
/// discarded the genuine zero it was trying to preserve.
///
/// On Linux the whole set comes from one `/sys/block/*/stat` line, so they
/// succeed or fail together; they are individually optional because the line
/// gained fields over time (discards arrived in 4.18) and a short line should
/// leave the later ones absent rather than zero.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct IoStats {
    /// Reads completed.
    pub reads_completed: Option<u64>,
    /// Reads merged.
    pub reads_merged: Option<u64>,
    /// Sectors read.
    pub sectors_read: Option<u64>,
    /// Time reading (ms).
    pub read_time_ms: Option<u64>,
    /// Writes completed.
    pub writes_completed: Option<u64>,
    /// Writes merged.
    pub writes_merged: Option<u64>,
    /// Sectors written.
    pub sectors_written: Option<u64>,
    /// Time writing (ms).
    pub write_time_ms: Option<u64>,
    /// Current I/O in flight.
    pub in_flight: Option<u64>,
    /// Time doing I/O (ms).
    pub io_time_ms: Option<u64>,
    /// Weighted time doing I/O (ms).
    pub weighted_io_time_ms: Option<u64>,
    /// Discards completed (TRIM).
    pub discards_completed: Option<u64>,
}

/// Block device I/O scheduler info.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlockDeviceIo {
    /// Device name (e.g. "sda", "nvme0n1").
    pub name: String,
    /// Active I/O scheduler, or `None` where `queue/scheduler` was not read.
    pub scheduler: Option<IoSchedulerType>,
    /// Available schedulers, or `None` where `queue/scheduler` was not read.
    pub available_schedulers: Option<Vec<IoSchedulerType>>,
    /// Whether this is a rotational (HDD) device. `None` when
    /// `queue/rotational` was not readable — which is not the same as an SSD.
    pub rotational: Option<bool>,
    /// Queue depth (nr_requests). `None` when not readable.
    pub queue_depth: Option<u32>,
    /// Logical block size. `None` when not readable — never 512.
    pub logical_block_size: Option<u32>,
    /// Physical block size. `None` when not readable — never 512. A 4Kn drive
    /// reports 4096 for both and an Advanced Format drive 512 over 4096, which
    /// is the distinction these two fields exist to carry.
    pub physical_block_size: Option<u32>,
    /// Whether device supports discard (TRIM). `None` when not readable.
    pub discard_support: Option<bool>,
    /// I/O statistics.
    pub stats: IoStats,
    /// Device size in bytes, or `None` where `size` was not readable.
    ///
    /// The third struct in this crate to hold a disk's size from the same
    /// sysfs `size` attribute, and the third to have flattened it with
    /// `.unwrap_or(0)`. See `disk::DiskInfo::capacity` and
    /// `smart::SmartDiskInfo::capacity_bytes`.
    pub size_bytes: Option<u64>,
    /// Model / product name, or `None` where `device/model` was not read. An
    /// empty file is no model either.
    pub model: Option<String>,
}

impl BlockDeviceIo {
    /// Read operations per second of time the device spent reading, over the
    /// whole of its uptime. `None` when it has not spent any.
    ///
    /// **Two things this is not.** It is not a current rate: `/sys/block/*/stat`
    /// gives counters cumulative since boot, so this is a lifetime average and
    /// will barely move under a burst of load. A caller wanting current IOPS
    /// must read [`IoStats`] twice and difference it. And the denominator is
    /// time *spent* reading rather than elapsed time, so the figure is IOPS
    /// while busy, which on a mostly-idle device is far above its IOPS.
    ///
    /// `None` rather than the `0.0` this returned before, because
    /// `read_time_ms == 0` had two meanings and neither is "this device does
    /// zero reads per second": either it has genuinely never served a read, or
    /// the counters were never populated -- which is every platform but Linux,
    /// where [`IoStats`] was constructed with zeros.
    ///
    /// **Those two are now distinguishable**, and this asks the right question
    /// of each: `None` if the counters were not read, and `None` again if the
    /// device has spent no time reading -- but the second is now a division
    /// guard rather than a proxy for the first.
    pub fn read_iops_from_stats(&self) -> Option<f64> {
        let (reads, time_ms) = (self.stats.reads_completed?, self.stats.read_time_ms?);
        if time_ms == 0 {
            return None;
        }
        Some(reads as f64 / (time_ms as f64 / 1000.0))
    }

    /// Write operations per second of time spent writing. See
    /// [`Self::read_iops_from_stats`] for what this figure is and is not.
    pub fn write_iops_from_stats(&self) -> Option<f64> {
        let (writes, time_ms) = (self.stats.writes_completed?, self.stats.write_time_ms?);
        if time_ms == 0 {
            return None;
        }
        Some(writes as f64 / (time_ms as f64 / 1000.0))
    }

    /// Read throughput in MB/s over time spent reading. See
    /// [`Self::read_iops_from_stats`] for what this figure is and is not.
    pub fn read_throughput_mbs(&self) -> Option<f64> {
        let (sectors, time_ms) = (self.stats.sectors_read?, self.stats.read_time_ms?);
        if time_ms == 0 {
            return None;
        }
        Some((sectors as f64 * 512.0) / (time_ms as f64 / 1000.0) / 1_000_000.0)
    }

    /// Whether the scheduler is optimal for this device type, or `None` when
    /// `rotational` was not read — the answer depends entirely on it, so there
    /// is no verdict to give without it.
    pub fn scheduler_optimal(&self) -> Option<bool> {
        // No scheduler read is no scheduler to judge.
        let scheduler = self.scheduler?;
        let optimal = if self.rotational? {
            // HDDs benefit from BFQ or mq-deadline
            matches!(
                scheduler,
                IoSchedulerType::Bfq | IoSchedulerType::MqDeadline
            )
        } else {
            // SSDs/NVMe work best with none, mq-deadline, or kyber
            matches!(
                scheduler,
                IoSchedulerType::None | IoSchedulerType::MqDeadline | IoSchedulerType::Kyber
            )
        };
        Some(optimal)
    }
}

/// I/O scheduler overview.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IoSchedulerOverview {
    /// All block devices.
    pub devices: Vec<BlockDeviceIo>,
    /// Total devices.
    pub total_devices: u32,
    /// Devices with non-optimal schedulers.
    pub non_optimal_count: u32,
    /// Recommendations.
    pub recommendations: Vec<String>,
}

/// I/O scheduler monitor.
pub struct IoSchedulerMonitor {
    overview: IoSchedulerOverview,
}

impl IoSchedulerMonitor {
    /// Create a new I/O scheduler monitor.
    pub fn new() -> Result<Self, IronError> {
        let overview = Self::scan()?;
        Ok(Self { overview })
    }

    /// Refresh.
    pub fn refresh(&mut self) -> Result<(), IronError> {
        self.overview = Self::scan()?;
        Ok(())
    }

    /// Get overview.
    pub fn overview(&self) -> &IoSchedulerOverview {
        &self.overview
    }

    /// Get devices.
    pub fn devices(&self) -> &[BlockDeviceIo] {
        &self.overview.devices
    }

    /// Get device by name.
    pub fn device(&self, name: &str) -> Option<&BlockDeviceIo> {
        self.overview.devices.iter().find(|d| d.name == name)
    }

    #[cfg(target_os = "linux")]
    fn scan() -> Result<IoSchedulerOverview, IronError> {
        let block_path = std::path::Path::new("/sys/block");
        let mut devices = Vec::new();

        // A missing `/sys/block` used to return an empty overview, which read
        // as "this machine has no block devices". It is a reader that could
        // not run, so it says so, as the non-Linux stubs do.
        if !block_path.exists() {
            return Err(IronError::UnsupportedPlatform(
                "`/sys/block` is not present, so block devices cannot be enumerated here".into(),
            ));
        }

        let entries = std::fs::read_dir(block_path).map_err(IronError::Io)?;

        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();

            // Skip loop, ram, dm devices
            if name.starts_with("loop") || name.starts_with("ram") || name.starts_with("dm-") {
                continue;
            }

            let dev_path = entry.path();
            let queue_path = dev_path.join("queue");

            if !queue_path.exists() {
                continue;
            }

            // Read scheduler
            let (scheduler, available) = Self::read_scheduler(&queue_path);

            // Rotational
            let rotational = Self::read_sysfs_u32(&queue_path.join("rotational")).map(|v| v == 1);

            // Queue depth
            let queue_depth = Self::read_sysfs_u32(&queue_path.join("nr_requests"));

            // Block sizes
            let logical_block_size = Self::read_sysfs_u32(&queue_path.join("logical_block_size"));
            let physical_block_size = Self::read_sysfs_u32(&queue_path.join("physical_block_size"));

            // Discard support
            let discard_support =
                Self::read_sysfs_u32(&queue_path.join("discard_max_bytes")).map(|v| v > 0);

            // Stats
            let stats = Self::read_stats(&dev_path);

            // Size (in 512-byte sectors)
            let size_bytes = Self::read_sysfs_u64(&dev_path.join("size")).map(|s| s * 512);

            // Model
            // An unread model used to be `""`, which read as a device with a
            // blank product name. It is `None` now, as is an empty file.
            let model = std::fs::read_to_string(dev_path.join("device/model"))
                .ok()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty());

            devices.push(BlockDeviceIo {
                name,
                scheduler,
                available_schedulers: available,
                rotational,
                queue_depth,
                logical_block_size,
                physical_block_size,
                discard_support,
                stats,
                size_bytes,
                model,
            });
        }

        let total = devices.len() as u32;
        // A device whose `rotational` was not read is counted neither optimal
        // nor not: there is nothing to compare its scheduler against.
        let non_optimal = devices
            .iter()
            .filter(|d| d.scheduler_optimal() == Some(false))
            .count() as u32;

        let mut recommendations = Vec::new();
        for dev in &devices {
            if let (Some(false), Some(current)) = (dev.scheduler_optimal(), dev.scheduler) {
                let rotational = dev.rotational == Some(true);
                let suggested = if rotational { "bfq" } else { "none" };
                recommendations.push(format!(
                    "{}: using '{}' scheduler; '{}' may be better for {} devices",
                    dev.name,
                    current,
                    suggested,
                    if rotational { "rotational" } else { "SSD/NVMe" }
                ));
            }
        }

        Ok(IoSchedulerOverview {
            devices,
            total_devices: total,
            non_optimal_count: non_optimal,
            recommendations,
        })
    }

    #[cfg(target_os = "linux")]
    fn read_scheduler(
        queue_path: &std::path::Path,
    ) -> (Option<IoSchedulerType>, Option<Vec<IoSchedulerType>>) {
        // An unreadable `scheduler` file is no answer. It used to parse as the
        // empty string: an Unknown active scheduler and an empty list.
        let Ok(content) = std::fs::read_to_string(queue_path.join("scheduler")) else {
            return (None, None);
        };

        let mut active = IoSchedulerType::Unknown;
        let mut available = Vec::new();

        for part in content.split_whitespace() {
            let (name, is_active) = if part.starts_with('[') && part.ends_with(']') {
                (part.trim_matches(|c| c == '[' || c == ']'), true)
            } else {
                (part, false)
            };

            let sched = match name {
                "mq-deadline" => IoSchedulerType::MqDeadline,
                "bfq" => IoSchedulerType::Bfq,
                "kyber" => IoSchedulerType::Kyber,
                "none" => IoSchedulerType::None,
                "cfq" => IoSchedulerType::Cfq,
                "deadline" => IoSchedulerType::Deadline,
                "noop" => IoSchedulerType::Noop,
                _ => IoSchedulerType::Unknown,
            };

            available.push(sched);
            if is_active {
                active = sched;
            }
        }

        (Some(active), Some(available))
    }

    #[cfg(target_os = "linux")]
    /// Parse `/sys/block/<dev>/stat`.
    ///
    /// `unwrap_or_default()` on the file read meant a device with **no stat
    /// file at all** produced an empty string, no fields, and twelve counters
    /// of zero -- a device reporting it had served no I/O since boot. Every
    /// field is now taken positionally with `.copied()`, so a missing file
    /// leaves all twelve absent and a short line leaves only its tail absent.
    /// The `stat` line gained discard counters in 4.18 and that is exactly the
    /// short-line case.
    fn read_stats(dev_path: &std::path::Path) -> IoStats {
        let Ok(content) = std::fs::read_to_string(dev_path.join("stat")) else {
            return IoStats::default();
        };
        let parts: Vec<u64> = content
            .split_whitespace()
            .filter_map(|s| s.parse().ok())
            .collect();

        IoStats {
            reads_completed: parts.first().copied(),
            reads_merged: parts.get(1).copied(),
            sectors_read: parts.get(2).copied(),
            read_time_ms: parts.get(3).copied(),
            writes_completed: parts.get(4).copied(),
            writes_merged: parts.get(5).copied(),
            sectors_written: parts.get(6).copied(),
            write_time_ms: parts.get(7).copied(),
            in_flight: parts.get(8).copied(),
            io_time_ms: parts.get(9).copied(),
            weighted_io_time_ms: parts.get(10).copied(),
            discards_completed: parts.get(11).copied(),
        }
    }

    #[cfg(target_os = "linux")]
    fn read_sysfs_u32(path: &std::path::Path) -> Option<u32> {
        std::fs::read_to_string(path)
            .ok()
            .and_then(|s| s.trim().parse().ok())
    }

    #[cfg(target_os = "linux")]
    fn read_sysfs_u64(path: &std::path::Path) -> Option<u64> {
        std::fs::read_to_string(path)
            .ok()
            .and_then(|s| s.trim().parse().ok())
    }

    #[cfg(target_os = "windows")]
    fn scan() -> Result<IoSchedulerOverview, IronError> {
        // Returning an empty overview here made "this platform cannot
        // answer" indistinguishable from "this machine has none", which
        // is the same defect RAPL shipped once. The reason travels with
        // the error so a caller can report it.
        Err(IronError::UnsupportedPlatform(
            "the block I/O scheduler is read from `/sys/block/*/queue/scheduler`, which Windows does not expose"
                .into(),
        ))
    }

    #[cfg(target_os = "macos")]
    fn scan() -> Result<IoSchedulerOverview, IronError> {
        // Returning an empty overview here made "this platform cannot
        // answer" indistinguishable from "this machine has none", which
        // is the same defect RAPL shipped once. The reason travels with
        // the error so a caller can report it.
        Err(IronError::UnsupportedPlatform(
            "the block I/O scheduler is read from `/sys/block/*/queue/scheduler`, which macOS does not expose"
                .into(),
        ))
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn scan() -> Result<IoSchedulerOverview, IronError> {
        // Returning an empty overview here made "this platform cannot
        // answer" indistinguishable from "this machine has none", which
        // is the same defect RAPL shipped once. The reason travels with
        // the error so a caller can report it.
        Err(IronError::UnsupportedPlatform(
            "the block I/O scheduler is read from `/sys/block/*/queue/scheduler`, which this platform does not expose"
                .into(),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_scheduler_display() {
        assert_eq!(IoSchedulerType::MqDeadline.to_string(), "mq-deadline");
        assert_eq!(IoSchedulerType::Bfq.to_string(), "bfq");
        assert_eq!(IoSchedulerType::None.to_string(), "none");
    }

    #[test]
    fn test_optimal_ssd() {
        let dev = BlockDeviceIo {
            name: "nvme0n1".into(),
            scheduler: Some(IoSchedulerType::None),
            available_schedulers: Some(vec![IoSchedulerType::None, IoSchedulerType::MqDeadline]),
            rotational: Some(false),
            queue_depth: Some(256),
            logical_block_size: Some(512),
            physical_block_size: Some(4096),
            discard_support: Some(true),
            stats: IoStats {
                reads_completed: Some(0),
                reads_merged: Some(0),
                sectors_read: Some(0),
                read_time_ms: Some(0),
                writes_completed: Some(0),
                writes_merged: Some(0),
                sectors_written: Some(0),
                write_time_ms: Some(0),
                in_flight: Some(0),
                io_time_ms: Some(0),
                weighted_io_time_ms: Some(0),
                discards_completed: Some(0),
            },
            size_bytes: Some(1_000_000_000_000),
            model: Some("Samsung 990 Pro".into()),
        };
        assert_eq!(dev.scheduler_optimal(), Some(true));
    }

    #[test]
    fn test_non_optimal_hdd() {
        let dev = BlockDeviceIo {
            name: "sda".into(),
            scheduler: Some(IoSchedulerType::None),
            available_schedulers: Some(vec![IoSchedulerType::None, IoSchedulerType::Bfq]),
            rotational: Some(true),
            queue_depth: Some(128),
            logical_block_size: Some(512),
            physical_block_size: Some(512),
            discard_support: Some(false),
            stats: IoStats {
                reads_completed: Some(0),
                reads_merged: Some(0),
                sectors_read: Some(0),
                read_time_ms: Some(0),
                writes_completed: Some(0),
                writes_merged: Some(0),
                sectors_written: Some(0),
                write_time_ms: Some(0),
                in_flight: Some(0),
                io_time_ms: Some(0),
                weighted_io_time_ms: Some(0),
                discards_completed: Some(0),
            },
            size_bytes: Some(2_000_000_000_000),
            model: Some("WDC WD20EARS".into()),
        };
        assert_eq!(dev.scheduler_optimal(), Some(false));
    }

    #[test]
    fn test_serialization() {
        let stats = IoStats {
            reads_completed: Some(1000),
            reads_merged: Some(50),
            sectors_read: Some(80000),
            read_time_ms: Some(500),
            writes_completed: Some(2000),
            writes_merged: Some(100),
            sectors_written: Some(160000),
            write_time_ms: Some(800),
            in_flight: Some(2),
            io_time_ms: Some(1000),
            weighted_io_time_ms: Some(1200),
            discards_completed: Some(10),
        };
        let json = serde_json::to_string(&stats).unwrap();
        assert!(json.contains("1000"));
        let _: IoStats = serde_json::from_str(&json).unwrap();
    }
    /// A device whose `queue/rotational` was not readable has no optimal
    /// scheduler, because which scheduler is optimal is defined entirely by
    /// that flag. Before 6.0.0 an unreadable flag read as `0` and the device
    /// was judged as an SSD.
    #[test]
    fn an_unread_rotational_flag_yields_no_verdict() {
        let dev = BlockDeviceIo {
            name: "sdz".into(),
            scheduler: Some(IoSchedulerType::Bfq),
            available_schedulers: Some(vec![IoSchedulerType::Bfq]),
            rotational: None,
            queue_depth: None,
            logical_block_size: None,
            physical_block_size: None,
            discard_support: None,
            stats: IoStats {
                reads_completed: Some(0),
                reads_merged: Some(0),
                sectors_read: Some(0),
                read_time_ms: Some(0),
                writes_completed: Some(0),
                writes_merged: Some(0),
                sectors_written: Some(0),
                write_time_ms: Some(0),
                in_flight: Some(0),
                io_time_ms: Some(0),
                weighted_io_time_ms: Some(0),
                discards_completed: Some(0),
            },
            size_bytes: Some(0),
            model: None,
        };
        assert_eq!(dev.scheduler_optimal(), None);
    }

    /// An unread scheduler file is no scheduler, so there is no verdict on it.
    /// It used to parse as `Unknown`, which is not optimal on any device and
    /// was recommended against.
    #[cfg(target_os = "linux")]
    #[test]
    fn unread_scheduler_file_is_none_not_unknown() {
        let dir = std::env::temp_dir().join(format!("ironmon-iosched-none-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let (active, available) = IoSchedulerMonitor::read_scheduler(&dir);
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(active, None);
        assert_eq!(available, None);
    }

    /// The bracketed entry is the active scheduler and every entry is listed.
    #[cfg(target_os = "linux")]
    #[test]
    fn read_scheduler_takes_active_from_brackets() {
        let dir = std::env::temp_dir().join(format!("ironmon-iosched-ok-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("scheduler"), "[mq-deadline] kyber bfq none\n").unwrap();
        let (active, available) = IoSchedulerMonitor::read_scheduler(&dir);
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(active, Some(IoSchedulerType::MqDeadline));
        assert_eq!(
            available,
            Some(vec![
                IoSchedulerType::MqDeadline,
                IoSchedulerType::Kyber,
                IoSchedulerType::Bfq,
                IoSchedulerType::None,
            ])
        );
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn scan_is_unsupported_off_linux() {
        assert!(matches!(
            IoSchedulerMonitor::new(),
            Err(IronError::UnsupportedPlatform(_))
        ));
    }
}