xbp 0.3.5

XBP is a build pack and deployment management tool to deploy, rust, nextjs etc and manage the NGINX configs below it
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
//! Comprehensive logging system for XBP
//!
//! This module provides structured logging to /var/log/xbp/ with automatic
//! log rotation, different log levels, and command-specific log files.

use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};


/// Log levels for different types of operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LogLevel {
    Info,
    Warning,
    Error,
    Debug,
    Success,
}

impl LogLevel {
    fn to_string(&self) -> &'static str {
        match self {
            LogLevel::Info => "INFO",
            LogLevel::Warning => "WARN",
            LogLevel::Error => "ERROR",
            LogLevel::Debug => "DEBUG",
            LogLevel::Success => "SUCCESS",
        }
    }

    fn color_code(&self) -> &'static str {
        match self {
            LogLevel::Info => "\x1b[94m",      // Blue
            LogLevel::Warning => "\x1b[93m",   // Yellow
            LogLevel::Error => "\x1b[91m",     // Red
            LogLevel::Debug => "\x1b[90m",     // Gray
            LogLevel::Success => "\x1b[92m",   // Green
        }
    }
}

/// Structured log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogEntry {
    pub timestamp: DateTime<Local>,
    pub level: LogLevel,
    pub command: String,
    pub message: String,
    pub details: Option<String>,
    pub duration_ms: Option<u64>,
}

/// Logger instance for XBP operations
pub struct XbpLogger {
    log_dir: PathBuf,
    debug_enabled: bool,
}

impl XbpLogger {
    /// Create a new XBP logger instance
    pub async fn new(debug: bool) -> Result<Self, String> {
        let log_dir = PathBuf::from("/var/log/xbp");
        
        // Create log directory with proper permissions
        Self::ensure_log_directory(&log_dir).await?;
        
        let logger = XbpLogger {
            log_dir,
            debug_enabled: debug,
        };

        // Log the logger initialization directly to avoid recursion
        logger.write_log(LogLevel::Info, "system", "XBP Logger initialized", None, None).await?;
        
        Ok(logger)
    }

    /// Ensure the log directory exists with proper permissions
    async fn ensure_log_directory(log_dir: &Path) -> Result<(), String> {
        if !log_dir.exists() {
            // Try to create the directory
            if let Err(e) = fs::create_dir_all(log_dir) {
                // If we can't create in /var/log/xbp, fall back to user directory
                let fallback_dir = dirs::home_dir()
                    .unwrap_or_else(|| PathBuf::from("."))
                    .join(".xbp")
                    .join("logs");
                
                fs::create_dir_all(&fallback_dir)
                    .map_err(|e| format!("Failed to create log directory: {}", e))?;
                
                println!("\x1b[93mWarning: Could not create /var/log/xbp ({}), using {}\x1b[0m", 
                         e, fallback_dir.display());
                return Ok(());
            }
        }

        // Set proper permissions (readable/writable by owner, readable by group)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let permissions = std::fs::Permissions::from_mode(0o755);
            fs::set_permissions(log_dir, permissions)
                .map_err(|e| format!("Failed to set log directory permissions: {}", e))?;
        }

        Ok(())
    }

    /// Log an info message
    pub async fn log_info(&self, command: &str, message: &str, details: Option<&str>) -> Result<(), String> {
        self.write_log(LogLevel::Info, command, message, details, None).await
    }

    /// Log a warning message
    pub async fn log_warning(&self, command: &str, message: &str, details: Option<&str>) -> Result<(), String> {
        self.write_log(LogLevel::Warning, command, message, details, None).await
    }

    /// Log an error message
    pub async fn log_error(&self, command: &str, message: &str, details: Option<&str>) -> Result<(), String> {
        self.write_log(LogLevel::Error, command, message, details, None).await
    }

    /// Log a success message
    pub async fn log_success(&self, command: &str, message: &str, details: Option<&str>) -> Result<(), String> {
        self.write_log(LogLevel::Success, command, message, details, None).await
    }

    /// Log a debug message (only if debug is enabled)
    pub async fn log_debug(&self, command: &str, message: &str, details: Option<&str>) -> Result<(), String> {
        if self.debug_enabled {
            self.write_log(LogLevel::Debug, command, message, details, None).await
        } else {
            Ok(())
        }
    }

    /// Log a timed operation
    pub async fn log_timed(&self, level: LogLevel, command: &str, message: &str, duration_ms: u64) -> Result<(), String> {
        self.write_log(level, command, message, None, Some(duration_ms)).await
    }

    /// Write log entry to both console and file
    async fn write_log(
        &self,
        level: LogLevel,
        command: &str,
        message: &str,
        details: Option<&str>,
        duration_ms: Option<u64>,
    ) -> Result<(), String> {
        let entry = LogEntry {
            timestamp: Local::now(),
            level: level.clone(),
            command: command.to_string(),
            message: message.to_string(),
            details: details.map(|s| s.to_string()),
            duration_ms,
        };

        // Write to console
        self.write_console(&entry);

        // Write to file
        self.write_file(&entry).await?;

        Ok(())
    }

    /// Write log entry to console with colors
    fn write_console(&self, entry: &LogEntry) {
        let color = entry.level.color_code();
        let reset = "\x1b[0m";
        let timestamp = entry.timestamp.format("%H:%M:%S");
        
        let duration_str = if let Some(duration) = entry.duration_ms {
            format!(" ({:.2}ms)", duration)
        } else {
            String::new()
        };

        println!("{}[{}] [{}] {}: {}{}{}", 
                 color, 
                 timestamp, 
                 entry.level.to_string(), 
                 entry.command, 
                 entry.message,
                 duration_str,
                 reset);

        if let Some(details) = &entry.details {
            println!("  {}{}{}", color, details, reset);
        }
    }

    /// Write log entry to file
    async fn write_file(&self, entry: &LogEntry) -> Result<(), String> {
        // Create log file paths
        let date_str = entry.timestamp.format("%Y-%m-%d");
        let general_log = self.log_dir.join(format!("xbp-{}.log", date_str));
        let command_log = self.log_dir.join(format!("{}-{}.log", entry.command, date_str));

        // Prepare log line
        let duration_str = if let Some(duration) = entry.duration_ms {
            format!(" duration={}ms", duration)
        } else {
            String::new()
        };

        let details_str = if let Some(details) = &entry.details {
            format!(" details=\"{}\"", details.replace('"', "'"))
        } else {
            String::new()
        };

        let log_line = format!(
            "{} level={} command={} message=\"{}\"{}{}\n",
            entry.timestamp.format("%Y-%m-%d %H:%M:%S%.3f"),
            entry.level.to_string(),
            entry.command,
            entry.message.replace('"', "'"),
            details_str,
            duration_str
        );

        // Write to general log
        self.append_to_file(&general_log, &log_line).await?;

        // Write to command-specific log
        self.append_to_file(&command_log, &log_line).await?;

        // Rotate logs if necessary
        self.rotate_logs_if_needed(&general_log).await?;
        self.rotate_logs_if_needed(&command_log).await?;

        Ok(())
    }

    /// Append content to a log file
    async fn append_to_file(&self, file_path: &Path, content: &str) -> Result<(), String> {
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(file_path)
            .map_err(|e| format!("Failed to open log file {}: {}", file_path.display(), e))?;

        file.write_all(content.as_bytes())
            .map_err(|e| format!("Failed to write to log file: {}", e))?;

        Ok(())
    }

    /// Rotate logs if they exceed size limit (10MB)
    async fn rotate_logs_if_needed(&self, file_path: &Path) -> Result<(), String> {
        if let Ok(metadata) = fs::metadata(file_path) {
            const MAX_SIZE: u64 = 10 * 1024 * 1024; // 10MB
            
            if metadata.len() > MAX_SIZE {
                let rotated_path = file_path.with_extension(
                    format!("log.{}", Local::now().format("%H%M%S"))
                );
                
                fs::rename(file_path, &rotated_path)
                    .map_err(|e| format!("Failed to rotate log file: {}", e))?;
                
                // Log rotation directly to avoid recursion
                let entry = LogEntry {
                    timestamp: Local::now(),
                    level: LogLevel::Info,
                    command: "system".to_string(),
                    message: format!("Rotated log file to {}", rotated_path.display()),
                    details: None,
                    duration_ms: None,
                };
                self.write_console(&entry);
            }
        }
        
        Ok(())
    }

    /// Log command execution with timing
    pub async fn log_command_execution(
        &self,
        command: &str,
        cmd_args: &[&str],
        start_time: std::time::Instant,
    ) -> Result<(), String> {
        let duration = start_time.elapsed();
        let duration_ms = duration.as_millis() as u64;
        
        let full_command = format!("{} {}", command, cmd_args.join(" "));
        
        self.log_timed(
            LogLevel::Info,
            "command",
            &format!("Executed: {}", full_command),
            duration_ms,
        ).await
    }

    /// Log process output
    pub async fn log_process_output(
        &self,
        command: &str,
        process_name: &str,
        stdout: &str,
        stderr: &str,
    ) -> Result<(), String> {
        if !stdout.is_empty() {
            self.log_info(command, 
                         &format!("{} stdout", process_name), 
                         Some(stdout)).await?;
        }
        
        if !stderr.is_empty() {
            self.log_warning(command, 
                            &format!("{} stderr", process_name), 
                            Some(stderr)).await?;
        }
        
        Ok(())
    }

    /// Get log directory path
    pub fn log_dir(&self) -> &Path {
        &self.log_dir
    }

    /// List available log files
    pub async fn list_log_files(&self) -> Result<Vec<PathBuf>, String> {
        let mut files = Vec::new();
        
        let entries = fs::read_dir(&self.log_dir)
            .map_err(|e| format!("Failed to read log directory: {}", e))?;
        
        for entry in entries {
            let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
            let path = entry.path();
            
            if path.is_file() && path.extension().map_or(false, |ext| ext == "log") {
                files.push(path);
            }
        }
        
        files.sort();
        Ok(files)
    }

    /// Read recent log entries from a specific log file
    pub async fn read_recent_logs(&self, file_path: &Path, lines: usize) -> Result<Vec<String>, String> {
        let content = fs::read_to_string(file_path)
            .map_err(|e| format!("Failed to read log file: {}", e))?;
        
        let all_lines: Vec<&str> = content.lines().collect();
        let recent_lines = if all_lines.len() > lines {
            &all_lines[all_lines.len() - lines..]
        } else {
            &all_lines
        };
        
        Ok(recent_lines.iter().map(|s| s.to_string()).collect())
    }
}

/// Global logger instance
static mut LOGGER: Option<XbpLogger> = None;

/// Initialize the global logger
pub async fn init_logger(debug: bool) -> Result<(), String> {
    let logger = XbpLogger::new(debug).await?;
    
    unsafe {
        LOGGER = Some(logger);
    }
    
    Ok(())
}

/// Get the global logger instance
pub fn get_logger() -> Option<&'static XbpLogger> {
    unsafe { LOGGER.as_ref() }
}

/// Convenience macro for logging
#[macro_export]
macro_rules! xbp_log {
    (info, $command:expr, $message:expr) => {
        if let Some(logger) = crate::logging::get_logger() {
            let _ = logger.log_info($command, $message, None).await;
        }
    };
    (info, $command:expr, $message:expr, $details:expr) => {
        if let Some(logger) = crate::logging::get_logger() {
            let _ = logger.log_info($command, $message, Some($details)).await;
        }
    };
    (warning, $command:expr, $message:expr) => {
        if let Some(logger) = crate::logging::get_logger() {
            let _ = logger.log_warning($command, $message, None).await;
        }
    };
    (error, $command:expr, $message:expr) => {
        if let Some(logger) = crate::logging::get_logger() {
            let _ = logger.log_error($command, $message, None).await;
        }
    };
    (success, $command:expr, $message:expr) => {
        if let Some(logger) = crate::logging::get_logger() {
            let _ = logger.log_success($command, $message, None).await;
        }
    };
    (debug, $command:expr, $message:expr) => {
        if let Some(logger) = crate::logging::get_logger() {
            let _ = logger.log_debug($command, $message, None).await;
        }
    };
}