microsandbox-cli 0.6.1

CLI binary for managing microsandbox environments.
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
//! `msb run` command — create and start a new sandbox.

use std::io::{IsTerminal, Write};
use std::time::Duration;

use clap::Args;
use microsandbox::sandbox::{ExecOutput, RlimitResource, Sandbox};

use super::common::{SandboxOpts, apply_sandbox_opts};
use crate::ui;

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Create a sandbox from an image and run a command in it.
#[derive(Debug, Args)]
pub struct RunArgs {
    /// Image to use (e.g. alpine, python, ./rootfs, ./disk.qcow2).
    ///
    /// Mutually exclusive with `--snapshot`; one of the two is required.
    #[arg(required_unless_present = "snapshot", conflicts_with = "snapshot")]
    pub image: Option<String>,

    /// Boot a fresh sandbox from a snapshot artifact (path or name).
    ///
    /// The snapshot pins the image; passing `--snapshot` is equivalent
    /// to specifying the snapshot's image plus pre-populating the
    /// upper layer from the artifact.
    #[arg(long, value_name = "PATH_OR_NAME")]
    pub snapshot: Option<String>,

    /// Start the sandbox in the background and print its name.
    ///
    /// Use `msb exec` to run commands in a detached sandbox.
    #[arg(short, long)]
    pub detach: bool,

    /// Allocate a pseudo-terminal (enables colors, line editing).
    #[arg(short = 't', long, conflicts_with = "no_tty")]
    pub tty: bool,

    /// Disable pseudo-terminal allocation and run non-interactively.
    #[arg(long = "no-tty", conflicts_with = "tty")]
    pub no_tty: bool,

    /// Kill the command after this duration (e.g. 30s, 5m, 1h).
    #[arg(long)]
    pub timeout: Option<String>,

    /// Set a POSIX resource limit (e.g. nofile=1024, nproc=64, as=1073741824).
    #[arg(long)]
    pub rlimit: Vec<String>,

    /// Key sequence to detach from interactive session (default: ctrl-]).
    #[arg(long)]
    pub detach_keys: Option<String>,

    /// Command to run inside the sandbox in attached mode (after --).
    #[arg(last = true)]
    pub command: Vec<String>,

    /// Sandbox configuration options.
    #[command(flatten)]
    pub sandbox: SandboxOpts,
}

/// Parsed per-command execution options for `msb run`.
struct ExecOpts {
    tty: bool,
    timeout: Option<Duration>,
    rlimits: Vec<(RlimitResource, u64, u64)>,
    detach_keys: Option<String>,
}

impl ExecOpts {
    fn parse(args: &RunArgs) -> anyhow::Result<Self> {
        let rlimits: Vec<_> = args
            .rlimit
            .iter()
            .map(|s| super::common::parse_rlimit(s))
            .collect::<anyhow::Result<Vec<_>>>()?;

        let timeout = match &args.timeout {
            Some(t) => Some(Duration::from_secs(super::common::parse_duration_secs(t)?)),
            None => None,
        };

        Ok(Self {
            tty: args.tty,
            timeout,
            rlimits,
            detach_keys: args.detach_keys.clone(),
        })
    }
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

/// Execute the `msb run` command.
pub async fn run(args: RunArgs, log_level: Option<microsandbox::LogLevel>) -> anyhow::Result<()> {
    let is_named = args.sandbox.name.is_some();
    let name = args.sandbox.name.clone().unwrap_or_else(ui::generate_name);

    // Named sandboxes are reused if they already exist (unless --replace
    // or --replace-with-timeout). --replace-with-timeout implies --replace,
    // so either flag opts out of the reuse path.
    let replace_requested = args.sandbox.replace || args.sandbox.replace_with_timeout.is_some();
    if is_named && !replace_requested && Sandbox::get(&name).await.is_ok() {
        return run_existing(name, args).await;
    }

    run_new(name, is_named, args, log_level).await
}

/// Run in an existing named sandbox — start if stopped, connect if running.
async fn run_existing(name: String, args: RunArgs) -> anyhow::Result<()> {
    if let Some(ignored) = ignored_existing_inputs(&args) {
        ui::warn(&format!(
            "sandbox '{name}' already exists; {ignored} ignored (use --replace to recreate)"
        ));
    }

    let sandbox = super::resolve_and_start(&name, args.sandbox.quiet).await?;

    // Detach mode: ensure running and exit.
    if args.detach {
        warn_detached_command_ignored(&name, &args);
        sandbox.detach().await;
        println!("{name}");
        return Ok(());
    }

    let exec_opts = ExecOpts::parse(&args)?;
    let interactive =
        super::common::use_interactive_tty(std::io::stdin().is_terminal(), args.no_tty);

    let result: anyhow::Result<i32> = async {
        let (cmd, cmd_args) =
            super::common::resolve_command(sandbox.config(), args.command, interactive)?;
        match cmd {
            Some(cmd) => exec_in_sandbox(&sandbox, &cmd, cmd_args, interactive, &exec_opts).await,
            None => Ok(0),
        }
    }
    .await;

    // Stop only if we own the lifecycle (i.e., we started it from stopped).
    // Always runs, even if resolve_command or exec failed.
    super::maybe_stop(&sandbox).await;

    handle_exit(result?)
}

/// Create a new sandbox and run in it.
async fn run_new(
    name: String,
    is_named: bool,
    mut args: RunArgs,
    log_level: Option<microsandbox::LogLevel>,
) -> anyhow::Result<()> {
    let mut builder = Sandbox::builder(&name);
    if let Some(ref snap) = args.snapshot {
        builder = builder.from_snapshot(snap.clone());
    } else if let Some(ref image) = args.image {
        builder = builder.image(image.as_str());
    } else {
        anyhow::bail!("either an image or --snapshot is required");
    }
    if args.sandbox.log_level.is_none()
        && let Some(log_level) = log_level
    {
        args.sandbox.log_level = Some(log_level.to_string());
    }
    let mut builder = apply_sandbox_opts(builder, &args.sandbox)?;
    if !is_named {
        // Unnamed `msb run` (including `--detach`) is a one-off: mark it
        // ephemeral so the host runtime removes its persisted state on exit.
        // Named runs stay persistent and inspectable. This sets policy intent
        // only; cleanup is owned by the runtime, not this CLI.
        builder = builder.ephemeral(true);
    }
    if args.detach {
        builder = builder.persistent_initial_command(args.command.clone());
    } else {
        builder = builder.initial_command(args.command.clone());
    }

    // Create sandbox with pull progress — select attached vs detached mode.
    let builder = builder.detached(args.detach);
    let (mut progress, task) = if args.detach {
        builder.create_detached_with_pull_progress()?
    } else {
        builder.create_with_pull_progress()?
    };

    let display_label = args
        .snapshot
        .clone()
        .or_else(|| args.image.clone())
        .unwrap_or_else(|| name.clone());
    let mut display = if args.sandbox.quiet {
        ui::PullProgressDisplay::quiet(&display_label)
    } else {
        ui::PullProgressDisplay::new(&display_label)
    };

    while let Some(event) = progress.recv().await {
        display.handle_event(event);
    }

    display.finish();
    let sandbox = task
        .await
        .map_err(|e| anyhow::anyhow!("create task panicked: {e}"))??;

    // Detach mode: just print the name and exit.
    if args.detach {
        sandbox.detach().await;
        println!("{name}");
        return Ok(());
    }

    let exec_opts = ExecOpts::parse(&args)?;
    let interactive =
        super::common::use_interactive_tty(std::io::stdin().is_terminal(), args.no_tty);

    let (cmd, cmd_args) =
        super::common::resolve_command(sandbox.config(), args.command, interactive)?;
    let (cmd, cmd_args) = match (cmd, cmd_args) {
        (Some(cmd), args) => (cmd, args),
        (None, _) => {
            if let Err(e) = sandbox.stop().await {
                ui::warn(&format!("failed to stop sandbox: {e}"));
            }
            return Ok(());
        }
    };

    let result = exec_in_sandbox(&sandbox, &cmd, cmd_args, interactive, &exec_opts).await;

    // Stop always runs, even on exec/attach/IO errors. Unnamed (ephemeral)
    // sandboxes are removed by the host runtime on exit, not here.
    if let Err(e) = sandbox.stop().await {
        ui::warn(&format!("failed to stop sandbox: {e}"));
    }

    handle_exit(result?)
}

/// Execute or attach to a command in a sandbox.
async fn exec_in_sandbox(
    sandbox: &Sandbox,
    cmd: &str,
    cmd_args: Vec<String>,
    interactive: bool,
    opts: &ExecOpts,
) -> anyhow::Result<i32> {
    if interactive {
        let rlimits = opts.rlimits.clone();
        let detach_keys = opts.detach_keys.clone();
        let timeout = opts.timeout;
        let has_opts = !rlimits.is_empty() || detach_keys.is_some();

        let attach_fut = async {
            if has_opts {
                Ok(sandbox
                    .attach_with(cmd, |a| {
                        let mut a = a.args(cmd_args);
                        for (resource, soft, hard) in rlimits {
                            a = a.rlimit_range(resource, soft, hard);
                        }
                        if let Some(keys) = detach_keys {
                            a = a.detach_keys(keys);
                        }
                        a
                    })
                    .await?)
            } else {
                Ok(sandbox.attach(cmd, cmd_args).await?)
            }
        };

        match timeout {
            Some(duration) => match tokio::time::timeout(duration, attach_fut).await {
                Ok(result) => result,
                Err(_) => anyhow::bail!("command timed out after {duration:?}"),
            },
            None => attach_fut.await,
        }
    } else {
        let rlimits = opts.rlimits.clone();
        let timeout = opts.timeout;
        let tty = opts.tty;
        let has_opts = tty || timeout.is_some() || !rlimits.is_empty();
        let output: ExecOutput = if has_opts {
            sandbox
                .exec_with(cmd, |e| {
                    let mut e = e.args(cmd_args);
                    if tty {
                        e = e.tty(true);
                    }
                    if let Some(t) = timeout {
                        e = e.timeout(t);
                    }
                    for (resource, soft, hard) in rlimits {
                        e = e.rlimit_range(resource, soft, hard);
                    }
                    e
                })
                .await?
        } else {
            sandbox.exec(cmd, cmd_args).await?
        };

        std::io::stdout().write_all(output.stdout_bytes())?;
        std::io::stderr().write_all(output.stderr_bytes())?;

        Ok(if output.status().success {
            0
        } else {
            output.status().code
        })
    }
}

/// Exit the process with a non-zero code if needed.
fn handle_exit(exit_code: i32) -> anyhow::Result<()> {
    if exit_code != 0 {
        std::process::exit(exit_code);
    }
    Ok(())
}

/// Describe creation-only inputs that are ignored when reusing an
/// existing named sandbox.
fn ignored_existing_inputs(args: &RunArgs) -> Option<&'static str> {
    match (args.snapshot.is_some(), args.sandbox.has_creation_flags()) {
        (true, true) => Some("--snapshot and creation flags"),
        (true, false) => Some("--snapshot"),
        (false, true) => Some("creation flags"),
        (false, false) => None,
    }
}

/// Warn when a detached run reuses an existing sandbox and includes a command.
fn warn_detached_command_ignored(name: &str, args: &RunArgs) {
    if args.command.is_empty() {
        return;
    }

    ui::warn(&format!(
        "command after -- is not applied when reusing existing sandbox '{name}' in --detach mode (use `msb exec {name} -- ...`)"
    ));
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use clap::Parser;
    use clap::error::ErrorKind;

    use super::*;

    #[derive(Debug, Parser)]
    struct TestCli {
        #[command(flatten)]
        args: RunArgs,
    }

    fn parse_run_args(args: &[&str]) -> RunArgs {
        TestCli::parse_from(std::iter::once("msb").chain(args.iter().copied())).args
    }

    #[test]
    fn no_tty_parses_after_image_before_command_delimiter() {
        let args = parse_run_args(&[
            "-q",
            "python:3-alpine",
            "--no-tty",
            "--",
            "python3",
            "-c",
            "print('ok')",
        ]);

        assert!(args.no_tty);
        assert_eq!(args.image.as_deref(), Some("python:3-alpine"));
        assert_eq!(
            args.command,
            vec![
                "python3".to_string(),
                "-c".to_string(),
                "print('ok')".to_string()
            ]
        );
    }

    #[test]
    fn no_tty_conflicts_with_tty() {
        let err =
            TestCli::try_parse_from(["msb", "--tty", "--no-tty", "python:3-alpine"]).unwrap_err();

        assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
    }

    #[test]
    fn existing_reuse_does_not_warn_for_required_image() {
        let args = parse_run_args(&["--name", "box", "alpine", "--", "echo", "hello"]);

        assert_eq!(ignored_existing_inputs(&args), None);
    }

    #[test]
    fn existing_reuse_warns_for_snapshot() {
        let args = parse_run_args(&["--name", "box", "--detach", "--snapshot", "clean"]);

        assert_eq!(ignored_existing_inputs(&args), Some("--snapshot"));
    }

    #[test]
    fn existing_reuse_warns_for_snapshot_and_creation_flags() {
        let args = parse_run_args(&["--name", "box", "--memory", "1G", "--snapshot", "clean"]);

        assert_eq!(
            ignored_existing_inputs(&args),
            Some("--snapshot and creation flags")
        );
    }
}