solarboat 0.8.9

A CLI tool for intelligent Terraform operations management with automatic dependency detection
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
use std::process::{Command, Stdio};
use std::io::{BufRead, BufReader};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use std::path::{Path, PathBuf};
use crate::utils::error::{SolarboatError, SafeOperations};

#[derive(Debug, Clone)]
pub enum TerraformStatus {
    Initializing,
    Planning,
    Applying,
    Completed { success: bool },
    Failed { error: String },
}

#[derive(Debug)]
pub struct BackgroundTerraform {
    thread_handle: Option<thread::JoinHandle<()>>,
    status: Arc<Mutex<TerraformStatus>>,
    output: Arc<Mutex<Vec<String>>>,
}

impl Default for BackgroundTerraform {
    fn default() -> Self {
        Self::new()
    }
}

impl BackgroundTerraform {
    pub fn new() -> Self {
        Self {
            thread_handle: None,
            status: Arc::new(Mutex::new(TerraformStatus::Initializing)),
            output: Arc::new(Mutex::new(Vec::new())),
        }
    }

    pub fn get_status(&self) -> Result<TerraformStatus, SolarboatError> {
        let status = SafeOperations::lock_with_timeout(
            &self.status,
            Duration::from_secs(1),
            "terraform_status"
        )?;
        Ok(status.clone())
    }

    pub fn get_output(&self) -> Result<Vec<String>, SolarboatError> {
        let output = SafeOperations::lock_with_timeout(
            &self.output,
            Duration::from_secs(1),
            "terraform_output"
        )?;
        Ok(output.clone())
    }

    pub fn is_running(&mut self) -> bool {
        if let Some(handle) = &mut self.thread_handle {
            !handle.is_finished()
        } else {
            false
        }
    }

    pub fn init_background(&mut self, module_path: &str) -> Result<(), SolarboatError> {
        let mut cmd = Command::new("terraform");
        cmd.arg("init")
           .current_dir(module_path)
           .stdout(Stdio::piped())
           .stderr(Stdio::piped());

        let mut child = cmd.spawn()
            .map_err(|e| SolarboatError::Process {
                command: "terraform init".to_string(),
                args: vec!["init".to_string()],
                cause: e.to_string(),
                exit_code: None,
            })?;

        let status = Arc::clone(&self.status);
        let output = Arc::clone(&self.output);

        // Take stdout and stderr before moving child
        let stdout = child.stdout.take().ok_or_else(|| SolarboatError::Process {
            command: "terraform init".to_string(),
            args: vec!["init".to_string()],
            cause: "Failed to capture stdout".to_string(),
            exit_code: None,
        })?;
        
        let stderr = child.stderr.take().ok_or_else(|| SolarboatError::Process {
            command: "terraform init".to_string(),
            args: vec!["init".to_string()],
            cause: "Failed to capture stderr".to_string(),
            exit_code: None,
        })?;

        // Spawn a thread to monitor the init process
        let child_handle = thread::spawn(move || {
            let stdout_reader = BufReader::new(stdout);
            let stderr_reader = BufReader::new(stderr);

            // Monitor stdout
            for line in stdout_reader.lines() {
                if let Ok(line) = line {
                    if let Ok(mut output) = SafeOperations::lock_with_timeout(
                        &output,
                        Duration::from_secs(1),
                        "output_stdout"
                    ) {
                        output.push(line.clone());
                    }
                    println!("  {}", line);
                }
            }

            // Monitor stderr
            for line in stderr_reader.lines() {
                if let Ok(line) = line {
                    if let Ok(mut output) = SafeOperations::lock_with_timeout(
                        &output,
                        Duration::from_secs(1),
                        "output_stderr"
                    ) {
                        output.push(format!("ERROR: {}", line));
                    }
                    eprintln!("  ERROR: {}", line);
                }
            }

            // Wait for process to complete
            let exit_status = match child.wait() {
                Ok(status) => status,
                Err(e) => {
                    eprintln!("Failed to wait for terraform init process: {}", e);
                    return;
                }
            };
            
            if exit_status.success() {
                if let Ok(mut status) = SafeOperations::lock_with_timeout(
                    &status,
                    Duration::from_secs(1),
                    "status_success"
                ) {
                    *status = TerraformStatus::Completed { success: true };
                }
            } else {
                if let Ok(mut status) = SafeOperations::lock_with_timeout(
                    &status,
                    Duration::from_secs(1),
                    "status_failed"
                ) {
                    *status = TerraformStatus::Failed { 
                        error: "Terraform init failed".to_string() 
                    };
                }
            }
        });

        self.thread_handle = Some(child_handle);
        Ok(())
    }

    pub fn plan_background(&mut self, module_path: &str, var_files: Option<&[String]>) -> Result<(), String> {
        let mut cmd = Command::new("terraform");
        cmd.arg("plan")
           .current_dir(module_path)
           .stdout(Stdio::piped())
           .stderr(Stdio::piped());

        // Add var files if provided
        if let Some(var_files) = var_files {
            for var_file in var_files {
                // Resolve var file path relative to module directory
                let var_file_path = if Path::new(var_file).is_absolute() {
                    PathBuf::from(var_file)
                } else {
                    // Get current working directory
                    let current_dir = std::env::current_dir()
                        .map_err(|e| format!("Failed to get current directory: {}", e))?;
                    
                    // Create absolute path to var file from current directory
                    let absolute_var_file = current_dir.join(var_file);
                    
                    // Create absolute path to module
                    let absolute_module = current_dir.join(module_path);
                    
                    // Calculate relative path from module to var file
                    match absolute_var_file.strip_prefix(&absolute_module) {
                        Ok(relative_path) => {
                            // If var file is within module directory, use relative path
                            relative_path.to_path_buf()
                        }
                        Err(_) => {
                            // If var file is outside module directory, calculate relative path
                            let mut relative_path = PathBuf::new();
                            let module_components: Vec<_> = absolute_module.components().collect();
                            let var_file_components: Vec<_> = absolute_var_file.components().collect();
                            
                            // Find common prefix
                            let mut common_len = 0;
                            for (i, (m, v)) in module_components.iter().zip(var_file_components.iter()).enumerate() {
                                if m == v {
                                    common_len = i + 1;
                                } else {
                                    break;
                                }
                            }
                            
                            // Add "../" for each component in module path after common prefix
                            for _ in common_len..module_components.len() {
                                relative_path.push("..");
                            }
                            
                            // Add remaining components from var file path
                            for component in &var_file_components[common_len..] {
                                relative_path.push(component);
                            }
                            
                            relative_path
                        }
                    }
                };
                
                cmd.arg("-var-file").arg(&var_file_path);
            }
        }

        let mut child = cmd.spawn()
            .map_err(|e| format!("Failed to start terraform plan: {}", e))?;

        let status = Arc::clone(&self.status);
        let output = Arc::clone(&self.output);

        // Take stdout and stderr before moving child
        let stdout = child.stdout.take().unwrap();
        let stderr = child.stderr.take().unwrap();

        // Spawn a thread to monitor the plan process
        let child_handle = thread::spawn(move || {
            *status.lock().unwrap() = TerraformStatus::Planning;

            let stdout_reader = BufReader::new(stdout);
            let stderr_reader = BufReader::new(stderr);

            // Monitor stdout
            for line in stdout_reader.lines() {
                if let Ok(line) = line {
                    output.lock().unwrap().push(line.clone());
                    println!("  {}", line);
                }
            }

            // Monitor stderr
            for line in stderr_reader.lines() {
                if let Ok(line) = line {
                    output.lock().unwrap().push(format!("ERROR: {}", line));
                    eprintln!("  ERROR: {}", line);
                }
            }

            // Wait for process to complete
            let exit_status = child.wait().unwrap();
            
            if exit_status.success() {
                *status.lock().unwrap() = TerraformStatus::Completed { success: true };
            } else {
                *status.lock().unwrap() = TerraformStatus::Failed { 
                    error: "Terraform plan failed".to_string() 
                };
            }
        });

        // Store the thread handle instead of the child
        self.thread_handle = Some(child_handle);
        Ok(())
    }

    pub fn apply_background(&mut self, module_path: &str, var_files: Option<&[String]>) -> Result<(), String> {
        let mut cmd = Command::new("terraform");
        cmd.arg("apply")
           .arg("-auto-approve")
           .arg("-input=false")
           .current_dir(module_path)
           .stdout(Stdio::piped())
           .stderr(Stdio::piped());

        // Add var files if provided
        if let Some(var_files) = var_files {
            for var_file in var_files {
                // Resolve var file path relative to module directory
                let var_file_path = if Path::new(var_file).is_absolute() {
                    PathBuf::from(var_file)
                } else {
                    // Get current working directory
                    let current_dir = std::env::current_dir()
                        .map_err(|e| format!("Failed to get current directory: {}", e))?;
                    
                    // Create absolute path to var file from current directory
                    let absolute_var_file = current_dir.join(var_file);
                    
                    // Create absolute path to module
                    let absolute_module = current_dir.join(module_path);
                    
                    // Calculate relative path from module to var file
                    match absolute_var_file.strip_prefix(&absolute_module) {
                        Ok(relative_path) => {
                            // If var file is within module directory, use relative path
                            relative_path.to_path_buf()
                        }
                        Err(_) => {
                            // If var file is outside module directory, calculate relative path
                            let mut relative_path = PathBuf::new();
                            let module_components: Vec<_> = absolute_module.components().collect();
                            let var_file_components: Vec<_> = absolute_var_file.components().collect();
                            
                            // Find common prefix
                            let mut common_len = 0;
                            for (i, (m, v)) in module_components.iter().zip(var_file_components.iter()).enumerate() {
                                if m == v {
                                    common_len = i + 1;
                                } else {
                                    break;
                                }
                            }
                            
                            // Add "../" for each component in module path after common prefix
                            for _ in common_len..module_components.len() {
                                relative_path.push("..");
                            }
                            
                            // Add remaining components from var file path
                            for component in &var_file_components[common_len..] {
                                relative_path.push(component);
                            }
                            
                            relative_path
                        }
                    }
                };
                
                cmd.arg("-var-file").arg(&var_file_path);
            }
        }

        let mut child = cmd.spawn()
            .map_err(|e| format!("Failed to start terraform apply: {}", e))?;

        let status = Arc::clone(&self.status);
        let output = Arc::clone(&self.output);

        // Take stdout and stderr before moving child
        let stdout = child.stdout.take().unwrap();
        let stderr = child.stderr.take().unwrap();

        // Spawn a thread to monitor the apply process
        let child_handle = thread::spawn(move || {
            *status.lock().unwrap() = TerraformStatus::Applying;

            let stdout_reader = BufReader::new(stdout);
            let stderr_reader = BufReader::new(stderr);

            // Monitor stdout
            for line in stdout_reader.lines() {
                if let Ok(line) = line {
                    output.lock().unwrap().push(line.clone());
                    println!("  {}", line);
                }
            }

            // Monitor stderr
            for line in stderr_reader.lines() {
                if let Ok(line) = line {
                    output.lock().unwrap().push(format!("ERROR: {}", line));
                    eprintln!("  ERROR: {}", line);
                }
            }

            // Wait for process to complete
            let exit_status = child.wait().unwrap();
            
            if exit_status.success() {
                *status.lock().unwrap() = TerraformStatus::Completed { success: true };
            } else {
                *status.lock().unwrap() = TerraformStatus::Failed { 
                    error: "Terraform apply failed".to_string() 
                };
            }
        });

        self.thread_handle = Some(child_handle);
        Ok(())
    }

    pub fn wait_for_completion(&mut self, timeout_seconds: u64) -> Result<bool, String> {
        let start_time = std::time::Instant::now();
        let timeout = Duration::from_secs(timeout_seconds);

        while self.is_running() {
            if start_time.elapsed() > timeout {
                return Err("Operation timed out".to_string());
            }
            thread::sleep(Duration::from_millis(100));
        }

        match self.get_status() {
            Ok(status) => match status {
                TerraformStatus::Completed { success } => Ok(success),
                TerraformStatus::Failed { error } => Err(error),
                _ => Err("Operation did not complete properly".to_string()),
            },
            Err(e) => Err(format!("Failed to get status: {}", e)),
        }
    }

    pub fn kill(&mut self) {
        // Note: We can't directly kill the child process anymore since it's in a thread
        // The thread will handle the process lifecycle
        if let Some(handle) = self.thread_handle.take() {
            // The thread will complete naturally when the process finishes
            let _ = handle.join();
        }
    }
}

pub fn run_terraform_silent(
    command: &str,
    args: &[&str],
    module_path: &str,
    var_files: Option<&[String]>,
) -> Result<bool, String> {
    let mut cmd = Command::new("terraform");
    cmd.arg(command)
       .args(args)
       .current_dir(module_path)
       .stdout(Stdio::null())
       .stderr(Stdio::null());

    // Add var files if provided
    if let Some(var_files) = var_files {
        for var_file in var_files {
            cmd.arg("-var-file").arg(var_file);
        }
    }

    let status = cmd.status()
        .map_err(|e| format!("Failed to execute terraform {}: {}", command, e))?;

    Ok(status.success())
}