use std::process::Command;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::docker::{DockerCli, DockerRuntime};
use super::lxc::{self, LxcRuntime};
use super::{Probe, Runtime, RuntimeKind, Selection};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Engine {
Docker,
Nerdctl { cli: String, instance: String },
Lima { limactl: String, instance: String },
Colima { colima: String, profile: String },
}
impl Engine {
pub fn from_selection(sel: &Selection, lxc_cli: &str) -> Option<Engine> {
Some(match sel.chosen? {
RuntimeKind::Lxc => Engine::Nerdctl {
cli: lxc_cli.to_string(),
instance: lxc::SANDBOX.to_string(),
},
RuntimeKind::Lima => Engine::Lima {
limactl: super::lima::binary(),
instance: super::lima::LimaRuntime::shell().instance().to_string(),
},
RuntimeKind::Colima => Engine::Colima {
colima: super::colima::ColimaShell::binary(),
profile: super::colima::ColimaRuntime::shell().profile().to_string(),
},
_ => Engine::Docker,
})
}
pub fn invocation(&self, args: &[String]) -> (String, Vec<String>) {
match self {
Engine::Docker => ("docker".to_string(), args.to_vec()),
Engine::Nerdctl { cli, instance } => {
let mut a = vec!["exec".to_string(), instance.clone(), "--".to_string()];
a.extend(nerdctl_tail(args));
(cli.clone(), a)
}
Engine::Lima { limactl, instance } => {
let mut a = ["shell", "--workdir", "/", instance.as_str(), "--", "sudo"]
.map(String::from)
.to_vec();
a.extend(nerdctl_tail(args));
(limactl.clone(), a)
}
Engine::Colima { colima, profile } => {
let mut a = ["ssh", "-p", profile.as_str(), "--", "docker"]
.map(String::from)
.to_vec();
a.extend(args.iter().cloned());
(colima.clone(), a)
}
}
}
pub fn is_lxc(&self) -> bool {
matches!(self, Engine::Nerdctl { .. })
}
pub fn describe(&self) -> String {
match self {
Engine::Docker => "docker".to_string(),
Engine::Nerdctl { cli, instance } => format!("{cli} sandbox {instance} (nerdctl)"),
Engine::Lima { instance, .. } => format!("Lima VM {instance} (nerdctl)"),
Engine::Colima { profile, .. } => {
format!("Colima profile {profile} (docker in the VM)")
}
}
}
}
fn nerdctl_tail(args: &[String]) -> Vec<String> {
let mut a = Vec::new();
let rest = match args {
[flag, dir, rest @ ..] if flag == "--config" => {
a.push("env".into());
a.push(format!("DOCKER_CONFIG={dir}"));
rest
}
_ => args,
};
match detached_rm_run(rest) {
Some((name, run)) => {
a.extend(
[
"sh",
"-c",
r#"nerdctl rm -f "$1" >/dev/null 2>&1; shift; exec nerdctl "$@""#,
"sh",
]
.map(String::from),
);
a.push(name);
a.extend(run);
}
None => {
a.push("nerdctl".into());
a.extend(rest.iter().cloned());
}
}
a
}
fn detached_rm_run(args: &[String]) -> Option<(String, Vec<String>)> {
if args.first().map(String::as_str) != Some("run") {
return None;
}
let detached = args.iter().any(|a| a == "-d" || a == "--detach");
let rm = args.iter().any(|a| a == "--rm");
if !(detached && rm) {
return None;
}
let name = args
.iter()
.position(|a| a == "--name")
.and_then(|i| args.get(i + 1))?
.clone();
Some((
name,
args.iter().filter(|a| *a != "--rm").cloned().collect(),
))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
pub selection: Selection,
pub engine: Option<Engine>,
pub shared_reason: String,
pub jobs_per_instance: bool,
pub jobs_reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Choice {
pub engine: Option<Engine>,
pub reason: String,
}
pub fn shared_lxc_requested(get: &dyn Fn(&str) -> Option<String>) -> Option<String> {
let clean = |k: &str| {
get(k)
.map(|v| v.trim().to_ascii_lowercase())
.filter(|v| !v.is_empty())
};
if clean("ZAKURO_SANDBOX_SHARED").as_deref() == Some("lxc") {
return Some("ZAKURO_SANDBOX_SHARED=lxc".to_string());
}
let prefer = clean("ZAKURO_RUNTIME_PREFER")?;
let first = prefer
.split(',')
.filter_map(RuntimeKind::parse)
.find(|k| matches!(k, RuntimeKind::Lxc | RuntimeKind::Docker))?;
(first == RuntimeKind::Lxc).then(|| format!("ZAKURO_RUNTIME_PREFER={prefer}"))
}
pub fn resolve_shared(
get: &dyn Fn(&str) -> Option<String>,
lxc_probe: &Probe,
docker_probe: &Probe,
lxc_cli: &str,
) -> Choice {
let lxc = || Engine::Nerdctl {
cli: lxc_cli.to_string(),
instance: lxc::SANDBOX.to_string(),
};
let ok = |e: Engine, why: String| Choice {
engine: Some(e),
reason: why,
};
if let Some(ask) = shared_lxc_requested(get) {
if lxc_probe.available {
return ok(lxc(), format!("LXC sandbox, asked for by {ask}"));
}
if docker_probe.available {
return ok(
Engine::Docker,
format!("Docker ({ask} asked for LXC, but: {})", lxc_probe.detail),
);
}
} else {
if docker_probe.available {
return ok(
Engine::Docker,
"Docker (default; opt in to the LXC sandbox with ZAKURO_SANDBOX_SHARED=lxc)".into(),
);
}
if lxc_probe.available {
return ok(
lxc(),
format!(
"LXC sandbox (Docker is unavailable: {})",
docker_probe.detail
),
);
}
}
Choice {
engine: None,
reason: no_backend_message(&Selection {
chosen: None,
tried: vec![lxc_probe.clone(), docker_probe.clone()],
}),
}
}
pub fn resolve_jobs(
get: &dyn Fn(&str) -> Option<String>,
lxc_probe: &Probe,
shared: &Choice,
) -> (bool, String) {
let iso = get("ZAKURO_SANDBOX_ISOLATION")
.map(|v| v.trim().to_ascii_lowercase())
.filter(|v| !v.is_empty());
match iso.as_deref() {
Some("shared") => (
false,
"shared engine (ZAKURO_SANDBOX_ISOLATION=shared)".to_string(),
),
None | Some("job") if lxc_probe.available => (
true,
format!("ephemeral LXC instance per job ({})", lxc_probe.detail),
),
None | Some("job") => (
false,
format!(
"FALLBACK: shared engine with limits, no per-job instance ({})",
lxc_probe.detail
),
),
Some(other) => (
false,
format!("ZAKURO_SANDBOX_ISOLATION={other:?} is not one of job, shared; using the shared engine ({})", shared.reason),
),
}
}
pub fn no_backend_message(sel: &Selection) -> String {
let mut m = String::from("no isolating container backend on this host");
let reasons: Vec<String> = sel
.tried
.iter()
.map(|p| format!("{}: {}", p.kind.as_str(), p.detail))
.collect();
if !reasons.is_empty() {
m.push_str(&format!(" ({})", reasons.join("; ")));
}
m.push_str(
". Install Incus (`apt install incus && incus admin init --minimal`; LXD works too) \
or Docker, or run on the host with no isolation: ZAKURO_SHARE_RUNTIME=host \
(owner's own work only)",
);
m
}
const RETRY_AFTER: Duration = Duration::from_secs(30);
fn cache() -> &'static Mutex<Option<(Instant, Arc<Resolved>)>> {
static C: Mutex<Option<(Instant, Arc<Resolved>)>> = Mutex::new(None);
&C
}
pub fn active() -> Arc<Resolved> {
let mut g = cache().lock().unwrap_or_else(|p| p.into_inner());
if let Some((at, r)) = g.as_ref() {
if r.engine.is_some() || at.elapsed() < RETRY_AFTER {
return r.clone();
}
}
let r = Arc::new(resolve_host(&|k| std::env::var(k).ok()));
*g = Some((Instant::now(), r.clone()));
r
}
fn docker_probe() -> Probe {
let p = crate::broker::deploy::runtime_probe();
let detail = match p.next_step() {
Some(step) => format!("{} ({step})", p.detail),
None => p.detail.clone(),
};
Probe {
kind: RuntimeKind::Docker,
available: p.available,
detail,
}
}
fn resolve_host(get: &dyn Fn(&str) -> Option<String>) -> Resolved {
if !cfg!(target_os = "linux") {
let selection = super::probe_host();
let engine = Engine::from_selection(&selection, lxc::cli_binary());
let reason = match &engine {
Some(e) => format!("{} (first available in the preference order)", e.describe()),
None => no_backend_message(&selection),
};
return Resolved {
selection,
engine,
shared_reason: reason,
jobs_per_instance: false,
jobs_reason: "no per-job instance off Linux; shared engine with limits".into(),
};
}
let lxc_probe = lxc::LxcRuntime::shell().probe();
let docker_probe = docker_probe();
let shared = resolve_shared(get, &lxc_probe, &docker_probe, lxc::cli_binary());
let (jobs_per_instance, jobs_reason) = resolve_jobs(get, &lxc_probe, &shared);
let chosen = shared.engine.as_ref().map(|e| {
if e.is_lxc() {
RuntimeKind::Lxc
} else {
RuntimeKind::Docker
}
});
Resolved {
selection: Selection {
chosen,
tried: vec![lxc_probe, docker_probe],
},
engine: shared.engine,
shared_reason: shared.reason,
jobs_per_instance,
jobs_reason,
}
}
pub fn available() -> bool {
active().engine.is_some()
}
pub fn sandbox_exists() -> bool {
matches!(LxcRuntime::shell().state(), Ok(Some(_)))
}
fn prepare(engine: &Engine) -> Result<(), String> {
const REENSURE: Duration = Duration::from_secs(300);
if matches!(engine, Engine::Docker) {
return Ok(());
}
static LAST: Mutex<Option<Instant>> = Mutex::new(None);
let mut last = LAST.lock().unwrap_or_else(|p| p.into_inner());
if last.is_some_and(|t| t.elapsed() < REENSURE) {
return Ok(());
}
let _g = super::lock::provision_lock(Duration::from_secs(900))?;
match engine {
Engine::Nerdctl { .. } => LxcRuntime::shell().ensure()?,
Engine::Lima { .. } => super::lima::LimaRuntime::shell().ensure()?,
Engine::Colima { .. } => super::colima::ColimaRuntime::shell().ensure()?,
Engine::Docker => {}
}
*last = Some(Instant::now());
Ok(())
}
pub fn command(args: &[String]) -> Result<Command, String> {
let r = active();
let engine = r
.engine
.as_ref()
.ok_or_else(|| no_backend_message(&r.selection))?;
prepare(engine)?;
Ok(build(engine, args))
}
pub fn command_if_present(args: &[String]) -> Result<Option<Command>, String> {
let r = active();
let engine = r
.engine
.as_ref()
.ok_or_else(|| no_backend_message(&r.selection))?;
if engine.is_lxc() && !sandbox_exists() {
return Ok(None);
}
Ok(Some(build(engine, args)))
}
fn build(engine: &Engine, args: &[String]) -> Command {
let (prog, rest) = engine.invocation(args);
let mut c = Command::new(prog);
c.args(rest);
c
}
pub fn run(args: &[&str]) -> Result<String, String> {
let argv: Vec<String> = args.iter().map(|a| a.to_string()).collect();
let out = command(&argv)?
.output()
.map_err(|e| format!("container runtime not available: {e}"))?;
if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
Err(if stderr.is_empty() {
format!(
"container command {} failed",
args.first().copied().unwrap_or("")
)
} else {
stderr
})
}
}
pub struct EngineShell;
impl DockerCli for EngineShell {
fn run(&self, argv: &[String]) -> Result<String, String> {
let rest = match argv.split_first() {
Some((first, rest)) if first == "docker" => rest,
_ => argv,
};
let out = command(rest)?
.output()
.map_err(|e| format!("container runtime not available: {e}"))?;
if out.status.success() {
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
}
pub fn runtime() -> Result<Arc<dyn Runtime>, String> {
let r = active();
match r.engine {
Some(Engine::Nerdctl { .. }) => Ok(Arc::new(LxcRuntime::shell())),
Some(Engine::Lima { .. }) => Ok(Arc::new(super::lima::LimaRuntime::shell())),
Some(Engine::Colima { .. }) => Ok(Arc::new(super::colima::ColimaRuntime::shell())),
Some(Engine::Docker) => Ok(Arc::new(DockerRuntime::new(Arc::new(EngineShell)))),
None => Err(no_backend_message(&r.selection)),
}
}
pub fn ephemeral() -> &'static super::ephemeral::Ephemeral {
static E: std::sync::OnceLock<super::ephemeral::Ephemeral> = std::sync::OnceLock::new();
E.get_or_init(|| super::ephemeral::Ephemeral::from_env(&|k| std::env::var(k).ok()))
}
pub fn allocations() -> Result<Vec<super::Allocation>, String> {
let lxc = active().engine.as_ref().is_some_and(|e| e.is_lxc());
let mut all = if lxc && !sandbox_exists() {
Vec::new()
} else {
let args = super::docker::allocations_args();
let args: Vec<&str> = args.iter().map(String::as_str).collect();
super::docker::parse_allocations(&run(&args)?)
};
if active().jobs_per_instance {
all.extend(ephemeral().allocations()?);
}
Ok(all)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tier {
Shared,
PerJob,
}
pub fn active_job_tier() -> Tier {
if active().jobs_per_instance {
Tier::PerJob
} else {
Tier::Shared
}
}
#[cfg(test)]
mod tests {
#[test]
fn lima_and_colima_run_inside_their_vm_never_on_host_docker() {
let run: Vec<String> = ["run", "--rm", "-d", "--name", "w1", "img"]
.map(String::from)
.to_vec();
let lima = Engine::Lima {
limactl: "/opt/homebrew/bin/limactl".into(),
instance: "zakuro".into(),
};
let (p, a) = lima.invocation(&run);
assert_eq!(p, "/opt/homebrew/bin/limactl");
assert_eq!(
&a[..7],
&["shell", "--workdir", "/", "zakuro", "--", "sudo", "sh"].map(String::from)
);
assert!(!a.contains(&"--rm".to_string()), "{a:?}");
let (p, a) = lima.invocation(&["ps".to_string()]);
assert_eq!(
(p.as_str(), a.last().unwrap().as_str()),
("/opt/homebrew/bin/limactl", "ps")
);
assert_eq!(a[a.len() - 2], "nerdctl");
let colima = Engine::Colima {
colima: "colima".into(),
profile: "zakuro".into(),
};
let (p, a) = colima.invocation(&run);
assert_eq!(p, "colima");
assert_eq!(
&a[..5],
&["ssh", "-p", "zakuro", "--", "docker"].map(String::from)
);
assert_eq!(&a[5..], &run[..], "docker in the VM keeps --rm");
}
#[test]
fn nerdctl_never_gets_run_with_both_d_and_rm() {
let e = Engine::Nerdctl {
cli: "lxc".into(),
instance: "zakuro-sandbox".into(),
};
let run: Vec<String> = ["run", "--rm", "-d", "--name", "w1", "img"]
.map(String::from)
.to_vec();
let (prog, a) = e.invocation(&run);
assert_eq!(prog, "lxc");
assert!(!a.contains(&"--rm".to_string()), "{a:?}");
let tail: Vec<&str> = a.iter().map(String::as_str).collect();
assert_eq!(&tail[..4], &["exec", "zakuro-sandbox", "--", "sh"]);
assert_eq!(
&tail[tail.len() - 6..],
&["w1", "run", "-d", "--name", "w1", "img"]
);
assert_eq!(Engine::Docker.invocation(&run).1, run);
let fg: Vec<String> = ["run", "--rm", "img"].map(String::from).to_vec();
assert_eq!(e.invocation(&fg).1.last().unwrap(), "img");
assert!(e.invocation(&fg).1.contains(&"--rm".to_string()));
}
use super::*;
fn sel(chosen: Option<RuntimeKind>) -> Selection {
Selection {
chosen,
tried: vec![
Probe {
kind: RuntimeKind::Lxc,
available: chosen == Some(RuntimeKind::Lxc),
detail: "incus is not installed".into(),
},
Probe {
kind: RuntimeKind::Docker,
available: chosen == Some(RuntimeKind::Docker),
detail: "docker daemon is not responding".into(),
},
],
}
}
fn v(a: &[&str]) -> Vec<String> {
a.iter().map(|s| s.to_string()).collect()
}
#[test]
fn docker_is_the_docker_cli_byte_for_byte() {
let e = Engine::from_selection(&sel(Some(RuntimeKind::Docker)), "incus").unwrap();
assert_eq!(e, Engine::Docker);
let args = v(&["run", "-d", "--cpus", "1", "img"]);
assert_eq!(e.invocation(&args), ("docker".to_string(), args));
let cfg = v(&["--config", "/tmp/d", "pull", "img"]);
assert_eq!(e.invocation(&cfg).1, cfg);
}
#[test]
fn lxc_runs_the_same_argv_under_nerdctl_in_the_sandbox() {
let e = Engine::from_selection(&sel(Some(RuntimeKind::Lxc)), "lxc").unwrap();
assert!(e.is_lxc());
let (prog, a) = e.invocation(&v(&["inspect", "-f", "{{.State.Running}}", "c"]));
assert_eq!(prog, "lxc");
assert_eq!(
a,
v(&[
"exec",
"zakuro-sandbox",
"--",
"nerdctl",
"inspect",
"-f",
"{{.State.Running}}",
"c"
])
);
let (_, a) = e.invocation(&v(&["--config", "/d/cfg", "pull", "img"]));
assert_eq!(
a,
v(&[
"exec",
"zakuro-sandbox",
"--",
"env",
"DOCKER_CONFIG=/d/cfg",
"nerdctl",
"pull",
"img"
])
);
}
#[test]
fn nothing_available_is_no_engine_and_the_message_names_the_way_out() {
assert_eq!(Engine::from_selection(&sel(None), "incus"), None);
let m = no_backend_message(&sel(None));
assert!(m.contains("lxc: incus is not installed"), "{m}");
assert!(m.contains("docker: docker daemon is not responding"), "{m}");
assert!(m.contains("apt install incus"), "{m}");
assert!(m.contains("ZAKURO_SHARE_RUNTIME=host"), "{m}");
}
#[test]
fn lima_and_colima_selections_are_their_vm_engines_not_host_docker() {
let lima = Selection {
chosen: Some(RuntimeKind::Lima),
tried: vec![],
};
assert!(matches!(
Engine::from_selection(&lima, "incus"),
Some(Engine::Lima { .. })
));
let colima = Selection {
chosen: Some(RuntimeKind::Colima),
tried: vec![],
};
assert!(matches!(
Engine::from_selection(&colima, "incus"),
Some(Engine::Colima { .. })
));
let docker = Selection {
chosen: Some(RuntimeKind::Docker),
tried: vec![],
};
assert_eq!(
Engine::from_selection(&docker, "incus"),
Some(Engine::Docker)
);
}
fn probe(kind: RuntimeKind, ok: bool) -> Probe {
Probe {
kind,
available: ok,
detail: if ok { "ok".into() } else { "down".into() },
}
}
fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
move |k| {
pairs
.iter()
.find(|(ek, _)| *ek == k)
.map(|(_, v)| v.to_string())
}
}
fn matrix(lxc_ok: bool, docker_ok: bool, e: &[(&str, &str)]) -> (Option<Engine>, bool) {
let g = env(e);
let l = probe(RuntimeKind::Lxc, lxc_ok);
let c = resolve_shared(&g, &l, &probe(RuntimeKind::Docker, docker_ok), "incus");
let (jobs, _) = resolve_jobs(&g, &l, &c);
(c.engine, jobs)
}
fn lxc_engine() -> Option<Engine> {
Some(Engine::Nerdctl {
cli: "incus".into(),
instance: "zakuro-sandbox".into(),
})
}
#[test]
fn resolution_matrix_docker_only() {
assert_eq!(matrix(false, true, &[]), (Some(Engine::Docker), false));
let g = env(&[("ZAKURO_SANDBOX_SHARED", "lxc")]);
let c = resolve_shared(
&g,
&probe(RuntimeKind::Lxc, false),
&probe(RuntimeKind::Docker, true),
"incus",
);
assert_eq!(c.engine, Some(Engine::Docker));
assert!(
c.reason.contains("asked for LXC, but: down"),
"{}",
c.reason
);
}
#[test]
fn resolution_matrix_lxc_only() {
let (e, jobs) = matrix(true, false, &[]);
assert_eq!(e, lxc_engine());
assert!(jobs);
let g = env(&[]);
let c = resolve_shared(
&g,
&probe(RuntimeKind::Lxc, true),
&probe(RuntimeKind::Docker, false),
"incus",
);
assert!(c.reason.contains("Docker is unavailable"), "{}", c.reason);
}
#[test]
fn resolution_matrix_both_without_a_preference_keeps_long_lived_work_on_docker() {
let (e, jobs) = matrix(true, true, &[]);
assert_eq!(
e,
Some(Engine::Docker),
"an LXD host is not moved by an upgrade"
);
assert!(jobs, "foreign jobs still get their own instance");
for p in ["docker,lxc", "docker", "podman", ""] {
assert_eq!(
matrix(true, true, &[("ZAKURO_RUNTIME_PREFER", p)]).0,
Some(Engine::Docker),
"{p:?}"
);
}
assert_eq!(
matrix(true, true, &[("ZAKURO_SANDBOX_SHARED", "docker")]).0,
Some(Engine::Docker)
);
}
#[test]
fn resolution_matrix_both_with_an_explicit_lxc_choice() {
for e in [
&[("ZAKURO_RUNTIME_PREFER", "lxc,docker")][..],
&[("ZAKURO_RUNTIME_PREFER", "incus")][..],
&[("ZAKURO_RUNTIME_PREFER", " LXD , docker ")][..],
&[("ZAKURO_SANDBOX_SHARED", "LXC")][..],
] {
assert_eq!(matrix(true, true, e), (lxc_engine(), true), "{e:?}");
}
let g = env(&[("ZAKURO_RUNTIME_PREFER", "lxc,docker")]);
let c = resolve_shared(
&g,
&probe(RuntimeKind::Lxc, true),
&probe(RuntimeKind::Docker, true),
"incus",
);
assert!(
c.reason
.contains("asked for by ZAKURO_RUNTIME_PREFER=lxc,docker"),
"{}",
c.reason
);
}
#[test]
fn resolution_matrix_neither_names_what_to_install() {
let (e, jobs) = matrix(false, false, &[]);
assert_eq!((e, jobs), (None, false));
let g = env(&[]);
let c = resolve_shared(
&g,
&probe(RuntimeKind::Lxc, false),
&probe(RuntimeKind::Docker, false),
"incus",
);
assert!(
c.reason.contains("apt install incus")
&& c.reason.contains("ZAKURO_SHARE_RUNTIME=host"),
"{}",
c.reason
);
}
#[test]
fn the_job_tier_follows_the_lxc_probe_and_the_isolation_setting() {
let docker = Choice {
engine: Some(Engine::Docker),
reason: "d".into(),
};
let up = probe(RuntimeKind::Lxc, true);
let down = probe(RuntimeKind::Lxc, false);
let g = env(&[]);
assert!(resolve_jobs(&g, &up, &docker).0);
let (per, why) = resolve_jobs(&g, &down, &docker);
assert!(
!per && why.starts_with("FALLBACK: shared engine with limits"),
"{why}"
);
let shared = env(&[("ZAKURO_SANDBOX_ISOLATION", " Shared ")]);
assert!(!resolve_jobs(&shared, &up, &docker).0);
let job = env(&[("ZAKURO_SANDBOX_ISOLATION", "job")]);
assert!(resolve_jobs(&job, &up, &docker).0);
let bad = env(&[("ZAKURO_SANDBOX_ISOLATION", "vm")]);
let (per, why) = resolve_jobs(&bad, &up, &docker);
assert!(!per && why.contains("not one of job, shared"), "{why}");
}
fn rust_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap() {
let p = entry.unwrap().path();
if p.is_dir() {
rust_files(&p, out);
} else if p.extension().is_some_and(|e| e == "rs") {
out.push(p);
}
}
}
const ALLOWED: &[(&str, &str)] = &[
(
"src/sandbox/",
"the sandbox layer itself (backends, probes, this engine)",
),
(
"src/vpn/",
"the WireGuard sidecar is a Docker container by design",
),
(
"src/mesh.rs",
"the local static dev mesh (`zc mesh up`) is Docker-only",
),
("src/exec/", "`zc exec` runs a user-named Docker command"),
("src/common/mod.rs", "legacy `zc build` docker-compose verb"),
(
"src/hub_allocation/mod.rs",
"`docker info` host-memory probe for a hub offer",
),
(
"src/broker/deploy/runtime.rs",
"the Docker probe that `sandbox::probe_host` and `zc doctor` read",
),
];
fn spawns_engine(line: &str) -> bool {
let t = line.trim_start();
!t.starts_with("//")
&& [
"docker", "nerdctl", "podman", "lxc", "incus", "colima", "limactl",
]
.iter()
.any(|b| line.contains(&format!("Command::new(\"{b}\")")))
}
#[test]
fn no_container_engine_is_spawned_outside_the_sandbox_layer() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let mut files = Vec::new();
rust_files(&root.join("src"), &mut files);
assert!(files.len() > 20, "source scan found too few files");
let mut offenders = Vec::new();
for f in &files {
let rel = f.strip_prefix(root).unwrap().to_string_lossy().to_string();
if ALLOWED.iter().any(|(p, _)| rel.starts_with(p)) {
continue;
}
for (i, line) in std::fs::read_to_string(f).unwrap().lines().enumerate() {
if spawns_engine(line) {
offenders.push(format!("{rel}:{}: {}", i + 1, line.trim()));
}
}
}
assert!(
offenders.is_empty(),
"a container engine is spawned outside src/sandbox/ and the allow-list: go through \
sandbox::engine::command / run so the chosen backend (Incus or Docker) is used \
(zc#578):\n{}",
offenders.join("\n")
);
}
#[test]
fn the_scan_flags_a_direct_engine_spawn_and_spares_comments() {
assert!(spawns_engine(
r#" let out = Command::new("docker").args(a).output();"#
));
assert!(spawns_engine(r#"std::process::Command::new("nerdctl")"#));
assert!(spawns_engine(r#"Command::new("incus")"#));
assert!(!spawns_engine(
r#" // Command::new("docker") + captured stdout"#
));
assert!(!spawns_engine(r#"Command::new("git")"#));
for (p, why) in ALLOWED {
assert!(!why.is_empty(), "{p} needs a reason");
}
}
}