devsandbox 0.6.0

Manage devcontainer-style sandboxes on docker, podman, or Apple container — many throwaway instances per repo from one TOML config.
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
//! Container-runtime backends. Every runtime invocation in devsandbox goes
//! through [`Backend`], so the rest of the code never spells a binary name.
//!
//! Two shapes exist: docker-CLI-compatible runtimes (`docker`, `podman`), which
//! share [`dockerlike::Dockerlike`] and differ only in binary name, and Apple's
//! `container`, whose `inspect`/`ls` are JSON-only (no Go templates, no
//! `--filter`) and which lacks `network connect`, `--network-alias` and `top`.

mod apple;
pub mod bounded;
mod dockerlike;

#[cfg(test)]
pub use apple::AppleContainer;
#[cfg(test)]
pub use dockerlike::Dockerlike;

use std::collections::BTreeMap;
use std::process::Command;
use std::sync::OnceLock;

use anyhow::{bail, Context, Result};

/// Prefix for everything devsandbox creates in the runtime, so listings can
/// filter on it.
pub const NAME_PREFIX: &str = "devsandbox-";

/// Shell for the scripts devsandbox execs in containers, by absolute path:
/// a container's env (and whatever it planted on its `PATH`) is untrusted,
/// and these execs often run as root.
pub const SH: &str = "/bin/sh";

/// `PATH` those scripts run with (see [`fixed_path`]).
pub const FIXED_PATH: &str = "/usr/sbin:/usr/bin:/sbin:/bin";

/// `script` with `PATH` pinned to [`FIXED_PATH`] first, so the tools it names
/// (`mkdir`, `cat`, …) resolve the same whatever the container's env says.
/// Run it with [`SH`] `-c`.
pub fn fixed_path(script: &str) -> String {
    format!("PATH={FIXED_PATH}; export PATH; {script}")
}

/// Env var that overrides runtime selection: `docker`, `podman` or `container`.
pub const RUNTIME_ENV: &str = "DEVSANDBOX_RUNTIME";

/// One container as reported by the runtime's listing.
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
pub struct ContainerRow {
    pub name: String,
    pub image: String,
    /// Human status (`Up 3 minutes`, `Exited (0) 1 hour ago`, or the bare
    /// state on runtimes without one).
    pub status: String,
    /// Normalized state: `running` or anything else (stopped/exited/created…).
    pub state: String,
    pub labels: BTreeMap<String, String>,
    /// Host ports the container publishes.
    pub host_ports: Vec<String>,
}

impl ContainerRow {
    pub fn is_running(&self) -> bool {
        self.state == "running"
    }

    pub fn label(&self, key: &str) -> Option<&str> {
        self.labels.get(key).map(String::as_str)
    }
}

/// Resource usage of one running container, pre-rendered for display.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct StatsRow {
    pub name: String,
    pub cpu: String,
    pub mem: String,
}

/// A service a sandbox must reach by name: `(alias, service container)`.
pub struct ServiceEndpoint {
    pub alias: String,
    pub container: String,
}

/// A container's process listing plus whether its pids are usable by
/// [`Backend::signal_proc`]. `container_pids` is true when the listing came from
/// inside the container (`exec ps`), so its pids are container-namespace and a
/// signal can target them; false for a host-side `top` fallback, whose pids are
/// host-namespace and can't be signalled through `exec`.
pub struct ProcList {
    pub text: String,
    pub container_pids: bool,
}

pub trait Backend: Send + Sync {
    /// Short runtime name for messages and the dashboard header.
    fn name(&self) -> &'static str;
    /// Executable to invoke.
    fn bin(&self) -> &'static str;

    // --- process runners (shared) ---

    /// Run with stdio inherited (build output, exec, ps). Returns the exit code.
    fn run_inherit(&self, args: &[&str]) -> Result<i32> {
        let status = Command::new(self.bin())
            .args(args)
            .status()
            .with_context(|| format!("failed to run {} (is it installed?)", self.bin()))?;
        Ok(status.code().unwrap_or(1))
    }

    /// Capture stdout (stderr inherited); non-zero exit is an error.
    fn output(&self, args: &[&str]) -> Result<String> {
        let out = Command::new(self.bin())
            .args(args)
            .stderr(std::process::Stdio::inherit())
            .output()
            .with_context(|| format!("failed to run {} (is it installed?)", self.bin()))?;
        if !out.status.success() {
            bail!(
                "{} {} exited with status {}",
                self.bin(),
                args.first().unwrap_or(&""),
                out.status.code().unwrap_or(1)
            );
        }
        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
    }

    /// Like `output` but with stderr captured instead of inherited, for callers
    /// that own the screen (the TUI): stray stderr would corrupt the alternate
    /// screen. The first stderr line is folded into the error message.
    fn output_quiet(&self, args: &[&str]) -> Result<String> {
        let out = Command::new(self.bin())
            .args(args)
            .output()
            .with_context(|| format!("failed to run {} (is it installed?)", self.bin()))?;
        if !out.status.success() {
            let stderr = String::from_utf8_lossy(&out.stderr);
            bail!(
                "{} {}: {}",
                self.bin(),
                args.first().unwrap_or(&""),
                stderr.lines().next().unwrap_or("non-zero exit").trim()
            );
        }
        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
    }

    /// Capture stdout and stderr merged into one string (container logs go to
    /// both). Non-zero exit is an error with the first stderr line folded in.
    fn output_merged(&self, args: &[&str]) -> Result<String> {
        let out = Command::new(self.bin())
            .args(args)
            .output()
            .with_context(|| format!("failed to run {} (is it installed?)", self.bin()))?;
        if !out.status.success() {
            let stderr = String::from_utf8_lossy(&out.stderr);
            bail!(
                "{} {}: {}",
                self.bin(),
                args.first().unwrap_or(&""),
                stderr.lines().next().unwrap_or("non-zero exit").trim()
            );
        }
        let stdout = String::from_utf8_lossy(&out.stdout);
        let stderr = String::from_utf8_lossy(&out.stderr);
        let mut merged = String::new();
        merged.push_str(stdout.trim_end());
        let stderr = stderr.trim_end();
        if !stderr.is_empty() {
            if !merged.is_empty() {
                merged.push('\n');
            }
            merged.push_str(stderr);
        }
        Ok(merged.trim().to_string())
    }

    /// Like `run_inherit` but treats a non-zero exit as an error.
    fn run_checked(&self, args: &[&str]) -> Result<()> {
        let code = self.run_inherit(args)?;
        if code != 0 {
            bail!("{} {} exited with status {code}", self.bin(), args.first().unwrap_or(&""));
        }
        Ok(())
    }

    /// Run with `input` piped to stdin (e.g. `exec -i … sh -c 'cat > f'`).
    /// stdout is discarded and stderr captured, so it is screen-safe; a
    /// non-zero exit is an error with the first stderr line folded in.
    fn run_with_stdin(&self, args: &[&str], input: &[u8]) -> Result<()> {
        use std::io::Write;
        use std::process::Stdio;
        let mut child = Command::new(self.bin())
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .with_context(|| format!("failed to run {} (is it installed?)", self.bin()))?;
        let mut stdin = child.stdin.take().expect("stdin was piped");
        // A write error (EPIPE when the child exits early) is reported below
        // through the exit status, which carries the more useful message.
        let written = stdin.write_all(input);
        drop(stdin);
        let out = child.wait_with_output()?;
        if !out.status.success() {
            let stderr = String::from_utf8_lossy(&out.stderr);
            bail!(
                "{} {}: {}",
                self.bin(),
                args.first().unwrap_or(&""),
                stderr.lines().next().unwrap_or("non-zero exit").trim()
            );
        }
        written.with_context(|| format!("writing stdin of {} {}", self.bin(), args.first().unwrap_or(&"")))
    }

    // --- queries (diverge per runtime) ---

    /// `Some(true|false)` for an existing container, `None` when it does not
    /// exist (any lookup failure is treated as "not found").
    fn is_running(&self, container: &str) -> Result<Option<bool>>;

    /// A container label's value; `None` when the container or the label is
    /// missing (an empty value counts as missing).
    fn label(&self, container: &str, key: &str) -> Result<Option<String>>;

    fn network_exists(&self, network: &str) -> Result<bool>;

    /// Raw `inspect` JSON for a container, for the dashboard's inspect pane.
    fn inspect_json(&self, container: &str) -> Result<String>;

    /// Containers whose name starts with `name_prefix` (empty = all). stderr is
    /// captured so this is safe from the TUI.
    fn list(&self, all: bool, name_prefix: &str) -> Result<Vec<ContainerRow>>;

    /// Resource usage of running containers.
    fn stats(&self) -> Result<Vec<StatsRow>>;

    /// Runtime (server) version string.
    fn server_version(&self) -> Result<String>;

    /// Last `n` lines of a container's stdout+stderr.
    fn logs_tail(&self, container: &str, n: usize) -> Result<String>;

    /// `pid,ppid,args` process listing of a container, `ps -eo` style text,
    /// tagged with whether its pids are container-namespace (see [`ProcList`]).
    fn proc_list(&self, container: &str) -> Result<ProcList>;

    /// Send signal `sig` (a number, e.g. `15` for TERM, `9` for KILL) to `pid`
    /// inside `container`. Runs `kill -<sig> <pid>` via `exec`, which every
    /// backend supports; the numeric form is portable across busybox and
    /// coreutils `kill`. stderr is captured (screen-safe for the TUI).
    fn signal_proc(&self, container: &str, pid: &str, sig: i32) -> Result<()> {
        self.output_quiet(&["exec", container, "kill", &format!("-{sig}"), pid])?;
        Ok(())
    }

    // --- mutations that differ in shape ---

    /// Force-remove a container.
    fn remove_force(&self, container: &str) -> Result<i32>;

    /// `run` args attaching `networks`. Docker-likes accept a single `--network`
    /// at creation (the rest join via [`Self::connect_networks`]); Apple's
    /// `container` takes them all up front.
    fn network_run_args(&self, networks: &[String]) -> Vec<String>;

    /// Join networks not covered by [`Self::network_run_args`] after creation.
    fn connect_networks(&self, container: &str, networks: &[String]) -> Result<()>;

    /// `run` args making a service reachable as `alias` (`--network-alias` where
    /// supported; otherwise nothing and [`Self::wire_service_dns`] does it).
    fn service_alias_args(&self, alias: &str) -> Vec<String>;

    /// Make every endpoint resolvable by alias from inside `container`. No-op on
    /// runtimes where the alias was applied at service creation.
    fn wire_service_dns(&self, container: &str, endpoints: &[ServiceEndpoint]) -> Result<()>;

    /// Whether `build --cache-from` is supported.
    fn supports_cache_from(&self) -> bool;

    /// Whether a single host *file* (or socket) can be bind-mounted. Apple's
    /// `container` only binds directories; callers that would mount a file must
    /// mount its parent directory instead, or skip the mount.
    fn supports_file_binds(&self) -> bool;

    /// Whether `run --privileged` is supported. Apple's `container` has no such
    /// flag (each container is its own VM).
    fn supports_privileged(&self) -> bool;

    /// Whether containers can carry a restart policy (`run --restart`,
    /// changeable in place with `update --restart`). Apple's `container` has
    /// none, so `autostart = "runtime"` falls back to devsandbox-driven there.
    fn supports_restart_policy(&self) -> bool;

    /// A container's current restart policy name (`no`, `unless-stopped`, …;
    /// empty when unset). `None` when the container doesn't exist or the
    /// runtime has no restart policies. stderr is captured (screen-safe).
    fn restart_policy(&self, container: &str) -> Result<Option<String>>;

    /// Change a container's restart policy in place. stderr is captured
    /// (screen-safe); no-op on runtimes without restart policies.
    fn set_restart_policy(&self, container: &str, policy: &str) -> Result<()>;

    /// The local image's `ENTRYPOINT` (exec form; empty when unset). Needed to
    /// chain it behind feature entrypoints, since a Dockerfile cannot reference
    /// its parent's.
    fn image_entrypoint(&self, image: &str) -> Result<Vec<String>>;

    /// Delete a named volume. `Ok(false)` when it doesn't exist (already
    /// gone), an error when the runtime refuses (e.g. still in use).
    fn remove_volume(&self, name: &str) -> Result<bool>;
}

/// Whether a runtime's error text means "no such volume" (docker/podman say
/// `no such volume`, Apple `container` says `not found`).
pub(crate) fn is_missing_volume(err: &str) -> bool {
    let err = err.to_ascii_lowercase();
    err.contains("no such volume") || err.contains("not found")
}

/// Pick a backend by name: `docker`, `podman` or `container`.
pub fn backend_named(name: &str) -> Option<Box<dyn Backend>> {
    Some(match name {
        "docker" => Box::new(dockerlike::Dockerlike::DOCKER),
        "podman" => Box::new(dockerlike::Dockerlike::PODMAN),
        "container" | "apple" => Box::new(apple::AppleContainer),
        _ => return None,
    })
}

/// Whether the `docker` client resolves on `PATH`. Client-only (`--version`
/// prints the CLI version without contacting a daemon), so it stays fast and
/// does not hang when no engine is running.
fn docker_on_path() -> bool {
    Command::new("docker")
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Backend name devsandbox uses on this host: [`RUNTIME_ENV`] when set, else on
/// macOS `docker` when the `docker` client is on `PATH` (e.g. OrbStack, which
/// ships it and auto-selects its own context, or Docker Desktop) and Apple's
/// `container` otherwise; `docker` everywhere else.
pub fn default_backend_name(env: Option<&str>, macos: bool, docker_on_path: bool) -> &'static str {
    match env {
        Some("docker") => "docker",
        Some("podman") => "podman",
        Some("container") | Some("apple") => "container",
        Some(_) | None if macos => {
            if docker_on_path {
                "docker"
            } else {
                "container"
            }
        }
        _ => "docker",
    }
}

/// The process-wide backend, resolved once.
pub fn backend() -> &'static dyn Backend {
    static BACKEND: OnceLock<Box<dyn Backend>> = OnceLock::new();
    BACKEND
        .get_or_init(|| {
            let env = std::env::var(RUNTIME_ENV).ok();
            if let Some(value) = &env
                && backend_named(value).is_none()
            {
                eprintln!(
                    "warning: unknown {RUNTIME_ENV}=`{value}` (expected docker, podman or container); using the default"
                );
            }
            let macos = cfg!(target_os = "macos");
            // The PATH probe only affects the macOS default arm (no explicit
            // backend selected); skip it whenever it can't change the outcome.
            let explicit = matches!(env.as_deref(), Some("docker" | "podman" | "container" | "apple"));
            let docker = macos && !explicit && docker_on_path();
            let name = default_backend_name(env.as_deref(), macos, docker);
            backend_named(name).expect("default backend name is valid")
        })
        .as_ref()
}

/// The `ps` invocation `proc_list` runs inside a container. Shared so the call
/// site and [`without_self_ps`] can't drift.
pub(crate) const PROC_PS_ARGS: [&str; 3] = ["ps", "-eo", "pid,ppid,args"];

/// Drop the `ps` process we spawned from a container process listing: run via
/// `exec`, `ps` appears in its own output. Removes the row whose command column
/// (everything after pid and ppid) equals the [`PROC_PS_ARGS`] invocation;
/// every other line, including the header, is kept. Whitespace is normalized
/// before comparing so the parser's column padding doesn't matter.
pub(crate) fn without_self_ps(text: &str) -> String {
    let ps_cmd = PROC_PS_ARGS.join(" ");
    text.lines()
        .filter(|line| {
            let cmd = line.split_whitespace().skip(2).collect::<Vec<_>>().join(" ");
            cmd != ps_cmd
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Split `k=v` into `(k, v)`; a bare key maps to an empty value.
pub(crate) fn split_kv(pair: &str) -> (String, String) {
    match pair.split_once('=') {
        Some((k, v)) => (k.trim().to_string(), v.trim().to_string()),
        None => (pair.trim().to_string(), String::new()),
    }
}

/// `1.5GiB`-style rendering of a byte count, matching docker's stats output.
pub(crate) fn human_bytes(bytes: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit < UNITS.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes}B")
    } else if value >= 100.0 {
        format!("{value:.0}{}", UNITS[unit])
    } else {
        format!("{value:.1}{}", UNITS[unit])
    }
}

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

    #[test]
    fn default_backend_prefers_env_then_os() {
        // macOS default: docker when the client is on PATH, else Apple container.
        assert_eq!(default_backend_name(None, true, true), "docker");
        assert_eq!(default_backend_name(None, true, false), "container");
        // Non-macOS is always docker; the PATH flag is irrelevant.
        assert_eq!(default_backend_name(None, false, false), "docker");
        // Explicit env wins regardless of OS or PATH.
        assert_eq!(default_backend_name(Some("docker"), true, false), "docker");
        assert_eq!(default_backend_name(Some("podman"), true, true), "podman");
        assert_eq!(default_backend_name(Some("podman"), false, false), "podman");
        assert_eq!(default_backend_name(Some("container"), false, true), "container");
        // Unknown values fall back to the OS default arm.
        assert_eq!(default_backend_name(Some("nope"), true, true), "docker");
        assert_eq!(default_backend_name(Some("nope"), true, false), "container");
        assert_eq!(default_backend_name(Some("nope"), false, false), "docker");
    }

    #[test]
    fn backend_named_maps_binaries() {
        assert_eq!(backend_named("docker").unwrap().bin(), "docker");
        assert_eq!(backend_named("podman").unwrap().bin(), "podman");
        assert_eq!(backend_named("container").unwrap().bin(), "container");
        assert!(backend_named("lxc").is_none());
    }

    #[test]
    fn human_bytes_scales() {
        assert_eq!(human_bytes(512), "512B");
        assert_eq!(human_bytes(50 * 1024 * 1024), "50.0MiB");
        assert_eq!(human_bytes(2 * 1024 * 1024 * 1024), "2.0GiB");
        assert_eq!(human_bytes(150 * 1024 * 1024), "150MiB");
    }

    #[test]
    fn without_self_ps_drops_only_the_ps_row() {
        // Header kept, the `ps -eo pid,ppid,args` row (any column padding) removed,
        // real processes untouched.
        let input = "\
    PID    PPID COMMAND
      1       0 /sbin/init
   1409       1 claude --resume
   1500    1409 ps -eo pid,ppid,args";
        let out = without_self_ps(input);
        assert_eq!(
            out,
            "\
    PID    PPID COMMAND
      1       0 /sbin/init
   1409       1 claude --resume"
        );
    }

    #[test]
    fn without_self_ps_keeps_unrelated_lines() {
        // A `top` listing has no self `ps` row; nothing is dropped.
        let input = "PID PPID COMMAND\n1 0 bash\n2 1 node server.js";
        assert_eq!(without_self_ps(input), input);
    }
}