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
//! Interrupt topology and IRQ mapping monitor.
//!
//! Maps interrupts to CPUs, detects MSI/MSI-X, tracks per-CPU interrupt
//! counts, identifies interrupt affinity, and detects potential interrupt
//! storms or imbalances.
//!
//! ## Platform Support
//!
//! - **Linux**: `/proc/interrupts`, `/proc/irq/*/`, `/sys/bus/pci/devices/*/msi_irqs/`
//! - **Windows**: Performance counters for interrupt rates
//! - **macOS**: Not directly exposed (stub)

use serde::{Deserialize, Serialize};

use crate::error::IronError;

/// Interrupt delivery type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InterruptType {
    /// Legacy pin-based interrupt (INTA#-INTD#).
    LegacyPin,
    /// Message Signaled Interrupt.
    MSI,
    /// Extended MSI (multiple vectors).
    MSIX,
    /// Inter-Processor Interrupt.
    IPI,
    /// Local APIC timer.
    LocalTimer,
    /// Non-Maskable Interrupt.
    NMI,
    /// Spurious interrupt.
    Spurious,
    /// Software interrupt / tasklet.
    Software,
    /// Platform-specific (e.g. ARM GIC).
    Platform,
    Unknown,
}

impl std::fmt::Display for InterruptType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::LegacyPin => write!(f, "Legacy Pin"),
            Self::MSI => write!(f, "MSI"),
            Self::MSIX => write!(f, "MSI-X"),
            Self::IPI => write!(f, "IPI"),
            Self::LocalTimer => write!(f, "Local Timer"),
            Self::NMI => write!(f, "NMI"),
            Self::Spurious => write!(f, "Spurious"),
            Self::Software => write!(f, "Software"),
            Self::Platform => write!(f, "Platform"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// An interrupt source and its statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InterruptInfo {
    /// IRQ number (or name for special interrupts like NMI, LOC).
    pub irq: String,
    /// Interrupt type.
    pub interrupt_type: InterruptType,
    /// Per-CPU interrupt counts.
    pub per_cpu_counts: Vec<u64>,
    /// Total count across all CPUs.
    pub total_count: u64,
    /// Chip/controller name (e.g. "IO-APIC", "PCI-MSI").
    pub chip: String,
    /// Hardware IRQ description (e.g. device name).
    pub description: String,
    /// CPU affinity mask (which CPUs handle this IRQ). `None` when the IRQ has
    /// no `smp_affinity_list` (the per-CPU special interrupts such as NMI and
    /// LOC) or the file was not readable. It used to be filled with every CPU
    /// in that case, which read as "handled everywhere".
    pub affinity_cpus: Option<Vec<u32>>,
    /// Whether the affinity is balanced across CPUs. `None` exactly when
    /// `affinity_cpus` is `None`.
    pub affinity_balanced: Option<bool>,
}

/// Interrupt imbalance analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InterruptAnalysis {
    /// Total interrupts serviced since boot, summed over every CPU: a cumulative
    /// count, not a rate. It used to be documented as interrupts per second.
    /// `None` when no interrupt line was read; it used to be `0` then.
    pub total_interrupts: Option<u64>,
    /// Per-CPU interrupt totals.
    pub per_cpu_totals: Vec<u64>,
    /// CPU with the highest interrupt count, or `None` when no interrupts were
    /// counted. It used to be `0` then, which named CPU 0 as busiest.
    pub busiest_cpu: Option<u32>,
    /// CPU with the lowest non-zero interrupt count, or `None` when no CPU
    /// has a count. It used to be `0` then.
    pub quietest_cpu: Option<u32>,
    /// Imbalance ratio (max/min), or `None` when no CPU has a count. It used to
    /// be `max / 1`, which is `0.0` with no counts: a perfectly balanced machine,
    /// computed from nothing.
    pub imbalance_ratio: Option<f64>,
    /// Whether there's a significant imbalance (ratio > 3.0), or `None` when
    /// there is no ratio. It used to be `false` then.
    pub significant_imbalance: Option<bool>,
    /// Top interrupt sources by count.
    pub top_sources: Vec<(String, u64)>,
    /// Recommendations.
    pub recommendations: Vec<String>,
}

/// Interrupt map monitor.
pub struct InterruptMapMonitor {
    /// Current interrupt data.
    interrupts: Vec<InterruptInfo>,
    /// Number of CPUs.
    cpu_count: u32,
    /// Analysis.
    analysis: InterruptAnalysis,
}

impl InterruptMapMonitor {
    /// Create a new interrupt map monitor.
    pub fn new() -> Result<Self, IronError> {
        let (interrupts, cpu_count) = Self::read_interrupts()?;
        let analysis = Self::analyze(&interrupts, cpu_count);
        Ok(Self {
            interrupts,
            cpu_count,
            analysis,
        })
    }

    /// Refresh data.
    pub fn refresh(&mut self) -> Result<(), IronError> {
        let (interrupts, cpu_count) = Self::read_interrupts()?;
        self.analysis = Self::analyze(&interrupts, cpu_count);
        self.interrupts = interrupts;
        self.cpu_count = cpu_count;
        Ok(())
    }

    /// Get all interrupts.
    pub fn interrupts(&self) -> &[InterruptInfo] {
        &self.interrupts
    }

    /// Get analysis.
    pub fn analysis(&self) -> &InterruptAnalysis {
        &self.analysis
    }

    /// Get MSI/MSI-X interrupts only.
    pub fn msi_interrupts(&self) -> Vec<&InterruptInfo> {
        self.interrupts
            .iter()
            .filter(|i| {
                i.interrupt_type == InterruptType::MSI || i.interrupt_type == InterruptType::MSIX
            })
            .collect()
    }

    /// Get interrupts for a specific CPU.
    pub fn interrupts_for_cpu(&self, cpu: u32) -> Vec<(&InterruptInfo, u64)> {
        self.interrupts
            .iter()
            .filter_map(|i| {
                i.per_cpu_counts
                    .get(cpu as usize)
                    .filter(|&&count| count > 0)
                    .map(|&count| (i, count))
            })
            .collect()
    }

    fn analyze(interrupts: &[InterruptInfo], cpu_count: u32) -> InterruptAnalysis {
        let mut per_cpu_totals = vec![0u64; cpu_count as usize];

        for irq in interrupts {
            for (i, &count) in irq.per_cpu_counts.iter().enumerate() {
                if i < per_cpu_totals.len() {
                    per_cpu_totals[i] += count;
                }
            }
        }

        let total: u64 = per_cpu_totals.iter().sum();
        // With no counts at all there is no busiest CPU; `max_by_key` would
        // otherwise name the last CPU of an all-zero table.
        let max_cpu = (total > 0)
            .then(|| {
                per_cpu_totals
                    .iter()
                    .enumerate()
                    .max_by_key(|(_, &v)| v)
                    .map(|(i, _)| i as u32)
            })
            .flatten();
        let min_cpu = per_cpu_totals
            .iter()
            .enumerate()
            .filter(|(_, &v)| v > 0)
            .min_by_key(|(_, &v)| v)
            .map(|(i, _)| i as u32);

        let max_count = per_cpu_totals.iter().copied().max();
        let min_count = per_cpu_totals.iter().copied().filter(|&v| v > 0).min();
        let imbalance = match (max_count, min_count) {
            (Some(max), Some(min)) => Some(max as f64 / min as f64),
            _ => None,
        };

        // Top sources
        let mut sources: Vec<(String, u64)> = interrupts
            .iter()
            .filter(|i| i.total_count > 0)
            .map(|i| {
                let label = if i.description.is_empty() {
                    format!("IRQ {}", i.irq)
                } else {
                    format!("IRQ {} ({})", i.irq, i.description)
                };
                (label, i.total_count)
            })
            .collect();
        sources.sort_by_key(|p| std::cmp::Reverse(p.1));
        sources.truncate(10);

        let mut recommendations = Vec::new();
        let ratio = imbalance.unwrap_or(0.0);
        if ratio > 5.0 {
            if let (Some(busiest), Some(quietest)) = (max_cpu, min_cpu) {
                recommendations.push(format!(
                    "Severe interrupt imbalance: CPU {} handles {:.1}x more than CPU {}",
                    busiest, ratio, quietest
                ));
            }
            recommendations
                .push("Consider using irqbalance or setting IRQ affinity manually".into());
        } else if ratio > 3.0 {
            recommendations
                .push("Moderate interrupt imbalance detected; consider enabling irqbalance".into());
        }

        InterruptAnalysis {
            total_interrupts: (!interrupts.is_empty()).then_some(total),
            per_cpu_totals,
            busiest_cpu: max_cpu,
            quietest_cpu: min_cpu,
            imbalance_ratio: imbalance,
            significant_imbalance: imbalance.map(|r| r > 3.0),
            top_sources: sources,
            recommendations,
        }
    }

    #[cfg(target_os = "linux")]
    fn read_interrupts() -> Result<(Vec<InterruptInfo>, u32), IronError> {
        let content = std::fs::read_to_string("/proc/interrupts").map_err(IronError::Io)?;
        let mut lines = content.lines();

        // First line has CPU headers
        let header = lines.next().unwrap_or("");
        let cpu_count = header.split_whitespace().count() as u32;

        let mut interrupts = Vec::new();

        for line in lines {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() < (cpu_count as usize + 1) {
                continue;
            }

            let irq = parts[0].trim_end_matches(':').to_string();

            // A row with a count that is not a number cannot be attributed to
            // CPUs. It is left out whole rather than counted as zero per CPU.
            let Some(per_cpu_counts) = parse_per_cpu_counts(&parts[1..=(cpu_count as usize)])
            else {
                continue;
            };

            let total: u64 = per_cpu_counts.iter().sum();

            // Remaining parts: chip name and description
            let remaining = &parts[(cpu_count as usize + 1)..];
            let chip = remaining.first().unwrap_or(&"").to_string();
            let description = if remaining.len() > 1 {
                remaining[1..].join(" ")
            } else {
                String::new()
            };

            let interrupt_type = Self::classify_interrupt(&irq, &chip);

            // Try reading affinity
            let affinity_cpus = Self::read_affinity(&irq);
            let affinity_balanced = affinity_balance(affinity_cpus.as_deref(), cpu_count);

            interrupts.push(InterruptInfo {
                irq,
                interrupt_type,
                per_cpu_counts,
                total_count: total,
                chip,
                description,
                affinity_cpus,
                affinity_balanced,
            });
        }

        Ok((interrupts, cpu_count))
    }

    #[cfg(target_os = "linux")]
    fn classify_interrupt(irq: &str, chip: &str) -> InterruptType {
        let chip_lower = chip.to_lowercase();

        if chip_lower.contains("pci-msi") || chip_lower.contains("pci-msix") {
            if chip_lower.contains("msix") {
                InterruptType::MSIX
            } else {
                InterruptType::MSI
            }
        } else if irq == "NMI" || irq == "PMI" {
            InterruptType::NMI
        } else if irq == "LOC" {
            InterruptType::LocalTimer
        } else if irq == "SPU" {
            InterruptType::Spurious
        } else if irq == "RES" || irq == "CAL" || irq == "TLB" {
            InterruptType::IPI
        // An IO-APIC chip and a bare numeric IRQ are two different ways of spotting
        // the same thing, so they share an arm rather than repeating the result.
        } else if chip_lower.contains("io-apic")
            || chip_lower.contains("ioapic")
            || irq.parse::<u32>().is_ok()
        {
            InterruptType::LegacyPin
        } else {
            InterruptType::Unknown
        }
    }

    #[cfg(target_os = "linux")]
    fn read_affinity(irq: &str) -> Option<Vec<u32>> {
        // Only numeric IRQs have a `/proc/irq/N` directory. The named ones
        // (NMI, LOC, RES, ...) are per-CPU and have no affinity to read. This
        // used to answer "every CPU" for them, and for an unreadable file.
        if irq.parse::<u32>().is_err() {
            return None;
        }

        let affinity_path = format!("/proc/irq/{}/smp_affinity_list", irq);
        let s = std::fs::read_to_string(&affinity_path).ok()?;
        let cpus = Self::parse_cpu_list(s.trim());
        // A file that names no CPU is not a mask of zero CPUs.
        (!cpus.is_empty()).then_some(cpus)
    }

    #[cfg(any(target_os = "linux", test))]
    fn parse_cpu_list(s: &str) -> Vec<u32> {
        let mut cpus = Vec::new();
        for part in s.split(',') {
            let part = part.trim();
            if let Some((start, end)) = part.split_once('-') {
                if let (Ok(s), Ok(e)) = (start.parse::<u32>(), end.parse::<u32>()) {
                    cpus.extend(s..=e);
                }
            } else if let Ok(c) = part.parse::<u32>() {
                cpus.push(c);
            }
        }
        cpus
    }

    #[cfg(target_os = "windows")]
    fn read_interrupts() -> Result<(Vec<InterruptInfo>, u32), IronError> {
        // An empty list plus a CPU count read as "this machine has no
        // interrupts", which is impossible. The error carries the reason.
        Err(IronError::UnsupportedPlatform(
            "interrupt affinity is read from `/proc/interrupts` and `/proc/irq`, which Windows does not expose"
                .into(),
        ))
    }

    #[cfg(target_os = "macos")]
    fn read_interrupts() -> Result<(Vec<InterruptInfo>, u32), IronError> {
        // An empty list plus a CPU count read as "this machine has no
        // interrupts", which is impossible. The error carries the reason.
        Err(IronError::UnsupportedPlatform(
            "interrupt affinity is read from `/proc/interrupts` and `/proc/irq`, which macOS does not expose"
                .into(),
        ))
    }

    #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
    fn read_interrupts() -> Result<(Vec<InterruptInfo>, u32), IronError> {
        // An empty list plus a CPU count read as "this machine has no
        // interrupts", which is impossible. The error carries the reason.
        Err(IronError::UnsupportedPlatform(
            "interrupt affinity is read from `/proc/interrupts` and `/proc/irq`, which this platform does not expose"
                .into(),
        ))
    }
}

/// Whether an IRQ's affinity covers at least half the CPUs. Unknown affinity
/// gives unknown balance; a known single CPU is not balanced.
#[cfg(any(target_os = "linux", test))]
fn affinity_balance(affinity: Option<&[u32]>, cpu_count: u32) -> Option<bool> {
    affinity.map(|cpus| cpus.len() > 1 && cpus.len() as u32 >= cpu_count / 2)
}

/// Per-CPU counts from one `/proc/interrupts` row. `None` when any field is not
/// a count.
#[cfg(any(target_os = "linux", test))]
fn parse_per_cpu_counts(fields: &[&str]) -> Option<Vec<u64>> {
    fields.iter().map(|s| s.parse::<u64>().ok()).collect()
}

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

    #[test]
    fn test_interrupt_type_display() {
        assert_eq!(InterruptType::MSI.to_string(), "MSI");
        assert_eq!(InterruptType::MSIX.to_string(), "MSI-X");
        assert_eq!(InterruptType::NMI.to_string(), "NMI");
    }

    #[test]
    fn test_analysis_balanced() {
        let interrupts = vec![InterruptInfo {
            irq: "0".into(),
            interrupt_type: InterruptType::LegacyPin,
            per_cpu_counts: vec![1000, 1000, 1000, 1000],
            total_count: 4000,
            chip: "IO-APIC".into(),
            description: "timer".into(),
            affinity_cpus: Some(vec![0, 1, 2, 3]),
            affinity_balanced: Some(true),
        }];
        let analysis = InterruptMapMonitor::analyze(&interrupts, 4);
        assert_eq!(analysis.significant_imbalance, Some(false));
        assert!((analysis.imbalance_ratio.unwrap() - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_analysis_imbalanced() {
        let interrupts = vec![InterruptInfo {
            irq: "42".into(),
            interrupt_type: InterruptType::MSI,
            per_cpu_counts: vec![10000, 100, 100, 100],
            total_count: 10300,
            chip: "PCI-MSI".into(),
            description: "nvme0q0".into(),
            affinity_cpus: Some(vec![0]),
            affinity_balanced: Some(false),
        }];
        let analysis = InterruptMapMonitor::analyze(&interrupts, 4);
        assert_eq!(analysis.significant_imbalance, Some(true));
        assert!(analysis.imbalance_ratio.unwrap() > 3.0);
        assert!(!analysis.recommendations.is_empty());
    }

    #[test]
    fn cpu_list_expands_ranges_and_singletons() {
        assert_eq!(
            InterruptMapMonitor::parse_cpu_list("0-3,8"),
            vec![0, 1, 2, 3, 8]
        );
        assert_eq!(InterruptMapMonitor::parse_cpu_list("5"), vec![5]);
    }

    #[test]
    fn cpu_list_with_nothing_parseable_is_empty_not_all_cpus() {
        assert!(InterruptMapMonitor::parse_cpu_list("").is_empty());
        assert!(InterruptMapMonitor::parse_cpu_list("garbage").is_empty());
    }

    #[test]
    fn unknown_affinity_gives_unknown_balance() {
        assert_eq!(affinity_balance(None, 8), None);
    }

    #[test]
    fn balance_needs_at_least_half_the_cpus() {
        assert_eq!(affinity_balance(Some(&[0, 1, 2, 3]), 8), Some(true));
        assert_eq!(affinity_balance(Some(&[0, 1, 2]), 8), Some(false));
        // One CPU is observed, and it is not balanced.
        assert_eq!(affinity_balance(Some(&[0]), 1), Some(false));
    }

    #[test]
    fn test_serialization() {
        let info = InterruptInfo {
            irq: "42".into(),
            interrupt_type: InterruptType::MSI,
            per_cpu_counts: vec![100, 200],
            total_count: 300,
            chip: "PCI-MSI".into(),
            description: "eth0".into(),
            affinity_cpus: Some(vec![0, 1]),
            affinity_balanced: Some(true),
        };
        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("PCI-MSI"));
        let _: InterruptInfo = serde_json::from_str(&json).unwrap();
    }

    #[test]
    fn a_count_that_is_not_a_number_drops_the_row_instead_of_counting_zero() {
        assert_eq!(
            parse_per_cpu_counts(&["12", "7", "0"]),
            Some(vec![12, 7, 0])
        );
        assert_eq!(parse_per_cpu_counts(&["12", "ERR", "0"]), None);
    }

    fn irq_with_counts(counts: Vec<u64>) -> InterruptInfo {
        InterruptInfo {
            irq: "9".into(),
            interrupt_type: InterruptType::LegacyPin,
            total_count: counts.iter().sum(),
            per_cpu_counts: counts,
            chip: "IO-APIC".into(),
            description: "acpi".into(),
            affinity_cpus: None,
            affinity_balanced: None,
        }
    }

    #[test]
    fn no_counted_interrupts_means_no_busiest_or_quietest_cpu() {
        let analysis = InterruptMapMonitor::analyze(&[irq_with_counts(vec![0, 0, 0, 0])], 4);
        assert_eq!(analysis.busiest_cpu, None);
        assert_eq!(analysis.quietest_cpu, None);
        let none = InterruptMapMonitor::analyze(&[], 4);
        assert_eq!(none.busiest_cpu, None);
        assert_eq!(none.quietest_cpu, None);
    }

    #[test]
    fn busiest_and_quietest_are_named_from_the_counts() {
        let analysis = InterruptMapMonitor::analyze(&[irq_with_counts(vec![5, 900, 0, 40])], 4);
        assert_eq!(analysis.busiest_cpu, Some(1));
        // CPU 2 has no count, so it is not the quietest; CPU 0 is.
        assert_eq!(analysis.quietest_cpu, Some(0));
    }
}