Skip to main content

all_smi/device/common/
command_executor.rs

1// Copyright 2025 Lablup Inc. and Jeongkyu Shin
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Standardized command execution utilities for device modules.
16//
17// Goals:
18// - Centralize timeout behavior
19// - Normalize stdout/stderr handling (UTF-8 lossy conversion)
20// - Provide an optional status check
21// - Keep a default helper compatible with existing call sites
22
23use crate::device::common::{DeviceError, DeviceResult, validate_args, validate_command};
24use crate::utils::{command_timeout::run_command_with_timeout, run_command_fast_fail};
25use std::time::Duration;
26
27/// Options to control command execution behavior.
28#[derive(Debug, Clone, Default)]
29pub struct CommandOptions {
30    /// Optional timeout to use. If None, uses the environment-aware fast-fail timeout.
31    pub timeout: Option<Duration>,
32    /// If true, non-zero exit statuses will return an error.
33    pub check_status: bool,
34}
35
36/// Normalized command output.
37#[derive(Debug, Clone)]
38pub struct CommandOutput {
39    /// Process exit code (or -1 if unavailable)
40    pub status: i32,
41    /// UTF-8 (lossy) decoded stdout
42    pub stdout: String,
43    /// UTF-8 (lossy) decoded stderr
44    pub stderr: String,
45}
46
47/// Execute a command with the provided CommandOptions.
48///
49/// - Validates command and arguments for security
50/// - If options.timeout is Some, uses run_command_with_timeout with that duration
51/// - Otherwise, uses run_command_fast_fail (which adapts to container environments)
52/// - When options.check_status is true and exit code != 0, returns DeviceError::CommandFailed
53pub fn execute_command(
54    command: &str,
55    args: &[&str],
56    options: &CommandOptions,
57) -> DeviceResult<CommandOutput> {
58    // Validate command and arguments for security
59    if !validate_command(command) {
60        return Err(DeviceError::Other(format!(
61            "Invalid command rejected: {command}"
62        )));
63    }
64
65    if !validate_args(args) {
66        return Err(DeviceError::Other(format!(
67            "Invalid arguments rejected for command: {command}"
68        )));
69    }
70
71    let output = if let Some(timeout) = options.timeout {
72        run_command_with_timeout(command, args, timeout)?
73    } else {
74        run_command_fast_fail(command, args)?
75    };
76
77    let status_code = output.status.code().unwrap_or(-1);
78    let out = CommandOutput {
79        status: status_code,
80        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
81        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
82    };
83
84    if options.check_status && status_code != 0 {
85        let full_command = if args.is_empty() {
86            command.to_string()
87        } else {
88            format!("{command} {}", args.join(" "))
89        };
90
91        eprintln!("Command execution failed: '{full_command}' (exit code: {status_code})");
92
93        if !out.stderr.is_empty() {
94            eprintln!("Stderr output: {}", out.stderr);
95        }
96
97        return Err(DeviceError::CommandFailed {
98            command: full_command,
99            code: Some(status_code),
100            stderr: out.stderr.clone(),
101        });
102    }
103
104    Ok(out)
105}
106
107/// Convenience helper that mirrors legacy behavior:
108/// - Uses environment-aware fast-fail timeout
109/// - Does NOT enforce status checking (caller may inspect `status`)
110pub fn execute_command_default(command: &str, args: &[&str]) -> DeviceResult<CommandOutput> {
111    execute_command(command, args, &CommandOptions::default())
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    // `echo` and `false` are shell builtins on Windows rather than
119    // executables on PATH, so `Command::new` cannot spawn them and both
120    // tests failed with `NotFound` there. Gating them to Unix would have
121    // been easier and wrong: `execute_command` runs on Windows in
122    // production (nvidia-smi, wmic), so it is worth testing there. Each
123    // platform therefore names a program it actually has.
124    #[cfg(unix)]
125    const ECHO: (&str, &[&str]) = ("echo", &["hello"]);
126    #[cfg(windows)]
127    const ECHO: (&str, &[&str]) = ("cmd", &["/C", "echo", "hello"]);
128
129    #[cfg(unix)]
130    const FAILS: (&str, &[&str]) = ("false", &[]);
131    #[cfg(windows)]
132    const FAILS: (&str, &[&str]) = ("cmd", &["/C", "exit", "1"]);
133
134    #[test]
135    fn test_execute_command_default_success() {
136        let (cmd, args) = ECHO;
137        let out = execute_command_default(cmd, args).expect("echo should succeed");
138        assert_eq!(out.status, 0);
139        assert!(out.stdout.contains("hello"));
140    }
141
142    #[test]
143    fn test_execute_command_with_status_check() {
144        let opts = CommandOptions {
145            timeout: Some(Duration::from_secs(2)),
146            check_status: true,
147        };
148        let (cmd, args) = FAILS;
149        let err = execute_command(cmd, args, &opts).unwrap_err();
150        match err {
151            DeviceError::CommandFailed { .. } => {}
152            _ => panic!("Expected CommandFailed error"),
153        }
154    }
155}