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
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (c) 2024 NervoSys

//! NVIDIA GPU monitoring via NVML
//!
//! This module provides NVIDIA GPU support using the NVIDIA Management Library (NVML).
//! It supports both Jetson devices and desktop GPUs, monitoring:
//! - GPU utilization, frequency, memory
//! - Temperature and fan control
//! - Power consumption and limits
//! - Video encode/decode engines (NVENC/NVDEC)
//! - Process tracking
//! - Jetson-specific features (jetson_clocks, nvpmodel, etc.)
//!
//! This integrates the existing IronMonitor NVIDIA implementation with the unified GPU interface.

use crate::gpu::{
    Gpu, GpuClocks, GpuCollection, GpuDynamicInfo, GpuEngines, GpuMemory, GpuPower, GpuProcess,
    GpuProcessType, GpuStaticInfo, GpuThermal, GpuVendor, PcieLinkInfo,
};
use crate::Error;

#[cfg(feature = "nvidia")]
use nvml_wrapper::{Device, Nvml};

#[cfg(feature = "nvidia")]
use std::sync::Arc;

/// NVIDIA GPU implementation
pub struct NvidiaGpu {
    index: usize,
    #[cfg(feature = "nvidia")]
    device: Device<'static>,
    #[cfg(feature = "nvidia")]
    _nvml: Arc<Nvml>, // Keep NVML alive
    #[cfg(not(feature = "nvidia"))]
    _phantom: std::marker::PhantomData<()>,
}

impl NvidiaGpu {
    /// Create new NVIDIA GPU instance
    #[cfg(feature = "nvidia")]
    pub fn new(index: usize, device: Device<'static>, nvml: Arc<Nvml>) -> Result<Self, Error> {
        Ok(Self {
            index,
            device,
            _nvml: nvml,
        })
    }

    #[cfg(not(feature = "nvidia"))]
    pub fn new(index: usize) -> Result<Self, Error> {
        Ok(Self {
            index,
            _phantom: std::marker::PhantomData,
        })
    }
}

impl Gpu for NvidiaGpu {
    #[cfg(feature = "nvidia")]
    fn static_info(&self) -> Result<GpuStaticInfo, Error> {
        use nvml_wrapper::Nvml;

        let name = self
            .device
            .name()
            .map_err(|e| Error::GpuError(format!("Failed to get NVIDIA GPU name: {}", e)))?;

        let pci_info = self.device.pci_info().ok();
        let pci_bus_id = pci_info.map(|info| info.bus_id);

        let uuid = self.device.uuid().ok();

        let vbios_version = self.device.vbios_version().ok();

        // Create an NVML instance to get driver version
        let driver_version = Nvml::init()
            .ok()
            .and_then(|nvml| nvml.sys_driver_version().ok());

        let compute_capability = self
            .device
            .cuda_compute_capability()
            .ok()
            .map(|cap| (cap.major as u32, cap.minor as u32));

        let shader_cores = self.device.num_cores().ok();

        let l2_cache = None; // Not available in nvml-wrapper 0.10

        // NVML has no integrated/discrete property; its bus types are PCI, PCIe,
        // FPCI and AGP. This used to be a match on the product name ("nano",
        // "agx", "orin"...), which the ontology already refused to publish, so
        // it is left unread rather than guessed.
        let integrated = None;

        Ok(GpuStaticInfo {
            index: self.index,
            vendor: GpuVendor::Nvidia,
            name,
            pci_bus_id,
            uuid,
            vbios_version,
            driver_version,
            compute_capability,
            shader_cores,
            l2_cache,
            num_engines: None,
            integrated,
        })
    }

    #[cfg(not(feature = "nvidia"))]
    fn static_info(&self) -> Result<GpuStaticInfo, Error> {
        Err(Error::NotSupported(
            "NVIDIA support not compiled in".to_string(),
        ))
    }

    #[cfg(feature = "nvidia")]
    fn dynamic_info(&self) -> Result<GpuDynamicInfo, Error> {
        use nvml_wrapper::enum_wrappers::device::Clock;

        // GPU utilization
        // `.unwrap_or(0)` here reported an idle card for a query that
        // failed. The clocks below have always been `Option`; this now is too.
        let utilization = self.device.utilization_rates().ok().map(|u| u.gpu as u8);

        // Memory
        // An NVML query that failed reports nothing, rather than a card with
        // no memory. The clocks immediately below have always been `Option` for
        // this reason; the memory fields could not say it until 6.0.0.
        let memory = match self.device.memory_info().ok() {
            Some(m) => GpuMemory::from_total_used(m.total, m.used),
            None => GpuMemory::unreported(),
        };

        // Clocks
        let clocks = GpuClocks {
            graphics: self.device.clock_info(Clock::Graphics).ok(),
            graphics_max: self.device.max_clock_info(Clock::Graphics).ok(),
            memory: self.device.clock_info(Clock::Memory).ok(),
            memory_max: self.device.max_clock_info(Clock::Memory).ok(),
            sm: self.device.clock_info(Clock::SM).ok(),
            video: self.device.clock_info(Clock::Video).ok(),
        };

        // Power
        let power_draw = self.device.power_usage().ok();
        let power_limit = self.device.power_management_limit().ok();
        let default_limit = self.device.power_management_limit_default().ok();
        let power = GpuPower {
            draw: power_draw,
            limit: power_limit,
            default_limit,
            usage_percent: match (power_draw, power_limit) {
                (Some(draw), Some(limit)) if limit > 0 => {
                    Some(((draw as f64 / limit as f64) * 100.0) as u8)
                }
                _ => None,
            },
        };

        // Thermal
        let temperature = self
            .device
            .temperature(nvml_wrapper::enum_wrappers::device::TemperatureSensor::Gpu)
            .ok()
            .map(|t| t as i32);

        let fan_speed = self.device.fan_speed(0).ok().map(|s| s as u8);

        // Get thermal thresholds from NVML
        let max_temperature = self
            .device
            .temperature_threshold(
                nvml_wrapper::enum_wrappers::device::TemperatureThreshold::Slowdown,
            )
            .ok()
            .map(|t| t as i32);

        let critical_temperature = self
            .device
            .temperature_threshold(
                nvml_wrapper::enum_wrappers::device::TemperatureThreshold::Shutdown,
            )
            .ok()
            .map(|t| t as i32);

        let thermal = GpuThermal {
            temperature,
            max_temperature,
            critical_temperature,
            fan_speed,
            fan_rpm: None,
        };

        // PCIe
        let pcie_gen = self.device.current_pcie_link_gen().ok().map(|g| g as u8);
        let max_pcie_gen = self.device.max_pcie_link_gen().ok().map(|g| g as u8);
        let pcie_width = self.device.current_pcie_link_width().ok().map(|w| w as u8);
        let max_pcie_width = self.device.max_pcie_link_width().ok().map(|w| w as u8);

        let pcie = PcieLinkInfo {
            current_gen: pcie_gen,
            max_gen: max_pcie_gen,
            current_width: pcie_width,
            max_width: max_pcie_width,
            current_speed: None,
            max_speed: None,
            tx_throughput: None,
            rx_throughput: None,
        };

        // Engines
        let encoder_util = self
            .device
            .encoder_utilization()
            .ok()
            .map(|u| u.utilization as u8);
        let decoder_util = self
            .device
            .decoder_utilization()
            .ok()
            .map(|u| u.utilization as u8);

        let engines = GpuEngines {
            graphics: utilization,
            compute: None,
            encoder: encoder_util,
            decoder: decoder_util,
            copy: None,
            vendor_specific: vec![],
        };

        // Processes
        let processes = self.get_processes_internal()?;

        Ok(GpuDynamicInfo {
            utilization,
            memory,
            clocks,
            power,
            thermal,
            pcie,
            engines,
            processes,
        })
    }

    #[cfg(not(feature = "nvidia"))]
    fn dynamic_info(&self) -> Result<GpuDynamicInfo, Error> {
        Err(Error::NotSupported(
            "NVIDIA support not compiled in".to_string(),
        ))
    }

    fn vendor(&self) -> GpuVendor {
        GpuVendor::Nvidia
    }

    fn index(&self) -> usize {
        self.index
    }

    #[cfg(feature = "nvidia")]
    fn name(&self) -> Result<String, Error> {
        self.device
            .name()
            .map_err(|e| Error::GpuError(format!("Failed to get GPU name: {}", e)))
    }

    #[cfg(not(feature = "nvidia"))]
    fn name(&self) -> Result<String, Error> {
        Err(Error::NotSupported(
            "NVIDIA support not compiled in".to_string(),
        ))
    }

    #[cfg(feature = "nvidia")]
    fn processes(&self) -> Result<Vec<GpuProcess>, Error> {
        self.get_processes_internal()
    }

    #[cfg(not(feature = "nvidia"))]
    fn processes(&self) -> Result<Vec<GpuProcess>, Error> {
        Err(Error::NotSupported(
            "NVIDIA support not compiled in".to_string(),
        ))
    }

    fn kill_process(&self, pid: u32) -> Result<(), Error> {
        #[cfg(unix)]
        {
            use nix::sys::signal::{kill, Signal};
            use nix::unistd::Pid;
            kill(Pid::from_raw(pid as i32), Signal::SIGTERM).map_err(|e| {
                Error::ProcessError(format!("Failed to kill process {}: {}", pid, e))
            })?;
            Ok(())
        }
        #[cfg(windows)]
        {
            // Windows constants
            const PROCESS_TERMINATE: u32 = 0x0001;

            // Windows API declarations
            #[link(name = "kernel32")]
            extern "system" {
                fn OpenProcess(
                    dwDesiredAccess: u32,
                    bInheritHandle: i32,
                    dwProcessId: u32,
                ) -> *mut std::ffi::c_void;
                fn TerminateProcess(hProcess: *mut std::ffi::c_void, uExitCode: u32) -> i32;
                fn CloseHandle(hObject: *mut std::ffi::c_void) -> i32;
            }

            unsafe {
                // Open the process with terminate permission
                let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
                if handle.is_null() {
                    return Err(Error::ProcessError(format!(
                        "Failed to open process {}: access denied or process not found",
                        pid
                    )));
                }

                // Terminate the process
                let result = TerminateProcess(handle, 1);
                CloseHandle(handle);

                if result == 0 {
                    return Err(Error::ProcessError(format!(
                        "Failed to terminate process {}",
                        pid
                    )));
                }
            }

            Ok(())
        }
        #[cfg(not(any(unix, windows)))]
        {
            let _ = pid;
            Err(Error::NotSupported(
                "Process killing not supported on this platform".to_string(),
            ))
        }
    }

    #[cfg(feature = "nvidia")]
    fn set_power_limit(&mut self, limit_mw: u32) -> Result<(), Error> {
        self.device
            .set_power_management_limit(limit_mw)
            .map_err(|e| Error::GpuError(format!("Failed to set power limit: {}", e)))?;
        Ok(())
    }
}

#[cfg(feature = "nvidia")]
impl NvidiaGpu {
    fn get_processes_internal(&self) -> Result<Vec<GpuProcess>, Error> {
        use nvml_wrapper::enums::device::UsedGpuMemory;

        let mut processes = Vec::new();

        // Each query's failure used to be dropped by `if let Ok`, so a GPU whose
        // process queries both failed reported no processes. With both failing
        // nothing was read, and that is an error, not an empty list.
        let graphics = self.device.running_graphics_processes();
        let compute = self.device.running_compute_processes();
        if let (Err(e), Err(_)) = (&graphics, &compute) {
            return Err(Error::GpuError(format!("NVML process queries failed: {e}")));
        }

        // Get graphics processes
        if let Ok(graphics_procs) = graphics {
            for proc in graphics_procs {
                let memory_usage = match proc.used_gpu_memory {
                    UsedGpuMemory::Used(bytes) => Some(bytes),
                    _ => None,
                };

                processes.push(GpuProcess {
                    pid: proc.pid,
                    name: get_process_name(proc.pid),
                    user: get_process_user(proc.pid),
                    process_type: GpuProcessType::Graphics,
                    gpu_usage: None,
                    memory_usage,
                    memory_usage_percent: None,
                    encoder_usage: None,
                    decoder_usage: None,
                    cpu_usage: None,
                    cpu_memory: None,
                });
            }
        }

        // Get compute processes
        if let Ok(compute_procs) = compute {
            for proc in compute_procs {
                // Check if already in list (some processes are both graphics and compute)
                if let Some(existing) = processes.iter_mut().find(|p| p.pid == proc.pid) {
                    existing.process_type = GpuProcessType::GraphicsAndCompute;
                } else {
                    let memory_usage = match proc.used_gpu_memory {
                        UsedGpuMemory::Used(bytes) => Some(bytes),
                        _ => None,
                    };

                    processes.push(GpuProcess {
                        pid: proc.pid,
                        name: get_process_name(proc.pid),
                        user: get_process_user(proc.pid),
                        process_type: GpuProcessType::Compute,
                        gpu_usage: None,
                        memory_usage,
                        memory_usage_percent: None,
                        encoder_usage: None,
                        decoder_usage: None,
                        cpu_usage: None,
                        cpu_memory: None,
                    });
                }
            }
        }

        Ok(processes)
    }
}

#[cfg(feature = "nvidia")]
fn get_process_name(pid: u32) -> String {
    #[cfg(unix)]
    {
        std::fs::read_to_string(format!("/proc/{}/comm", pid))
            .ok()
            .and_then(|s| s.lines().next().map(|l| l.to_string()))
            .unwrap_or_else(|| format!("<unknown:{}>", pid))
    }
    #[cfg(windows)]
    {
        use std::mem;
        use windows::Win32::Foundation::CloseHandle;
        use windows::Win32::System::Diagnostics::ToolHelp::{
            CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
            TH32CS_SNAPPROCESS,
        };

        unsafe {
            if let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) {
                let mut entry: PROCESSENTRY32W = mem::zeroed();
                entry.dwSize = mem::size_of::<PROCESSENTRY32W>() as u32;

                if Process32FirstW(snapshot, &mut entry).is_ok() {
                    loop {
                        if entry.th32ProcessID == pid {
                            let name_len = entry
                                .szExeFile
                                .iter()
                                .position(|&c| c == 0)
                                .unwrap_or(entry.szExeFile.len());
                            let name = String::from_utf16_lossy(&entry.szExeFile[..name_len]);
                            let _ = CloseHandle(snapshot);
                            return name;
                        }
                        if Process32NextW(snapshot, &mut entry).is_err() {
                            break;
                        }
                    }
                }
                let _ = CloseHandle(snapshot);
            }
        }
        format!("process_{}", pid)
    }
    #[cfg(not(any(unix, windows)))]
    {
        format!("process_{}", pid)
    }
}

/// The owner of a process, or the empty string where it could not be read.
///
/// Empty is the codebase's "not read" marker for `GpuProcess::user`, and
/// `process_monitor` only copies a non-empty value. This used to return the
/// literal `"<unknown>"`, which passed that check and showed up as a user name.
#[cfg(feature = "nvidia")]
fn get_process_user(pid: u32) -> String {
    #[cfg(unix)]
    {
        use std::fs;
        use std::os::unix::fs::MetadataExt;

        fs::metadata(format!("/proc/{}", pid))
            .ok()
            .and_then(|meta| {
                nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(meta.uid()))
                    .ok()
                    .flatten()
                    .map(|u| u.name)
            })
            .unwrap_or_default()
    }
    #[cfg(windows)]
    {
        // Get username from Windows API
        use std::ffi::OsString;
        use std::os::windows::ffi::OsStringExt;

        extern "system" {
            fn OpenProcess(
                dwDesiredAccess: u32,
                bInheritHandle: i32,
                dwProcessId: u32,
            ) -> *mut std::ffi::c_void;
            fn CloseHandle(hObject: *mut std::ffi::c_void) -> i32;
            fn OpenProcessToken(
                ProcessHandle: *mut std::ffi::c_void,
                DesiredAccess: u32,
                TokenHandle: *mut *mut std::ffi::c_void,
            ) -> i32;
            fn GetTokenInformation(
                TokenHandle: *mut std::ffi::c_void,
                TokenInformationClass: u32,
                TokenInformation: *mut std::ffi::c_void,
                TokenInformationLength: u32,
                ReturnLength: *mut u32,
            ) -> i32;
            fn LookupAccountSidW(
                lpSystemName: *const u16,
                Sid: *mut std::ffi::c_void,
                Name: *mut u16,
                cchName: *mut u32,
                ReferencedDomainName: *mut u16,
                cchReferencedDomainName: *mut u32,
                peUse: *mut u32,
            ) -> i32;
        }

        const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
        const TOKEN_QUERY: u32 = 0x0008;
        const TOKEN_USER: u32 = 1;

        #[repr(C)]
        struct TokenUser {
            user: SidAndAttributes,
        }

        #[repr(C)]
        struct SidAndAttributes {
            sid: *mut std::ffi::c_void,
            attributes: u32,
        }

        unsafe {
            let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
            if process.is_null() {
                return String::new();
            }

            let mut token: *mut std::ffi::c_void = std::ptr::null_mut();
            if OpenProcessToken(process, TOKEN_QUERY, &mut token) == 0 {
                CloseHandle(process);
                return String::new();
            }

            // Get required buffer size
            let mut return_length: u32 = 0;
            GetTokenInformation(
                token,
                TOKEN_USER,
                std::ptr::null_mut(),
                0,
                &mut return_length,
            );

            if return_length == 0 {
                CloseHandle(token);
                CloseHandle(process);
                return String::new();
            }

            let mut buffer = vec![0u8; return_length as usize];
            if GetTokenInformation(
                token,
                TOKEN_USER,
                buffer.as_mut_ptr() as *mut _,
                return_length,
                &mut return_length,
            ) == 0
            {
                CloseHandle(token);
                CloseHandle(process);
                return String::new();
            }

            let token_user = &*(buffer.as_ptr() as *const TokenUser);

            // Look up the account name
            let mut name_size: u32 = 256;
            let mut domain_size: u32 = 256;
            let mut name_buf = vec![0u16; name_size as usize];
            let mut domain_buf = vec![0u16; domain_size as usize];
            let mut sid_type: u32 = 0;

            if LookupAccountSidW(
                std::ptr::null(),
                token_user.user.sid,
                name_buf.as_mut_ptr(),
                &mut name_size,
                domain_buf.as_mut_ptr(),
                &mut domain_size,
                &mut sid_type,
            ) == 0
            {
                CloseHandle(token);
                CloseHandle(process);
                return String::new();
            }

            CloseHandle(token);
            CloseHandle(process);

            // Convert wide string to Rust string
            let name = OsString::from_wide(&name_buf[..name_size as usize])
                .to_string_lossy()
                .to_string();
            name
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = pid;
        "user".to_string()
    }
}

/// Detect all NVIDIA GPUs in the system
#[cfg(feature = "nvidia")]
pub fn detect_gpus(collection: &mut GpuCollection) -> Result<(), Error> {
    let nvml = Arc::new(
        Nvml::init().map_err(|e| Error::GpuError(format!("Failed to initialize NVML: {}", e)))?,
    );

    let device_count = nvml
        .device_count()
        .map_err(|e| Error::GpuError(format!("Failed to get NVIDIA device count: {}", e)))?;

    // A device that fails is recorded and the rest are still read, so one bad
    // adapter does not hide the others. Each GPU keeps its NVML index.
    for i in 0..device_count {
        let device = match nvml.device_by_index(i) {
            Ok(device) => device,
            Err(e) => {
                collection
                    .detection_failures
                    .push(("nvidia", format!("device {i}: {e}")));
                continue;
            }
        };

        // Transmute the device to get a 'static lifetime (safe because we keep nvml alive via Arc)
        let static_device = unsafe { std::mem::transmute::<Device<'_>, Device<'static>>(device) };

        match NvidiaGpu::new(i as usize, static_device, Arc::clone(&nvml)) {
            Ok(gpu) => collection.add_gpu(Box::new(gpu)),
            Err(e) => collection
                .detection_failures
                .push(("nvidia", format!("device {i}: {e}"))),
        }
    }

    Ok(())
}

#[cfg(not(feature = "nvidia"))]
pub fn detect_gpus(_collection: &mut GpuCollection) -> Result<(), Error> {
    // NVIDIA support not compiled in
    Ok(())
}

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

    #[test]
    #[cfg(feature = "nvidia")]
    fn test_nvidia_detection() {
        let mut collection = GpuCollection::new();
        // This may fail if no NVIDIA GPU is present
        let _ = detect_gpus(&mut collection);
    }
}