-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprocess_runner.rs
More file actions
737 lines (647 loc) · 22.5 KB
/
process_runner.rs
File metadata and controls
737 lines (647 loc) · 22.5 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! External Process Execution
//!
//! Provides utilities for running the production application as an external
//! process for black-box testing.
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
/// Runs the production application as an external process
///
/// This struct provides methods for executing the application binary
/// with different command-line arguments for black-box testing.
///
/// By default the runner falls back to `cargo run --` so it can be used
/// from `src/bin/` programs that do not have a pre-built binary available.
/// In integration tests (`tests/`), you should always call
/// [`with_binary`](Self::with_binary) with
/// `env!("CARGO_BIN_EXE_torrust-tracker-deployer")` so that Cargo's
/// pre-built binary is used directly, eliminating ~13 s of `cargo run`
/// startup overhead per invocation.
pub struct ProcessRunner {
working_dir: Option<PathBuf>,
log_dir: Option<PathBuf>,
/// Path to the pre-built binary. When `None`, falls back to `cargo run`.
binary: Option<PathBuf>,
}
impl ProcessRunner {
/// Create a new process runner
///
/// Falls back to `cargo run --` for executing the application. In
/// integration tests prefer [`with_binary`](Self::with_binary) to avoid
/// the ~13 s `cargo run` startup overhead.
#[must_use]
pub fn new() -> Self {
Self {
working_dir: None,
log_dir: None,
binary: None,
}
}
/// Set the pre-built binary to use instead of `cargo run`.
///
/// In integration tests pass `env!("CARGO_BIN_EXE_torrust-tracker-deployer")`
/// here. Cargo automatically builds the binary before running the
/// integration test, so the binary is always up-to-date.
#[must_use]
pub fn with_binary<P: AsRef<Path>>(mut self, binary: P) -> Self {
self.binary = Some(binary.as_ref().to_path_buf());
self
}
/// Build the base [`Command`] for the application.
///
/// When a binary path is set, returns `Command::new(binary)`.
/// Otherwise returns `Command::new("cargo")` pre-loaded with
/// `["run", "--"]` so callers only need to append sub-command args.
fn make_command(&self) -> Command {
if let Some(binary) = &self.binary {
Command::new(binary)
} else {
let mut cmd = Command::new("cargo");
cmd.args(["run", "--"]);
cmd
}
}
/// Set the working directory for the test process (not the app working dir)
///
/// This is the directory where the test command will be executed from,
/// typically a temporary directory for test isolation.
#[must_use]
pub fn working_dir<P: AsRef<Path>>(mut self, dir: P) -> Self {
self.working_dir = Some(dir.as_ref().to_path_buf());
self
}
/// Set the log directory for the application
///
/// This is passed as `--log-dir` to the application to control where
/// logs are written, enabling test isolation.
#[must_use]
pub fn log_dir<P: AsRef<Path>>(mut self, dir: P) -> Self {
self.log_dir = Some(dir.as_ref().to_path_buf());
self
}
/// Run the create command with the production binary
///
/// This method runs `create environment --env-file <config_file>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory or config file path contains invalid UTF-8.
pub fn run_create_command(&self, config_file: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
// If working directory is specified, we need to:
// 1. Make the config file path absolute (the binary runs from project root)
// 2. Pass --working-dir to tell the app where to store data
if let Some(working_dir) = &self.working_dir {
// Convert config file to absolute path
let absolute_config = if config_file.starts_with("./") {
working_dir.join(config_file.trim_start_matches("./"))
} else {
working_dir.join(config_file)
};
// Build command with absolute paths
cmd.args([
"create",
"environment",
"--env-file",
absolute_config.to_str().unwrap(),
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
// No working directory, use relative paths
cmd.args(["create", "environment", "--env-file", config_file]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute create command")?;
Ok(ProcessResult::new(output))
}
/// Run the provision command with the production binary
///
/// This method runs `provision <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_provision_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
// Build command with working directory
cmd.args([
"provision",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["provision", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd
.output()
.context("Failed to execute provision command")?;
Ok(ProcessResult::new(output))
}
/// Run the destroy command with the production binary
///
/// This method runs `destroy <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_destroy_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"destroy",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["destroy", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute destroy command")?;
Ok(ProcessResult::new(output))
}
/// Run the register command with the production binary
///
/// This method runs `register <environment_name> --instance-ip <ip>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_register_command(
&self,
environment_name: &str,
instance_ip: &str,
ssh_port: Option<u16>,
) -> Result<ProcessResult> {
let mut cmd = self.make_command();
cmd.args(["register", environment_name, "--instance-ip", instance_ip]);
// Add optional SSH port
if let Some(port) = ssh_port {
cmd.args(["--ssh-port", &port.to_string()]);
}
// Add working-dir if specified
if let Some(working_dir) = &self.working_dir {
cmd.args(["--working-dir", working_dir.to_str().unwrap()]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute register command")?;
Ok(ProcessResult::new(output))
}
/// Run the configure command with the production binary
///
/// This method runs `configure <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_configure_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"configure",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["configure", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd
.output()
.context("Failed to execute configure command")?;
Ok(ProcessResult::new(output))
}
/// Run the test command with the production binary
///
/// This method runs `test <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_test_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"test",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["test", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute test command")?;
Ok(ProcessResult::new(output))
}
/// Run the release command with the production binary
///
/// This method runs `release <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_release_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"release",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["release", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute release command")?;
Ok(ProcessResult::new(output))
}
/// Run the run command with the production binary
///
/// This method runs `run <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_run_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"run",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["run", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute run command")?;
Ok(ProcessResult::new(output))
}
/// Run the list command with the production binary
///
/// This method runs `list` with optional working directory
/// for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_list_command(&self) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args(["list", "--working-dir", working_dir.to_str().unwrap()]);
} else {
cmd.arg("list");
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute list command")?;
Ok(ProcessResult::new(output))
}
/// Run the exists command with the production binary
///
/// This method runs `exists <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_exists_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"exists",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["exists", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute exists command")?;
Ok(ProcessResult::new(output))
}
/// Run the show command with the production binary
///
/// This method runs `show <environment_name>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
pub fn run_show_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"show",
environment_name,
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["show", environment_name]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute show command")?;
Ok(ProcessResult::new(output))
}
/// Run the validate command with the production binary
///
/// This method runs `validate -f <config_file>` with
/// optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory or log directory path contains invalid UTF-8.
pub fn run_validate_command(&self, config_file: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
cmd.args(["validate", "-f", config_file]);
// Add working-dir if specified
if let Some(working_dir) = &self.working_dir {
cmd.arg("--working-dir");
cmd.arg(working_dir);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute validate command")?;
Ok(ProcessResult::new(output))
}
/// Run the purge command with the production binary
///
/// This method runs `cargo run -- purge <environment_name> --force` with
/// optional working directory for the application itself via `--working-dir`.
/// Always uses `--force` flag to skip interactive confirmation prompts in tests.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// Panics if the working directory path contains invalid UTF-8.
/// Run the render command with environment name input mode
///
/// This method runs `render --env-name <name> --instance-ip <ip> --output-dir <dir>`
/// with optional working directory for the application itself via `--working-dir`.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// May panic if the working directory path is not valid UTF-8.
pub fn run_render_command_with_env_name(
&self,
environment_name: &str,
instance_ip: &str,
output_dir: &str,
) -> Result<ProcessResult> {
let mut cmd = self.make_command();
cmd.args([
"render",
"--env-name",
environment_name,
"--instance-ip",
instance_ip,
"--output-dir",
output_dir,
]);
if let Some(working_dir) = &self.working_dir {
cmd.args(["--working-dir", working_dir.to_str().unwrap()]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd
.output()
.context("Failed to execute render command with env-name")?;
Ok(ProcessResult::new(output))
}
/// Run the render command with config file input mode
///
/// This method runs `render --env-file <path> --instance-ip <ip> --output-dir <dir>`
/// with optional working directory and log directory for test isolation.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// May panic if the working directory or log directory path is not valid UTF-8.
pub fn run_render_command_with_config_file(
&self,
config_file: &str,
instance_ip: &str,
output_dir: &str,
) -> Result<ProcessResult> {
let mut cmd = self.make_command();
cmd.args([
"render",
"--env-file",
config_file,
"--instance-ip",
instance_ip,
"--output-dir",
output_dir,
]);
// Add working-dir if specified
if let Some(working_dir) = &self.working_dir {
cmd.arg("--working-dir");
cmd.arg(working_dir);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd
.output()
.context("Failed to execute render command with env-file")?;
Ok(ProcessResult::new(output))
}
/// Run the purge command with the production binary
///
/// This method runs `purge <environment_name> --force`
/// with optional working directory for the application itself via `--working-dir`.
/// The `--force` flag is always used to skip interactive prompts.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
///
/// # Panics
///
/// May panic if the working directory path is not valid UTF-8.
pub fn run_purge_command(&self, environment_name: &str) -> Result<ProcessResult> {
let mut cmd = self.make_command();
if let Some(working_dir) = &self.working_dir {
cmd.args([
"purge",
environment_name,
"--force",
"--working-dir",
working_dir.to_str().unwrap(),
]);
} else {
cmd.args(["purge", environment_name, "--force"]);
}
// Add log-dir if specified
if let Some(log_dir) = &self.log_dir {
cmd.arg("--log-dir");
cmd.arg(log_dir);
}
let output = cmd.output().context("Failed to execute purge command")?;
Ok(ProcessResult::new(output))
}
}
impl Default for ProcessRunner {
fn default() -> Self {
Self::new()
}
}
/// Wrapper around process execution results
///
/// Provides convenient access to process output, exit status, and other
/// execution results.
pub struct ProcessResult {
output: Output,
}
impl ProcessResult {
fn new(output: Output) -> Self {
Self { output }
}
/// Check if the process completed successfully
#[must_use]
pub fn success(&self) -> bool {
self.output.status.success()
}
/// Get the process stdout as a string
#[must_use]
pub fn stdout(&self) -> String {
String::from_utf8_lossy(&self.output.stdout).to_string()
}
/// Get the process stderr as a string
#[must_use]
pub fn stderr(&self) -> String {
String::from_utf8_lossy(&self.output.stderr).to_string()
}
/// Get the process exit code
#[must_use]
pub fn exit_code(&self) -> Option<i32> {
self.output.status.code()
}
}