all-smi 0.26.3

Command-line utility for monitoring GPU hardware. It provides a real-time view of GPU utilization, memory usage, temperature, power consumption, and other metrics.
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
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::utils::command::new_command;
use once_cell::sync::Lazy;
use std::io::{self, Write};
use std::sync::Mutex;
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};

/// Global System instance for process collection
/// This avoids creating new System instances on every collection cycle
static GLOBAL_SYSTEM: Lazy<Mutex<System>> = Lazy::new(|| {
    let system = System::new();
    Mutex::new(system)
});

/// Cached hostname - fetched once and reused to avoid repeated system calls
static CACHED_HOSTNAME: Lazy<String> =
    Lazy::new(|| System::host_name().unwrap_or_else(|| "unknown".to_string()));

pub fn get_hostname() -> String {
    CACHED_HOSTNAME.clone()
}

/// Get global system instance for process collection
/// Returns a reference to the global System wrapped in a MutexGuard
/// This is more efficient than creating a new System instance every time
pub fn with_global_system<F, R>(f: F) -> R
where
    F: FnOnce(&mut System) -> R,
{
    // Recover from a poisoned lock instead of propagating it: `System` is a
    // plain metrics snapshot, so continuing to use it after a panic mid-update
    // elsewhere is safe, and it keeps one panicking caller (there are several,
    // across GPU/process readers on multiple platforms) from permanently
    // taking down every later call to this function.
    let mut system = GLOBAL_SYSTEM
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    f(&mut system)
}

/// Refresh processes using the global System instance
/// This is the primary use case - collecting process information
#[allow(dead_code)]
pub fn refresh_global_processes() {
    let mut system = GLOBAL_SYSTEM
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    system.refresh_processes_specifics(
        ProcessesToUpdate::All,
        true,
        ProcessRefreshKind::everything().with_user(UpdateKind::Always),
    );
    system.refresh_memory();
}

/// Check if the current process already has sudo privileges
pub fn has_sudo_privileges() -> bool {
    new_command("sudo")
        .arg("-n") // Non-interactive mode
        .arg("-v") // Validate sudo timestamp
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

#[allow(dead_code)] // Used in runner_old.rs (backup file)
pub fn calculate_adaptive_interval(node_count: usize) -> u64 {
    // Adaptive interval based on node count to prevent overwhelming the network
    // For 1-10 nodes: 2 seconds
    // For 11-50 nodes: 3 seconds
    // For 51-100 nodes: 4 seconds
    // For 101-200 nodes: 5 seconds
    // For 201+ nodes: 6 seconds
    match node_count {
        0..=10 => 2,
        11..=50 => 3,
        51..=100 => 4,
        101..=200 => 5,
        _ => 6,
    }
}

#[allow(dead_code)] // Used conditionally based on platform and feature flags
pub fn ensure_sudo_permissions() {
    if cfg!(target_os = "macos") {
        // macOS uses native APIs (IOReport, SMC) that don't require sudo
    } else if cfg!(target_os = "linux") {
        // On Linux, check if AMD hardware needs DRI privileges. Detection is
        // feature-independent; the native backend itself is loaded later.
        #[cfg(all(target_os = "linux", not(target_env = "musl")))]
        {
            use crate::device::platform_detection::has_amd;

            if has_amd() {
                // AMD GPUs require sudo to access /dev/dri devices
                // Check if running as root
                if unsafe { libc::geteuid() } != 0 {
                    request_sudo_with_explanation(SudoPlatform::Linux, false);
                }
            }
        }
    } else {
        // For other systems, we might need different handling
        eprintln!("Note: This platform may not require sudo for hardware monitoring.");
    }
}

pub fn ensure_sudo_permissions_for_api() -> bool {
    #[cfg(target_os = "windows")]
    {
        // Windows does not use sudo/root model
        println!("✅ Running on Windows, no sudo required.");
        true
    }

    #[cfg(unix)]
    {
        // macOS with native APIs (IOReport, SMC) doesn't require sudo
        #[cfg(target_os = "macos")]
        {
            true
        }

        #[cfg(not(target_os = "macos"))]
        {
            // Check if we are already running as root
            if std::env::var("USER").unwrap_or_default() == "root"
                || unsafe { libc::geteuid() } == 0
            {
                println!("✅ Running as root, no sudo required.");
                return true;
            }

            // Check if we already have sudo privileges cached
            if has_sudo_privileges() {
                println!("✅ Sudo privileges already available.");
                return true;
            }

            // Sudo not available - warn but continue (for API mode)
            println!("⚠️  Warning: Running without sudo privileges.");
            println!("   Some hardware metrics may not be available.");
            println!("   For full functionality, run with: sudo all-smi api --port <port>");
            false
        }
    }

    #[cfg(not(any(target_os = "windows", unix)))]
    {
        // For other platforms, assume no sudo required
        println!("✅ Running on unsupported platform, no sudo required.");
        true
    }
}

#[allow(dead_code)] // Used conditionally based on platform and feature flags
pub fn ensure_sudo_permissions_with_fallback() -> bool {
    if cfg!(target_os = "macos") {
        // macOS uses native APIs (IOReport, SMC) that don't require sudo
        true
    } else if cfg!(target_os = "linux") {
        // On Linux, check if AMD hardware needs DRI privileges. Detection is
        // feature-independent; the native backend itself is loaded later.
        #[cfg(all(target_os = "linux", not(target_env = "musl")))]
        {
            use crate::device::platform_detection::has_amd;

            if has_amd() {
                // AMD GPUs require sudo - check if running as root
                if unsafe { libc::geteuid() } != 0 {
                    request_sudo_with_explanation(SudoPlatform::Linux, false);
                }
                // If we're here, either:
                // 1. We were already root (geteuid() == 0)
                // 2. sudo request succeeded (otherwise process would have exited)
                // In both cases, we can proceed
                return true;
            }
        }
        // For musl builds or when no AMD GPU is detected, no AMD-specific
        // privilege escalation is needed.
        true
    } else {
        true
    }
}

/// Platform-specific sudo messages (Linux only - macOS uses native APIs without sudo)
#[derive(Copy, Clone)]
#[allow(dead_code)] // Used conditionally based on platform
enum SudoPlatform {
    Linux,
}

/// Get platform-specific sudo explanation messages (Linux only)
#[allow(dead_code)] // Used conditionally based on platform
fn get_sudo_messages(
    _platform: SudoPlatform,
) -> (
    &'static str,
    &'static str,
    &'static str,
    Option<&'static str>,
    Option<&'static str>,
) {
    // Linux AMD GPU support
    (
        // Required reasons
        "   • Access to AMD GPU devices requires read/write permissions on /dev/dri\n   • These devices are typically only accessible by root or video/render group\n   • This includes GPU utilization, memory usage, temperature, and power data",
        // Security info
        "   • all-smi only reads GPU metrics - it does not modify your system\n   • The sudo access is used exclusively for accessing AMD GPU devices\n   • No data is transmitted externally without your explicit configuration",
        // Monitored items
        "   • AMD GPU: Utilization, VRAM usage, temperature, power, clock speeds\n   • CPU: Core utilization and performance metrics\n   • Memory: System RAM usage and allocation\n   • Storage: Disk usage and performance",
        // Alternative
        Some(
            "💡 Alternative: Add your user to the 'video' and 'render' groups:\n   sudo usermod -a -G video,render $USER\n   (requires logout/login to take effect)",
        ),
        // Additional troubleshooting
        Some(
            "   Alternative: Add your user to video/render groups:\n   → sudo usermod -a -G video,render $USER",
        ),
    )
}

/// Unified function to request sudo with platform-specific explanations
#[allow(dead_code)] // Used conditionally based on platform and feature flags
fn request_sudo_with_explanation(platform: SudoPlatform, return_bool: bool) -> bool {
    // Check if we already have sudo privileges
    if has_sudo_privileges() {
        // On Linux, having sudo timestamp is not enough - process must run as root
        #[cfg(target_os = "linux")]
        {
            if matches!(platform, SudoPlatform::Linux) && unsafe { libc::geteuid() } != 0 {
                println!();
                println!("⚠️  Sudo timestamp is valid, but the process is not running as root.");
                println!();
                println!("AMD GPU monitoring requires the program itself to run with sudo:");
                println!("   → sudo all-smi");
                println!();
                println!("(Unlike macOS, Linux requires root privileges for /dev/dri access)");
                println!();
                std::process::exit(1);
            }
        }

        println!();
        println!("✅ Administrator privileges already available.");
        println!("   Starting system monitoring...");
        println!();
        // Add a small delay for non-fallback mode so user can see the message
        if !return_bool {
            std::thread::sleep(std::time::Duration::from_millis(300));
        }
        return true; // Always return true if sudo is available
    }

    let (required_reasons, security_info, monitored_items, alternative, additional_troubleshooting) =
        get_sudo_messages(platform);

    // Always show the explanation first, regardless of sudo status
    println!();
    println!("🔧 all-smi: System Monitoring Interface");
    println!("============================================");
    println!();
    println!("This application monitors GPU, CPU, and memory usage on your system.");
    println!();
    println!("🔒 Administrator privileges are required because:");
    println!("{required_reasons}");
    println!();
    println!("🛡️  Security Information:");
    println!("{security_info}");
    println!();
    println!("📋 What will be monitored:");
    println!("{monitored_items}");
    println!();

    // Show alternative if available (Linux only)
    if let Some(alt) = alternative {
        println!("{alt}");
        println!();
    }

    // Give user a choice to continue
    print!("To proceed, you need to enter your sudo password.");
    println!();
    println!("🔑 Requesting administrator privileges...");
    println!("   (You may be prompted for your password)");
    println!();

    // Flush output to ensure all messages are displayed before sudo prompt
    io::stdout().flush().unwrap();

    // Attempt to get sudo privileges
    let status = new_command("sudo")
        .arg("-v")
        .status()
        .expect("Failed to execute sudo command");

    if !status.success() {
        println!("❌ Failed to acquire administrator privileges.");
        println!();
        println!("💡 Troubleshooting:");
        println!("   • Make sure you entered the correct password");
        println!("   • Ensure your user account has sudo privileges");
        println!("   • Try running 'sudo -v' manually to test sudo access");
        println!();

        // Show additional troubleshooting if available (Linux only)
        if let Some(additional) = additional_troubleshooting {
            println!("{additional}");
            println!();
        }

        println!("   For remote monitoring without sudo, use:");
        println!("   → all-smi view --hosts <url1> <url2>");
        println!();
        std::process::exit(1);
    }

    println!("✅ Administrator privileges granted successfully.");
    println!("   Starting system monitoring...");
    println!();

    true // Always return true if we reach this point (sudo was successful)
}

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

    #[test]
    fn test_calculate_adaptive_interval() {
        assert_eq!(calculate_adaptive_interval(0), 2);
        assert_eq!(calculate_adaptive_interval(1), 2);
        assert_eq!(calculate_adaptive_interval(5), 2);
        assert_eq!(calculate_adaptive_interval(10), 2);
        assert_eq!(calculate_adaptive_interval(11), 3);
        assert_eq!(calculate_adaptive_interval(25), 3);
        assert_eq!(calculate_adaptive_interval(50), 3);
        assert_eq!(calculate_adaptive_interval(51), 4);
        assert_eq!(calculate_adaptive_interval(75), 4);
        assert_eq!(calculate_adaptive_interval(100), 4);
        assert_eq!(calculate_adaptive_interval(101), 5);
        assert_eq!(calculate_adaptive_interval(150), 5);
        assert_eq!(calculate_adaptive_interval(200), 5);
        assert_eq!(calculate_adaptive_interval(201), 6);
        assert_eq!(calculate_adaptive_interval(500), 6);
        assert_eq!(calculate_adaptive_interval(1000), 6);
    }

    #[test]
    fn test_get_hostname() {
        let hostname = get_hostname();
        assert!(!hostname.is_empty(), "Hostname should not be empty");
        assert!(
            !hostname.contains('\n'),
            "Hostname should not contain newlines"
        );
        assert!(
            !hostname.contains('\r'),
            "Hostname should not contain carriage returns"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    #[ignore] // Run with: sudo cargo test -- --ignored
    fn test_ensure_sudo_permissions_macos() {
        ensure_sudo_permissions();
    }

    #[cfg(not(target_os = "macos"))]
    #[test]
    fn test_ensure_sudo_permissions_non_macos() {
        ensure_sudo_permissions();
    }

    #[test]
    #[cfg_attr(target_os = "macos", ignore)] // Run with: sudo cargo test -- --ignored
    fn test_ensure_sudo_permissions_with_fallback_returns_bool() {
        let _result = ensure_sudo_permissions_with_fallback();
        // Function should execute without panicking and return a boolean
    }

    #[test]
    #[cfg(target_os = "macos")]
    fn test_has_sudo_privileges_on_macos() {
        // This test just checks if the function runs without error
        // It doesn't require sudo itself
        let _result = has_sudo_privileges();
        // Function should execute without panicking and return a boolean
    }

    #[test]
    #[cfg(not(target_os = "macos"))]
    fn test_has_sudo_privileges_on_non_macos() {
        let result = has_sudo_privileges();
        // Result is always a boolean, so just verify it completes
        let _ = result;
    }
}