zlayer-builder 0.14.0

Dockerfile parsing and buildah-based container image building
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
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
//! Buildah command execution
//!
//! This module provides functionality to execute buildah commands,
//! with support for both synchronous and streaming output.

use std::ffi::OsString;
use std::path::PathBuf;
use std::process::Stdio;

use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
use tracing::{debug, error, instrument, trace};

use crate::error::{BuildError, Result};

use super::BuildahCommand;

/// Output from a buildah command execution
#[derive(Debug, Clone)]
pub struct CommandOutput {
    /// Standard output from the command
    pub stdout: String,

    /// Standard error from the command
    pub stderr: String,

    /// Exit code (0 = success)
    pub exit_code: i32,
}

impl CommandOutput {
    /// Returns true if the command succeeded (exit code 0)
    #[must_use]
    pub fn success(&self) -> bool {
        self.exit_code == 0
    }

    /// Returns the combined stdout and stderr
    #[must_use]
    pub fn combined_output(&self) -> String {
        if self.stderr.is_empty() {
            self.stdout.clone()
        } else if self.stdout.is_empty() {
            self.stderr.clone()
        } else {
            format!("{}\n{}", self.stdout, self.stderr)
        }
    }
}

/// How buildah commands are executed.
#[derive(Debug, Clone, Default)]
pub enum BuildahTransport {
    /// Run buildah as a local process (default; current behavior).
    #[default]
    Local,
    /// Run buildah inside a WSL2 distro: `wsl.exe -d <distro> -- buildah ...`.
    Wsl {
        /// Name of the WSL2 distribution to run buildah inside.
        distro: String,
    },
}

/// Executor for buildah commands
#[derive(Debug, Clone)]
pub struct BuildahExecutor {
    /// Path to the buildah binary
    buildah_path: PathBuf,

    /// Default storage driver (if set)
    storage_driver: Option<String>,

    /// Root directory for buildah storage
    root: Option<PathBuf>,

    /// Run directory for buildah state
    runroot: Option<PathBuf>,

    /// How buildah commands are executed (local process or inside WSL2).
    transport: BuildahTransport,
}

impl Default for BuildahExecutor {
    fn default() -> Self {
        Self {
            buildah_path: PathBuf::from("buildah"),
            storage_driver: None,
            root: None,
            runroot: None,
            transport: BuildahTransport::Local,
        }
    }
}

impl BuildahExecutor {
    /// Create a new `BuildahExecutor`, locating the buildah binary (sync version)
    ///
    /// This will search for buildah in common system locations and PATH.
    /// For more comprehensive discovery with version checking, use [`new_async`].
    ///
    /// # Errors
    ///
    /// Returns an error if buildah is not found in common system locations or PATH.
    pub fn new() -> Result<Self> {
        let buildah_path = which_buildah()?;
        Ok(Self {
            buildah_path,
            storage_driver: None,
            root: None,
            runroot: None,
            transport: BuildahTransport::Local,
        })
    }

    /// Create a new `BuildahExecutor` using the `BuildahInstaller`
    ///
    /// This async version uses [`BuildahInstaller`] to find buildah and verify
    /// it meets minimum version requirements. If buildah is not found, it returns
    /// a helpful error with installation instructions.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use zlayer_builder::BuildahExecutor;
    ///
    /// # async fn example() -> Result<(), zlayer_builder::BuildError> {
    /// let executor = BuildahExecutor::new_async().await?;
    /// let version = executor.version().await?;
    /// println!("Using buildah version: {}", version);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if buildah is not installed or does not meet the minimum version.
    pub async fn new_async() -> Result<Self> {
        use super::install::BuildahInstaller;

        let installer = BuildahInstaller::new();
        let installation = installer
            .ensure()
            .await
            .map_err(|e| BuildError::BuildahNotFound {
                message: e.to_string(),
            })?;

        Ok(Self {
            buildah_path: installation.path,
            storage_driver: None,
            root: None,
            runroot: None,
            transport: BuildahTransport::Local,
        })
    }

    /// Create a `BuildahExecutor` with a specific path to the buildah binary
    pub fn with_path(path: impl Into<PathBuf>) -> Self {
        Self {
            buildah_path: path.into(),
            storage_driver: None,
            root: None,
            runroot: None,
            transport: BuildahTransport::Local,
        }
    }

    /// Set the storage driver
    #[must_use]
    pub fn storage_driver(mut self, driver: impl Into<String>) -> Self {
        self.storage_driver = Some(driver.into());
        self
    }

    /// Set the root directory for buildah storage
    #[must_use]
    pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
        self.root = Some(root.into());
        self
    }

    /// Set the runroot directory for buildah state
    #[must_use]
    pub fn runroot(mut self, runroot: impl Into<PathBuf>) -> Self {
        self.runroot = Some(runroot.into());
        self
    }

    /// Set the transport used to run buildah commands.
    ///
    /// Defaults to [`BuildahTransport::Local`] (run buildah as a local
    /// process). Use [`BuildahTransport::Wsl`] to run every `buildah`
    /// invocation inside a WSL2 distro via `wsl.exe -d <distro> -- buildah …`.
    #[must_use]
    pub fn with_transport(mut self, t: BuildahTransport) -> Self {
        self.transport = t;
        self
    }

    /// Get the path to the buildah binary
    #[must_use]
    pub fn buildah_path(&self) -> &PathBuf {
        &self.buildah_path
    }

    /// Build the base tokio Command with global options.
    ///
    /// The "global flags + subcommand args" assembly is built once into a
    /// single `argv` vector that BOTH transports consume, so the local and
    /// WSL paths cannot drift in flag/arg ordering.
    fn build_command(&self, cmd: &BuildahCommand) -> Command {
        // Assemble global options (before the subcommand) followed by the
        // command's own arguments. Identical for every transport.
        let mut argv: Vec<OsString> = Vec::new();

        if let Some(ref driver) = self.storage_driver {
            argv.push(OsString::from("--storage-driver"));
            argv.push(OsString::from(driver));
        }

        if let Some(ref root) = self.root {
            argv.push(OsString::from("--root"));
            argv.push(root.clone().into_os_string());
        }

        if let Some(ref runroot) = self.runroot {
            argv.push(OsString::from("--runroot"));
            argv.push(runroot.clone().into_os_string());
        }

        for arg in &cmd.args {
            argv.push(OsString::from(arg));
        }

        match &self.transport {
            BuildahTransport::Local => {
                let mut command = Command::new(&self.buildah_path);
                command.args(&argv);

                // Local processes inherit the parent env; per-command vars are
                // injected directly via `.env(K, V)`.
                for (key, value) in &cmd.env {
                    command.env(key, value);
                }

                command
            }
            BuildahTransport::Wsl { distro } => {
                // `wsl.exe -d <distro> -- [env K=V ...] buildah <flags> <args>`
                //
                // WSL does NOT inherit the Win32 process environment into the
                // distro, so any per-command env vars must be passed as
                // `env K=V` argv tokens INSIDE the distro (prepended to the
                // buildah argv), not via `.env()` on the `wsl.exe` Command.
                let mut command = Command::new("wsl.exe");
                command.arg("-d").arg(distro).arg("--");

                if !cmd.env.is_empty() {
                    command.arg("env");
                    // Sort keys for deterministic argv ordering (HashMap
                    // iteration order is unspecified).
                    let mut keys: Vec<&String> = cmd.env.keys().collect();
                    keys.sort();
                    for key in keys {
                        if let Some(value) = cmd.env.get(key) {
                            command.arg(format!("{key}={value}"));
                        }
                    }
                }

                command.arg(&self.buildah_path);
                // Translate Windows drive-rooted paths (`C:\...` / `C:/...`) to
                // their `/mnt/<drive>/...` form so the in-distro buildah can read
                // the Windows-side build context + rendered Dockerfile. Image
                // refs (`name:tag`) and flags must pass through untouched.
                for a in &argv {
                    let s = a.to_string_lossy();
                    let bytes = s.as_bytes();
                    // Translate ONLY a true drive root (`X:\` or `X:/`), never a
                    // bare `X:` (which would corrupt refs like `c:latest`).
                    let is_drive_root = bytes.len() >= 3
                        && bytes[0].is_ascii_alphabetic()
                        && bytes[1] == b':'
                        && (bytes[2] == b'\\' || bytes[2] == b'/');
                    if is_drive_root {
                        if let Some(w) =
                            zlayer_wsl::paths::windows_to_wsl(std::path::Path::new(&*s))
                        {
                            command.arg(w);
                            continue;
                        }
                    }
                    command.arg(a);
                }

                command
            }
        }
    }

    /// Execute a buildah command and wait for completion
    ///
    /// # Errors
    ///
    /// Returns an error if the buildah process fails to spawn.
    #[instrument(skip(self), fields(command = %cmd.to_command_string()))]
    pub async fn execute(&self, cmd: &BuildahCommand) -> Result<CommandOutput> {
        debug!("Executing buildah command");
        trace!("Full command: {:?}", cmd);

        let mut command = self.build_command(cmd);
        command.stdout(Stdio::piped()).stderr(Stdio::piped());

        let output = command.output().await.map_err(|e| {
            error!("Failed to spawn buildah process: {}", e);
            BuildError::IoError(e)
        })?;

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();
        let exit_code = output.status.code().unwrap_or(-1);

        if !output.status.success() {
            debug!(
                "Buildah command failed with exit code {}: {}",
                exit_code,
                stderr.trim()
            );
        }

        Ok(CommandOutput {
            stdout,
            stderr,
            exit_code,
        })
    }

    /// Execute a buildah command and return an error if it fails
    ///
    /// # Errors
    ///
    /// Returns an error if the process fails to spawn or exits with a non-zero code.
    pub async fn execute_checked(&self, cmd: &BuildahCommand) -> Result<CommandOutput> {
        let output = self.execute(cmd).await?;

        if !output.success() {
            return Err(BuildError::BuildahExecution {
                command: cmd.to_command_string(),
                exit_code: output.exit_code,
                stderr: output.stderr,
            });
        }

        Ok(output)
    }

    /// Create a manifest list, removing any stale list or plain image of the
    /// same name first so the operation is idempotent / re-runnable.
    ///
    /// `buildah manifest create <ref>` fails (exit 125) when a manifest list —
    /// or a plain image left behind by a partially-completed prior run — is
    /// already associated with `<ref>` (`image name "…" is already in use`).
    /// To make multi-arch assembly re-runnable after such a partial run, we
    /// best-effort remove any pre-existing manifest list (`manifest rm`) AND
    /// any plain image (`rmi -f`) of that exact name before creating fresh.
    /// Both removals ignore "not found"/non-zero — a clean store no-ops them.
    ///
    /// # Errors
    ///
    /// Returns an error only if the final `manifest create` itself fails.
    pub async fn manifest_create_idempotent(&self, name: &str) -> Result<()> {
        // Best-effort cleanup of stale state — ignore errors (e.g. "not found").
        let _ = self.execute(&BuildahCommand::manifest_rm(name)).await;
        let _ = self.execute(&BuildahCommand::rmi_force(name)).await;
        self.execute_checked(&BuildahCommand::manifest_create(name))
            .await?;
        Ok(())
    }

    /// Execute a buildah command with streaming output
    ///
    /// The callback is called for each line of output (both stdout and stderr).
    /// The first parameter indicates whether it's stdout (true) or stderr (false).
    ///
    /// # Errors
    ///
    /// Returns an error if the process fails to spawn or an I/O error occurs.
    ///
    /// # Panics
    ///
    /// Panics if stdout or stderr pipes are unexpectedly missing (should not happen
    /// since they are explicitly configured as piped).
    #[instrument(skip(self, on_output), fields(command = %cmd.to_command_string()))]
    pub async fn execute_streaming<F>(
        &self,
        cmd: &BuildahCommand,
        mut on_output: F,
    ) -> Result<CommandOutput>
    where
        F: FnMut(bool, &str),
    {
        debug!("Executing buildah command with streaming output");

        let mut command = self.build_command(cmd);
        command.stdout(Stdio::piped()).stderr(Stdio::piped());

        let mut child = command.spawn().map_err(|e| {
            error!("Failed to spawn buildah process: {}", e);
            BuildError::IoError(e)
        })?;

        let stdout = child.stdout.take().expect("stdout was piped");
        let stderr = child.stderr.take().expect("stderr was piped");

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

        let mut stdout_output = String::new();
        let mut stderr_output = String::new();

        // Read stdout and stderr concurrently
        loop {
            tokio::select! {
                line = stdout_reader.next_line() => {
                    match line {
                        Ok(Some(line)) => {
                            on_output(true, &line);
                            stdout_output.push_str(&line);
                            stdout_output.push('\n');
                        }
                        Ok(None) => {}
                        Err(e) => {
                            error!("Error reading stdout: {}", e);
                        }
                    }
                }
                line = stderr_reader.next_line() => {
                    match line {
                        Ok(Some(line)) => {
                            on_output(false, &line);
                            stderr_output.push_str(&line);
                            stderr_output.push('\n');
                        }
                        Ok(None) => {}
                        Err(e) => {
                            error!("Error reading stderr: {}", e);
                        }
                    }
                }
                status = child.wait() => {
                    let status = status.map_err(BuildError::IoError)?;
                    let exit_code = status.code().unwrap_or(-1);

                    // Drain remaining output
                    while let Ok(Some(line)) = stdout_reader.next_line().await {
                        on_output(true, &line);
                        stdout_output.push_str(&line);
                        stdout_output.push('\n');
                    }
                    while let Ok(Some(line)) = stderr_reader.next_line().await {
                        on_output(false, &line);
                        stderr_output.push_str(&line);
                        stderr_output.push('\n');
                    }

                    return Ok(CommandOutput {
                        stdout: stdout_output,
                        stderr: stderr_output,
                        exit_code,
                    });
                }
            }
        }
    }

    /// Check if buildah is available
    pub async fn is_available(&self) -> bool {
        let cmd = BuildahCommand::new("version");
        self.execute(&cmd).await.is_ok_and(|o| o.success())
    }

    /// Get buildah version information
    ///
    /// # Errors
    ///
    /// Returns an error if the version command fails to execute.
    pub async fn version(&self) -> Result<String> {
        let cmd = BuildahCommand::new("version");
        let output = self.execute_checked(&cmd).await?;
        Ok(output.stdout.trim().to_string())
    }
}

/// Find the buildah binary in PATH
fn which_buildah() -> Result<PathBuf> {
    // Check common locations
    let candidates = ["/usr/bin/buildah", "/usr/local/bin/buildah", "/bin/buildah"];

    for path in &candidates {
        let path = PathBuf::from(path);
        if path.exists() {
            return Ok(path);
        }
    }

    // Try using `which` command
    let output = std::process::Command::new("which")
        .arg("buildah")
        .output()
        .ok();

    if let Some(output) = output {
        if output.status.success() {
            let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if !path.is_empty() {
                return Ok(PathBuf::from(path));
            }
        }
    }

    Err(BuildError::IoError(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        "buildah not found in PATH",
    )))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_command_output_success() {
        let output = CommandOutput {
            stdout: "success".to_string(),
            stderr: String::new(),
            exit_code: 0,
        };
        assert!(output.success());
    }

    #[test]
    fn test_command_output_failure() {
        let output = CommandOutput {
            stdout: String::new(),
            stderr: "error".to_string(),
            exit_code: 1,
        };
        assert!(!output.success());
    }

    #[test]
    fn test_command_output_combined() {
        let output = CommandOutput {
            stdout: "out".to_string(),
            stderr: "err".to_string(),
            exit_code: 0,
        };
        assert_eq!(output.combined_output(), "out\nerr");
    }

    #[test]
    fn test_executor_builder() {
        let executor = BuildahExecutor::with_path("/custom/buildah")
            .storage_driver("overlay")
            .root("/var/lib/containers")
            .runroot("/run/containers");

        assert_eq!(executor.buildah_path, PathBuf::from("/custom/buildah"));
        assert_eq!(executor.storage_driver, Some("overlay".to_string()));
        assert_eq!(executor.root, Some(PathBuf::from("/var/lib/containers")));
        assert_eq!(executor.runroot, Some(PathBuf::from("/run/containers")));
    }

    // Integration tests would require buildah to be installed
    #[tokio::test]
    #[ignore = "requires buildah to be installed"]
    async fn test_execute_version() {
        let executor = BuildahExecutor::new().expect("buildah should be available");
        let version = executor.version().await.expect("should get version");
        assert!(!version.is_empty());
    }

    #[tokio::test]
    #[ignore = "requires buildah to be installed"]
    async fn test_execute_streaming() {
        let executor = BuildahExecutor::new().expect("buildah should be available");
        let cmd = BuildahCommand::new("version");

        let mut lines = Vec::new();
        let output = executor
            .execute_streaming(&cmd, |_is_stdout, line| {
                lines.push(line.to_string());
            })
            .await
            .expect("should execute");

        assert!(output.success());
        assert!(!lines.is_empty());
    }
}