Skip to main content

start_command/
isolation_log.rs

1//! Logging and utility functions for isolation runners
2
3use std::env;
4use std::fs::{self, File, OpenOptions};
5use std::io::Write;
6use std::path::PathBuf;
7
8/// Generate timestamp for logging
9pub fn get_timestamp() -> String {
10    chrono::Utc::now()
11        .format("%Y-%m-%d %H:%M:%S%.3f")
12        .to_string()
13}
14
15/// Generate unique log filename
16pub fn generate_log_filename(environment: &str) -> String {
17    let timestamp = std::time::SystemTime::now()
18        .duration_since(std::time::UNIX_EPOCH)
19        .unwrap()
20        .as_millis();
21    let random: String = (0..6)
22        .map(|_| {
23            let idx = (std::time::SystemTime::now()
24                .duration_since(std::time::UNIX_EPOCH)
25                .unwrap()
26                .as_nanos()
27                % 36) as u8;
28            if idx < 10 {
29                (b'0' + idx) as char
30            } else {
31                (b'a' + idx - 10) as char
32            }
33        })
34        .collect();
35    format!("start-command-{}-{}-{}.log", environment, timestamp, random)
36}
37
38/// Root directory for start-command temporary files.
39pub fn get_temp_root() -> PathBuf {
40    env::var("START_TEMP_ROOT")
41        .map(PathBuf::from)
42        .unwrap_or_else(|_| env::temp_dir().join("start-command"))
43}
44
45/// Log header parameters
46#[derive(Debug)]
47pub struct LogHeaderParams {
48    pub command: String,
49    pub environment: String,
50    pub mode: String,
51    pub session_name: String,
52    pub image: Option<String>,
53    pub user: Option<String>,
54    pub start_time: String,
55}
56
57/// Create log content header
58pub fn create_log_header(params: &LogHeaderParams) -> String {
59    let mut content = String::new();
60    content.push_str("=== Start Command Log ===\n");
61    content.push_str(&format!("Timestamp: {}\n", params.start_time));
62    content.push_str(&format!("Command: {}\n", params.command));
63    content.push_str(&format!("Environment: {}\n", params.environment));
64    content.push_str(&format!("Mode: {}\n", params.mode));
65    content.push_str(&format!("Session: {}\n", params.session_name));
66    if let Some(ref image) = params.image {
67        content.push_str(&format!("Image: {}\n", image));
68    }
69    if let Some(ref user) = params.user {
70        content.push_str(&format!("User: {}\n", user));
71    }
72    content.push_str(&format!("Platform: {}\n", std::env::consts::OS));
73    content.push_str(&format!(
74        "Working Directory: {}\n",
75        env::current_dir().unwrap_or_default().display()
76    ));
77    content.push_str(&format!("{}\n\n", "=".repeat(50)));
78    content
79}
80
81/// Create log content footer
82pub fn create_log_footer(end_time: &str, exit_code: i32) -> String {
83    let mut content = String::new();
84    content.push_str(&format!("\n{}\n", "=".repeat(50)));
85    content.push_str(&format!("Finished: {}\n", end_time));
86    content.push_str(&format!("Exit Code: {}\n", exit_code));
87    content
88}
89
90/// Write log file
91pub fn write_log_file(log_path: &PathBuf, content: &str) -> bool {
92    if let Some(parent) = log_path.parent() {
93        if let Err(e) = fs::create_dir_all(parent) {
94            eprintln!("\nWarning: Could not create log directory: {}", e);
95            return false;
96        }
97    }
98    match File::create(log_path) {
99        Ok(mut file) => file.write_all(content.as_bytes()).is_ok(),
100        Err(e) => {
101            eprintln!("\nWarning: Could not save log file: {}", e);
102            false
103        }
104    }
105}
106
107/// Append to a log file, creating its parent directory when needed.
108pub fn append_log_file(log_path: &PathBuf, content: &str) -> bool {
109    if let Some(parent) = log_path.parent() {
110        if let Err(e) = fs::create_dir_all(parent) {
111            eprintln!("\nWarning: Could not create log directory: {}", e);
112            return false;
113        }
114    }
115    match OpenOptions::new().create(true).append(true).open(log_path) {
116        Ok(mut file) => file.write_all(content.as_bytes()).is_ok(),
117        Err(e) => {
118            eprintln!("\nWarning: Could not append log file: {}", e);
119            false
120        }
121    }
122}
123
124/// Get log directory from environment or use system temp
125pub fn get_log_dir() -> PathBuf {
126    env::var("START_LOG_DIR")
127        .map(PathBuf::from)
128        .unwrap_or_else(|_| get_temp_root().join("logs"))
129}
130
131/// Get a start-command temporary directory for sidecar files.
132pub fn get_temp_dir(segments: &[&str]) -> PathBuf {
133    let mut dir = get_temp_root().join("tmp");
134    for segment in segments {
135        dir.push(segment);
136    }
137    let _ = fs::create_dir_all(&dir);
138    dir
139}
140
141/// Create log file path
142pub fn create_log_path(environment: &str) -> PathBuf {
143    let log_dir = get_log_dir();
144    let log_filename = generate_log_filename(environment);
145    if environment == "direct" {
146        log_dir.join("direct").join(log_filename)
147    } else {
148        log_dir
149            .join("isolation")
150            .join(environment)
151            .join(log_filename)
152    }
153}
154
155/// Create stable log file path for a specific execution UUID/session ID.
156pub fn create_log_path_for_execution(environment: &str, execution_id: &str) -> PathBuf {
157    if environment == "direct" {
158        get_log_dir()
159            .join("direct")
160            .join(format!("{}.log", execution_id))
161    } else {
162        get_log_dir()
163            .join("isolation")
164            .join(environment)
165            .join(format!("{}.log", execution_id))
166    }
167}
168
169pub fn shell_quote(value: &str) -> String {
170    format!("'{}'", value.replace('\'', "'\\''"))
171}
172
173pub fn create_shell_log_footer_snippet() -> String {
174    let date_command = "date '+%Y-%m-%d %H:%M:%S.%3N' 2>/dev/null || date '+%Y-%m-%d %H:%M:%S'";
175    format!(
176        "printf '\\n==================================================\\nFinished: %s\\nExit Code: %s\\n' \"$({})\" \"$__start_command_exit\"",
177        date_command
178    )
179}
180
181pub fn wrap_command_with_log_footer(command: &str, shell: &str, keep_alive: bool) -> String {
182    let after_footer = if keep_alive {
183        format!("exec {}", shell_quote(shell))
184    } else {
185        "exit \"$__start_command_exit\"".to_string()
186    };
187    format!(
188        "({}); __start_command_exit=$?; {}; {}",
189        command,
190        create_shell_log_footer_snippet(),
191        after_footer
192    )
193}
194
195/// Get the default Docker image based on the host operating system
196/// Returns an image that matches the current OS as closely as possible:
197/// - macOS: Uses alpine (since macOS cannot run in Docker)
198/// - Ubuntu/Debian: Uses ubuntu:latest
199/// - Arch Linux: Uses archlinux:latest
200/// - Other Linux: Uses the detected distro or alpine as fallback
201/// - Windows: Uses alpine (Windows containers have limited support)
202pub fn get_default_docker_image() -> String {
203    #[cfg(target_os = "macos")]
204    {
205        // macOS cannot run in Docker containers, use alpine as lightweight alternative
206        return "alpine:latest".to_string();
207    }
208
209    #[cfg(target_os = "windows")]
210    {
211        // Windows containers have limited support, use alpine for Linux containers
212        return "alpine:latest".to_string();
213    }
214
215    #[cfg(target_os = "linux")]
216    {
217        use std::fs;
218        // Try to detect the Linux distribution
219        if let Ok(os_release) = fs::read_to_string("/etc/os-release") {
220            // Check for Ubuntu
221            if os_release.contains("ID=ubuntu")
222                || os_release.contains("ID_LIKE=ubuntu")
223                || os_release.contains("ID_LIKE=debian ubuntu")
224            {
225                return "ubuntu:latest".to_string();
226            }
227
228            // Check for Debian
229            if os_release.contains("ID=debian") || os_release.contains("ID_LIKE=debian") {
230                return "debian:latest".to_string();
231            }
232
233            // Check for Arch Linux
234            if os_release.contains("ID=arch") || os_release.contains("ID_LIKE=arch") {
235                return "archlinux:latest".to_string();
236            }
237
238            // Check for Fedora
239            if os_release.contains("ID=fedora") {
240                return "fedora:latest".to_string();
241            }
242
243            // Check for CentOS/RHEL
244            if os_release.contains("ID=centos")
245                || os_release.contains("ID=rhel")
246                || os_release.contains("ID_LIKE=rhel")
247            {
248                return "centos:latest".to_string();
249            }
250
251            // Check for Alpine
252            if os_release.contains("ID=alpine") {
253                return "alpine:latest".to_string();
254            }
255        }
256
257        // Default fallback: use alpine as a lightweight, universal option
258        "alpine:latest".to_string()
259    }
260
261    // Fallback for other platforms
262    #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
263    {
264        "alpine:latest".to_string()
265    }
266}