Skip to main content

byob_exec/env/
container.rs

1//! Containers: a workspace can run its commands inside one long-lived Docker or Podman
2//! container instead of on this machine (opt-in per workspace; asked once when the
3//! workspace has a devcontainer.json).
4//!
5//! - **One container per workspace**, named `byob-<folder>-<hash of the path>` and
6//!   labeled `byob.managed=1`, `byob.workspace=<path>`, `byob.config=<stamp>`. It's
7//!   created on first use, reused across commands and byob restarts, and recreated when
8//!   devcontainer.json (or the image setting) changes. It idles in a `sleep` loop under
9//!   `--init`.
10//! - **The workspace is mounted at the same path** (`-v /ws:/ws`), so paths in output,
11//!   scripts and changed-file reports mean the same inside and out. byob's per-run temp
12//!   folders live under `<data>/envs/<ws>/ctmp`, mounted the same way.
13//! - **Commands run as the host user** (`exec -u uid:gid`; Podman adds
14//!   `--userns=keep-id`), so files they write aren't owned by root. `install_packages`
15//!   runs as root (apt-get / apk / dnf, and pip for Python libraries).
16//! - **Network follows the call**: the container is disconnected from its network after
17//!   creation and connected only while a call with `network: true` (or an install) runs.
18//! - **Stop and timeouts reach inside**: each run records its process group (the
19//!   `docker exec` process leads one), which is killed in the container when the run is
20//!   stopped or times out — killing the CLI alone would leave it running.
21//! - byob's own sandbox (Landlock, Seatbelt) doesn't apply inside: the container is the
22//!   isolation. A container can only reach the workspace and byob's temp folder.
23
24use byob_types::process::NoWindow as _;
25use std::collections::BTreeMap;
26use std::ffi::OsString;
27use std::path::{Path, PathBuf};
28use std::process::Command;
29use std::sync::{Mutex, PoisonError};
30use std::time::Duration;
31
32use byob_sandbox::{Outcome, RunOptions};
33
34use super::devcontainer::{Cmd, Image, Spec};
35use super::{Installed, STOPPED, fnv64};
36
37/// The image for workspaces without a devcontainer.json: small, Debian (apt), Python 3.
38pub const DEFAULT_IMAGE: &str = "python:3-slim";
39/// `docker` or `podman`: overrides the settings and the automatic choice.
40pub const RUNTIME_ENV: &str = "BYOB_CONTAINER_RUNTIME";
41
42const QUICK: Duration = Duration::from_secs(60);
43const SLOW: Duration = Duration::from_secs(1800);
44const MAX_CLI_OUTPUT: usize = 64 * 1024;
45/// Keeps the container alive doing nothing until it's stopped.
46const IDLE: &str = "trap 'exit 0' TERM INT; while sleep 1000; do :; done";
47/// Records the run's process group, sets up the user's home, runs the command.
48const WRAPPER: &str = r#"echo $$ > "$BYOB_PID"; mkdir -p "$HOME" 2>/dev/null; export PATH="$HOME/.local/bin:$PATH"; exec "$@""#;
49const HOME: &str = "/tmp/byob-home";
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum RuntimeKind {
53    Docker,
54    Podman,
55}
56
57/// The container CLI.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Runtime {
60    pub kind: RuntimeKind,
61    pub program: PathBuf,
62}
63
64impl Runtime {
65    /// `pref` ("docker", "podman"; [`RUNTIME_ENV`] wins over it) or, by default, Podman
66    /// if it's installed (rootless: a container escape is only the user), else Docker.
67    /// Not on Windows yet (workspace paths can't be mounted at the same path).
68    pub fn detect(pref: Option<&str>) -> Option<Self> {
69        if cfg!(windows) {
70            return None;
71        }
72        let find = |kind: RuntimeKind| {
73            let name = if kind == RuntimeKind::Docker { "docker" } else { "podman" };
74            byob_sandbox::which(name.as_ref()).map(|program| Self { kind, program })
75        };
76        let env = std::env::var(RUNTIME_ENV).ok();
77        match env.as_deref().or(pref).map(|p| p.trim().to_ascii_lowercase()).as_deref() {
78            Some("docker") => find(RuntimeKind::Docker),
79            Some("podman") => find(RuntimeKind::Podman),
80            _ => find(RuntimeKind::Podman).or_else(|| find(RuntimeKind::Docker)),
81        }
82    }
83
84    pub fn name(&self) -> &'static str {
85        match self.kind {
86            RuntimeKind::Docker => "docker",
87            RuntimeKind::Podman => "podman",
88        }
89    }
90
91    /// The network a container joins for network access.
92    fn network(&self) -> &'static str {
93        match self.kind {
94            RuntimeKind::Docker => "bridge",
95            RuntimeKind::Podman => "podman",
96        }
97    }
98
99    /// Run the CLI (outside byob's sandbox: it talks to the daemon, or is Podman itself).
100    fn call<S: AsRef<std::ffi::OsStr>>(&self, args: &[S], timeout: Duration, cancelled: &dyn Fn() -> bool) -> Result<Outcome, String> {
101        let mut cmd = Command::new(&self.program);
102        cmd.no_window();
103        cmd.args(args);
104        let opts = RunOptions { timeout, max_output: MAX_CLI_OUTPUT, ..Default::default() };
105        byob_sandbox::run(cmd, &opts, cancelled).map_err(|e| format!("can't run {}: {e}", self.name()))
106    }
107
108    /// Run the CLI and require success; returns stdout, trimmed.
109    fn ok<S: AsRef<std::ffi::OsStr>>(&self, args: &[S], timeout: Duration, cancelled: &dyn Fn() -> bool) -> Result<String, String> {
110        let out = self.call(args, timeout, cancelled)?;
111        if out.cancelled {
112            return Err(STOPPED.into());
113        }
114        if out.timed_out {
115            return Err(format!("`{} {}` took too long", self.name(), first_args(args)));
116        }
117        if !out.success() {
118            return Err(format!("`{} {}` failed: {}", self.name(), first_args(args), out.stderr.text().trim()));
119        }
120        Ok(out.stdout.text().trim().to_owned())
121    }
122
123    /// Whether the daemon (or Podman) answers; the error says what to do.
124    pub fn check(&self) -> Result<(), String> {
125        let never = || false;
126        match self.call(&["info", "--format", "{{.ServerVersion}}"], QUICK, &never) {
127            Ok(out) if out.success() => Ok(()),
128            Ok(out) => Err(unreachable_message(self, out.stderr.text().trim())),
129            Err(e) => Err(unreachable_message(self, &e)),
130        }
131    }
132}
133
134fn first_args<S: AsRef<std::ffi::OsStr>>(args: &[S]) -> String {
135    args.iter().take(2).map(|a| a.as_ref().to_string_lossy().into_owned()).collect::<Vec<_>>().join(" ")
136}
137
138fn unreachable_message(rt: &Runtime, detail: &str) -> String {
139    let what = if rt.kind == RuntimeKind::Docker { "Docker isn't running or can't be reached" } else { "Podman doesn't work here" };
140    let detail: String = detail.lines().take(3).collect::<Vec<_>>().join(" ");
141    format!(
142        "{what} (`{} info`: {detail}). Nothing ran. Start it, or choose another environment in the workspace's settings \
143         (its menu in the chat list).",
144        rt.name()
145    )
146}
147
148/// A container ready to run commands in.
149#[derive(Debug, Clone)]
150pub struct Ready {
151    pub name: String,
152    /// For messages: the image, or what it was built from.
153    pub image: String,
154    pub remote_env: Vec<(String, String)>,
155    /// Per-run temp folders go here (mounted at the same path).
156    pub tmp_base: PathBuf,
157    /// Created (or recreated) just now.
158    pub fresh: bool,
159    /// Problems worth telling the model (a failed postCreateCommand, …).
160    pub notes: Vec<String>,
161}
162
163/// The containers of all workspaces, through one runtime.
164#[derive(Debug)]
165pub struct Containers {
166    pub runtime: Runtime,
167    pub default_image: String,
168    /// One creation at a time.
169    creating: Mutex<()>,
170    /// Runs using the network, per container.
171    online: Mutex<BTreeMap<String, usize>>,
172}
173
174/// `byob-<folder>-<hash>`: stable per workspace path, valid as a container name.
175pub fn container_name(ws: &Path) -> String {
176    let folder: String = ws
177        .file_name()
178        .map(|n| n.to_string_lossy().chars().filter(|c| c.is_ascii_alphanumeric() || "-_".contains(*c)).take(24).collect::<String>().to_ascii_lowercase())
179        .unwrap_or_default();
180    let hash = fnv64(ws.as_os_str().as_encoded_bytes());
181    format!("byob-{}-{:012x}", if folder.is_empty() { "ws" } else { &folder }, hash & 0xffff_ffff_ffff)
182}
183
184/// What the container was made from, as a label: recreate when it changes.
185fn stamp(spec: &Spec, rt: &Runtime) -> String {
186    let mut s = format!("v1\0{:?}\0{:?}\0{:?}\0", rt.kind, spec.env, spec.on_create);
187    match &spec.image {
188        Image::Pull(i) => s.push_str(i),
189        Image::Build { dockerfile, context, args } => {
190            s.push_str(&format!("{}\0{}\0{args:?}\0", dockerfile.display(), context.display()));
191            s.push_str(&String::from_utf8_lossy(&std::fs::read(dockerfile).unwrap_or_default()));
192        }
193    }
194    format!("{:016x}", fnv64(s.as_bytes()))
195}
196
197/// `uid:gid` of whoever owns `p` (a folder byob just made: this process's user).
198#[cfg(unix)]
199fn user_of(p: &Path) -> Option<String> {
200    use std::os::unix::fs::MetadataExt;
201    let m = std::fs::metadata(p).ok()?;
202    Some(format!("{}:{}", m.uid(), m.gid()))
203}
204
205#[cfg(not(unix))]
206fn user_of(_p: &Path) -> Option<String> {
207    None
208}
209
210/// The variables every run gets (like the sandbox's clean environment).
211fn run_env(tmp: &Path) -> Vec<(String, String)> {
212    let t = tmp.to_string_lossy().into_owned();
213    let mut v: Vec<(String, String)> = [
214        ("HOME", HOME),
215        ("LANG", "C.UTF-8"),
216        ("MPLBACKEND", "Agg"),
217        ("PYTHONIOENCODING", "utf-8"),
218        ("PYTHONUNBUFFERED", "1"),
219        ("PYTHONDONTWRITEBYTECODE", "1"),
220        ("PIP_DISABLE_PIP_VERSION_CHECK", "1"),
221        ("TERM", "dumb"),
222        ("NO_COLOR", "1"),
223        ("PAGER", "cat"),
224        ("GIT_PAGER", "cat"),
225    ]
226    .into_iter()
227    .map(|(k, v)| (k.to_owned(), v.to_owned()))
228    .collect();
229    for k in ["TMPDIR", "TMP", "TEMP"] {
230        v.push((k.to_owned(), t.clone()));
231    }
232    v.push(("MPLCONFIGDIR".into(), format!("{t}/.matplotlib")));
233    v
234}
235
236/// One command to run in a container.
237#[derive(Debug)]
238pub struct Exec {
239    pub argv: Vec<OsString>,
240    pub env: Vec<(String, OsString)>,
241    pub network: bool,
242    pub timeout: Duration,
243}
244
245impl Containers {
246    pub fn new(runtime: Runtime, default_image: Option<String>) -> Self {
247        let default_image = default_image.filter(|i| super::devcontainer::valid_image(i)).unwrap_or_else(|| DEFAULT_IMAGE.to_owned());
248        Self { runtime, default_image, creating: Mutex::new(()), online: Mutex::new(BTreeMap::new()) }
249    }
250
251    /// The container's state ("running", "exited", …), `None` if there is none (or the
252    /// daemon doesn't answer).
253    pub fn state(&self, ws: &Path) -> Option<String> {
254        let never = || false;
255        self.runtime.ok(&["container", "inspect", "--format", "{{.State.Status}}", &container_name(ws)], QUICK, &never).ok().filter(|s| !s.is_empty())
256    }
257
258    pub fn stop(&self, ws: &Path) -> Result<String, String> {
259        let never = || false;
260        let name = container_name(ws);
261        self.runtime.ok(&["stop", "-t", "3", &name], QUICK, &never)?;
262        Ok(format!("Stopped {name}; it starts again on the next command."))
263    }
264
265    pub fn remove(&self, ws: &Path) -> Result<String, String> {
266        let never = || false;
267        let name = container_name(ws);
268        self.runtime.ok(&["rm", "-f", &name], QUICK, &never)?;
269        Ok(format!("Removed {name}; the next command creates a new one."))
270    }
271
272    /// The workspace's container, created or started as needed. `tmp_base` is the folder
273    /// for per-run temp folders (in byob's data folder).
274    pub fn ensure(&self, ws: &Path, spec: &Spec, tmp_base: &Path, cancelled: &dyn Fn() -> bool) -> Result<Ready, String> {
275        let _one = self.creating.lock().unwrap_or_else(PoisonError::into_inner);
276        let rt = &self.runtime;
277        let name = container_name(ws);
278        let want = stamp(spec, rt);
279        std::fs::create_dir_all(tmp_base).map_err(|e| format!("can't create {}: {e}", tmp_base.display()))?;
280        let tmp_base = tmp_base.canonicalize().map_err(|e| format!("{}: {e}", tmp_base.display()))?;
281        let mut ready = Ready {
282            name: name.clone(),
283            image: spec.describe(ws),
284            remote_env: spec.remote_env.clone(),
285            tmp_base: tmp_base.clone(),
286            fresh: false,
287            notes: Vec::new(),
288        };
289        let inspect = rt.call(&["container", "inspect", "--format", "{{.State.Status}}|{{index .Config.Labels \"byob.config\"}}", &name], QUICK, cancelled)?;
290        if inspect.success() {
291            let text = inspect.stdout.text();
292            let (status, label) = text.trim().split_once('|').unwrap_or((text.trim(), ""));
293            if label == want {
294                if status != "running" {
295                    rt.ok(&["start", &name], QUICK, cancelled)?;
296                }
297                return Ok(ready);
298            }
299            rt.ok(&["rm", "-f", &name], QUICK, cancelled)?;
300            ready.notes.push("The workspace's container was recreated because its configuration changed; packages installed in the old one are gone.".into());
301        } else {
302            let err = inspect.stderr.text();
303            if !err.to_ascii_lowercase().contains("no such") {
304                rt.check()?;
305                return Err(format!("`{} container inspect` failed: {}", rt.name(), err.trim()));
306            }
307        }
308        let image = self.image(ws, spec, cancelled)?;
309        let mut args: Vec<String> = vec!["run".into(), "-d".into(), "--init".into(), "--name".into(), name.clone()];
310        for (k, v) in [("byob.managed", "1".to_owned()), ("byob.workspace", ws.display().to_string()), ("byob.config", want)] {
311            args.extend(["--label".into(), format!("{k}={v}")]);
312        }
313        for dir in [ws, tmp_base.as_path()] {
314            args.extend(["-v".into(), format!("{0}:{0}", dir.display())]);
315        }
316        args.extend(["-w".into(), ws.display().to_string(), "--network".into(), rt.network().into()]);
317        if rt.kind == RuntimeKind::Podman {
318            args.push("--userns=keep-id".into());
319        }
320        for (k, v) in &spec.env {
321            args.extend(["-e".into(), format!("{k}={v}")]);
322        }
323        args.extend(["--entrypoint".into(), "/bin/sh".into(), image, "-c".into(), IDLE.into()]);
324        rt.ok(&args, SLOW, cancelled)?;
325        ready.fresh = true;
326        // Lifecycle commands, as root, with network (they usually install things).
327        for c in &spec.on_create {
328            let mut a: Vec<String> = vec!["exec".into(), "-u".into(), "0".into(), "-w".into(), ws.display().to_string(), name.clone()];
329            match c {
330                Cmd::Shell(s) => a.extend(["/bin/sh".into(), "-c".into(), s.clone()]),
331                Cmd::Args(v) => a.extend(v.iter().cloned()),
332            }
333            match rt.call(&a, SLOW, cancelled) {
334                Ok(o) if o.success() => {}
335                Ok(o) if o.cancelled => return Err(STOPPED.into()),
336                Ok(o) => ready.notes.push(format!("The devcontainer's setup command failed (exit {:?}): {}", o.exit_code, o.stderr.text().trim())),
337                Err(e) => ready.notes.push(format!("The devcontainer's setup command didn't run: {e}")),
338            }
339        }
340        // No network until a call asks for it.
341        if let Err(e) = rt.ok(&["network", "disconnect", rt.network(), &name], QUICK, cancelled) {
342            log::warn!("containers: {name} keeps its network: {e}");
343            ready.notes.push(format!("byob couldn't take the container's network away ({e}), so every command has internet access."));
344        }
345        Ok(ready)
346    }
347
348    /// The image to run: pulled if missing, or built.
349    fn image(&self, ws: &Path, spec: &Spec, cancelled: &dyn Fn() -> bool) -> Result<String, String> {
350        let rt = &self.runtime;
351        match &spec.image {
352            Image::Pull(i) => {
353                if !rt.call(&["image", "inspect", "--format", "{{.Id}}", i], QUICK, cancelled)?.success() {
354                    rt.ok(&["pull", i.as_str()], SLOW, cancelled).map_err(|e| format!("couldn't get the image {i}: {e}"))?;
355                }
356                Ok(i.clone())
357            }
358            Image::Build { dockerfile, context, args } => {
359                let tag = format!("{}:{}", container_name(ws).replacen("byob-", "byob-image-", 1), stamp(spec, rt));
360                let mut a: Vec<String> = vec!["build".into(), "-t".into(), tag.clone(), "-f".into(), dockerfile.display().to_string()];
361                for (k, v) in args {
362                    a.extend(["--build-arg".into(), format!("{k}={v}")]);
363                }
364                a.push(context.display().to_string());
365                rt.ok(&a, SLOW, cancelled).map_err(|e| format!("building the dev container image failed: {e}"))?;
366                Ok(tag)
367            }
368        }
369    }
370
371    /// Connect `name` to the network while `f` runs (counted, so overlapping runs share).
372    fn online<T>(&self, name: &str, on: bool, f: impl FnOnce() -> T) -> (T, Option<String>) {
373        if !on {
374            return (f(), None);
375        }
376        let never = || false;
377        let mut problem = None;
378        {
379            let mut users = self.online.lock().unwrap_or_else(PoisonError::into_inner);
380            let n = users.entry(name.to_owned()).or_insert(0);
381            if *n == 0
382                && let Err(e) = self.runtime.ok(&["network", "connect", self.runtime.network(), name], QUICK, &never)
383                && !e.contains("already exists")
384            {
385                problem = Some(format!("couldn't give the container network access: {e}"));
386            }
387            *n += 1;
388        }
389        let out = f();
390        let mut users = self.online.lock().unwrap_or_else(PoisonError::into_inner);
391        let n = users.entry(name.to_owned()).or_insert(1);
392        *n = n.saturating_sub(1);
393        if *n == 0 {
394            users.remove(name);
395            if let Err(e) = self.runtime.ok(&["network", "disconnect", self.runtime.network(), name], QUICK, &never) {
396                log::warn!("containers: {name}: {e}");
397            }
398        }
399        (out, problem)
400    }
401
402    /// Run `job` in the container as this user, with `cwd` (the workspace) and `tmp`
403    /// (under `ready.tmp_base`) as its temp folder.
404    pub fn exec(&self, ready: &Ready, job: Exec, cwd: &Path, tmp: &Path, cancelled: &dyn Fn() -> bool) -> Result<(Outcome, Option<String>), String> {
405        let pid_file = tmp.join(".byob-pid");
406        let mut args: Vec<OsString> = vec!["exec".into()];
407        if let Some(u) = user_of(tmp) {
408            args.extend(["-u".into(), u.into()]);
409        }
410        args.extend(["-w".into(), cwd.as_os_str().to_owned()]);
411        let mut env: Vec<(String, OsString)> = run_env(tmp).into_iter().map(|(k, v)| (k, v.into())).collect();
412        env.extend(ready.remote_env.iter().map(|(k, v)| (k.clone(), v.into())));
413        env.extend(job.env);
414        env.push(("BYOB_PID".into(), pid_file.clone().into_os_string()));
415        for (k, v) in env {
416            let mut kv = OsString::from(format!("{k}="));
417            kv.push(v);
418            args.extend(["-e".into(), kv]);
419        }
420        args.extend([ready.name.clone().into(), "/bin/sh".into(), "-c".into(), WRAPPER.into(), "sh".into()]);
421        args.extend(job.argv);
422        let (out, problem) = self.online(&ready.name, job.network, || self.runtime.call(&args, job.timeout, cancelled));
423        let out = out?;
424        if out.timed_out || out.cancelled {
425            self.kill(ready, &pid_file);
426        }
427        Ok((out, problem))
428    }
429
430    /// Kill the run whose process group is in `pid_file`, inside the container.
431    fn kill(&self, ready: &Ready, pid_file: &Path) {
432        let Some(pid) = std::fs::read_to_string(pid_file).ok().and_then(|s| s.trim().parse::<u32>().ok()).filter(|p| *p > 1) else { return };
433        let never = || false;
434        let script = format!("kill -9 -{pid} 2>/dev/null; kill -9 {pid} 2>/dev/null; true");
435        if let Err(e) = self.runtime.ok(&["exec", "-u", "0", &ready.name, "/bin/sh", "-c", &script], QUICK, &never) {
436            log::warn!("containers: couldn't stop a run in {}: {e}", ready.name);
437        }
438    }
439
440    /// Install `packages` in the container as root: the distribution's package manager for
441    /// programs, pip for Python libraries (and for names it doesn't know).
442    pub fn install(&self, ready: &Ready, ws: &Path, packages: &[String], cancelled: &dyn Fn() -> bool) -> Result<Installed, String> {
443        let names: Vec<String> = packages.iter().map(|p| install_name(p)).collect::<Result<_, _>>()?;
444        let mut args: Vec<String> = vec!["exec".into(), "-u".into(), "0".into(), "-w".into(), ws.display().to_string()];
445        for (k, v) in [
446            ("DEBIAN_FRONTEND", "noninteractive"),
447            ("PIP_BREAK_SYSTEM_PACKAGES", "1"),
448            ("PIP_ROOT_USER_ACTION", "ignore"),
449            ("PIP_DISABLE_PIP_VERSION_CHECK", "1"),
450        ] {
451            args.extend(["-e".into(), format!("{k}={v}")]);
452        }
453        args.extend([ready.name.clone(), "/bin/sh".into(), "-c".into(), INSTALL.into(), "sh".into()]);
454        args.extend(names);
455        let (out, problem) = self.online(&ready.name, true, || self.runtime.call(&args, SLOW, cancelled));
456        let out = out?;
457        if out.cancelled {
458            return Err(STOPPED.into());
459        }
460        let report = parse_install(&out.stdout.text());
461        if let Some(p) = problem {
462            return Err(format!("{p}\n{}", out.stderr.text().trim()));
463        }
464        if report.manager.is_empty() && report.pip.is_empty() && report.missing.is_empty() {
465            return Err(format!("installing failed: {}", out.stderr.text().trim()));
466        }
467        Ok(report.describe(&out.stderr.text()))
468    }
469}
470
471/// Shell script run as root in the container: `$@` are names, `py:` marks Python libraries.
472/// Prints `BYOB-PM <manager>`, `BYOB-OS <names>` / `BYOB-OSFAIL <names>`, `BYOB-PIP <name>`,
473/// `BYOB-MISSING <name>` on stdout; the managers' output goes to stderr.
474const INSTALL: &str = r#"
475pm=""
476for m in apt-get apk dnf microdnf yum; do command -v $m >/dev/null 2>&1 && { pm=$m; break; }; done
477echo "BYOB-PM $pm"
478case "$pm" in apt-get) apt-get update -qq >&2 ;; apk) apk update -q >&2 ;; esac
479os=""; py=""
480for n in "$@"; do
481  case "$n" in py:*) py="$py ${n#py:}"; continue ;; esac
482  case "$pm" in
483    apt-get) apt-cache show "$n" >/dev/null 2>&1 && os="$os $n" || py="$py $n" ;;
484    apk) apk search -qe "$n" 2>/dev/null | grep -qx "$n" && os="$os $n" || py="$py $n" ;;
485    dnf|microdnf|yum) $pm info "$n" >/dev/null 2>&1 && os="$os $n" || py="$py $n" ;;
486    *) py="$py $n" ;;
487  esac
488done
489if [ -n "$os" ]; then
490  case "$pm" in
491    apt-get) apt-get install -y -qq --no-install-recommends $os >&2 ;;
492    apk) apk add --no-cache $os >&2 ;;
493    *) $pm install -y $os >&2 ;;
494  esac && echo "BYOB-OS$os" || echo "BYOB-OSFAIL$os"
495fi
496if [ -n "$py" ]; then
497  if ! python3 -m pip --version >/dev/null 2>&1; then
498    case "$pm" in
499      apt-get) apt-get install -y -qq --no-install-recommends python3 python3-pip >&2 ;;
500      apk) apk add --no-cache python3 py3-pip >&2 ;;
501      dnf|microdnf|yum) $pm install -y python3 python3-pip >&2 ;;
502    esac
503  fi
504  for p in $py; do
505    if python3 -m pip install -q "$p" >&2; then echo "BYOB-PIP $p"; else echo "BYOB-MISSING $p"; fi
506  done
507fi
508"#;
509
510/// What [`INSTALL`] reported.
511#[derive(Debug, Default, PartialEq, Eq)]
512pub struct Report {
513    pub manager: String,
514    pub os: Vec<String>,
515    pub os_failed: Vec<String>,
516    pub pip: Vec<String>,
517    pub missing: Vec<String>,
518}
519
520pub fn parse_install(stdout: &str) -> Report {
521    let mut r = Report::default();
522    for line in stdout.lines() {
523        let words = |rest: &str| rest.split_whitespace().map(str::to_owned).collect::<Vec<_>>();
524        if let Some(rest) = line.strip_prefix("BYOB-PM") {
525            rest.trim().clone_into(&mut r.manager);
526        } else if let Some(rest) = line.strip_prefix("BYOB-OSFAIL") {
527            r.os_failed.extend(words(rest));
528        } else if let Some(rest) = line.strip_prefix("BYOB-OS") {
529            r.os.extend(words(rest));
530        } else if let Some(rest) = line.strip_prefix("BYOB-PIP") {
531            r.pip.extend(words(rest));
532        } else if let Some(rest) = line.strip_prefix("BYOB-MISSING") {
533            r.missing.extend(words(rest));
534        }
535    }
536    r
537}
538
539impl Report {
540    fn describe(&self, stderr: &str) -> Installed {
541        let mut text = Vec::new();
542        if !self.os.is_empty() {
543            text.push(format!("Installed in the container with {}: {}.", self.manager, self.os.join(", ")));
544        }
545        if !self.pip.is_empty() {
546            text.push(format!("Installed in the container with pip: {} (run_python's python3 has them).", self.pip.join(", ")));
547        }
548        if !self.os.is_empty() || !self.pip.is_empty() {
549            text.push("run_command and run_python can use them now; they stay in this workspace's container.".into());
550        }
551        if !self.os_failed.is_empty() {
552            let tail: String = stderr.lines().rev().take(8).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n");
553            text.push(format!("{} couldn't install {}:\n{tail}", self.manager, self.os_failed.join(", ")));
554        }
555        if !self.missing.is_empty() {
556            text.push(format!(
557                "Not found{}: {}. Call install_packages again with the exact package name.",
558                if self.manager.is_empty() { String::new() } else { format!(" with {} or pip", self.manager) },
559                self.missing.iter().map(|m| format!("{m:?}")).collect::<Vec<_>>().join(", ")
560            ));
561        }
562        let failed = !self.missing.is_empty() || !self.os_failed.is_empty();
563        Installed { text: text.join("\n"), failed, missing: self.missing.clone() }
564    }
565}
566
567/// Python libraries models commonly ask for: installed with pip, not as system packages.
568const PIP_NAMES: &[&str] = &[
569    "numpy",
570    "pandas",
571    "matplotlib",
572    "scipy",
573    "seaborn",
574    "plotly",
575    "requests",
576    "httpx",
577    "openpyxl",
578    "xlrd",
579    "pyyaml",
580    "beautifulsoup4",
581    "lxml",
582    "sympy",
583    "statsmodels",
584    "pillow",
585    "scikit-learn",
586    "networkx",
587    "tabulate",
588    "polars",
589    "pyarrow",
590    "jinja2",
591    "pytest",
592    "flask",
593    "fastapi",
594    "torch",
595    "tqdm",
596    "rich",
597    "click",
598    "pydantic",
599    "python-dateutil",
600    "pytz",
601    "markdown",
602    "pypdf",
603    "reportlab",
604    "python-docx",
605];
606
607/// The name to pass to [`INSTALL`]: `py:<name>` for Python libraries, a Debian-style name
608/// otherwise; refuses anything that isn't a plain package name.
609pub fn install_name(raw: &str) -> Result<String, String> {
610    let p = raw.trim();
611    let (py, p) = match p.strip_prefix("python3Packages.").or_else(|| p.strip_prefix("python3.pkgs.")) {
612        Some(rest) => (true, rest),
613        None => (false, p),
614    };
615    let ok = !p.is_empty() && p.len() <= 100 && !p.starts_with(['-', '.']) && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.+=<>!~,".contains(c));
616    if !ok {
617        return Err(format!("{raw:?} is not a package name (like \"jq\" or \"pandas\")"));
618    }
619    let lower = p.to_ascii_lowercase();
620    let base = lower.split(['=', '<', '>', '!', '~']).next().unwrap_or(&lower);
621    let pip = py || PIP_NAMES.contains(&base) || super::nix::PYTHON_IMPORTS.iter().any(|(_, pkg)| *pkg == base);
622    if pip {
623        return Ok(format!("py:{p}"));
624    }
625    let os = match base {
626        "poppler_utils" | "poppler" => "poppler-utils",
627        "gnumake" => "make",
628        "python" => "python3",
629        "fd" => "fd-find",
630        "nodejs_22" | "nodejs_20" | "node" => "nodejs",
631        _ => base,
632    };
633    Ok(os.to_owned())
634}
635
636/// A per-run temp folder under the container's temp base, removed when dropped.
637#[derive(Debug)]
638pub struct RunTmp(PathBuf);
639
640impl RunTmp {
641    pub fn new(base: &Path) -> Result<Self, String> {
642        for attempt in 0..16u32 {
643            let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0);
644            let p = base.join(format!("run-{}-{nanos:x}-{attempt}", std::process::id()));
645            match std::fs::create_dir(&p) {
646                Ok(()) => return Ok(Self(p)),
647                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
648                Err(e) => return Err(format!("can't create a temp folder in {}: {e}", base.display())),
649            }
650        }
651        Err("can't create a temp folder".into())
652    }
653
654    pub fn path(&self) -> &Path {
655        &self.0
656    }
657}
658
659impl Drop for RunTmp {
660    fn drop(&mut self) {
661        let _ = std::fs::remove_dir_all(&self.0);
662    }
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668
669    #[test]
670    fn names_are_stable_and_valid() {
671        let a = container_name(Path::new("/home/me/My Project"));
672        assert_eq!(a, container_name(Path::new("/home/me/My Project")));
673        assert_ne!(a, container_name(Path::new("/home/you/My Project")));
674        assert!(a.starts_with("byob-myproject-") && a.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'), "{a}");
675        assert!(container_name(Path::new("/")).starts_with("byob-ws-"));
676    }
677
678    #[test]
679    fn install_names() {
680        assert_eq!(install_name("jq").unwrap(), "jq");
681        assert_eq!(install_name("pandas").unwrap(), "py:pandas");
682        assert_eq!(install_name("scikit-learn").unwrap(), "py:scikit-learn");
683        assert_eq!(install_name("python3Packages.six").unwrap(), "py:six");
684        assert_eq!(install_name("numpy>=2").unwrap(), "py:numpy>=2");
685        assert_eq!(install_name("poppler_utils").unwrap(), "poppler-utils");
686        for bad in ["", "-y", "a b", "x;rm -rf /", "$(id)"] {
687            assert!(install_name(bad).is_err(), "{bad}");
688        }
689    }
690
691    #[test]
692    fn install_reports() {
693        let r = parse_install("BYOB-PM apt-get\nBYOB-OS jq ripgrep\nBYOB-PIP pandas\nBYOB-MISSING nosuch\n");
694        assert_eq!(
695            r,
696            Report {
697                manager: "apt-get".into(),
698                os: vec!["jq".into(), "ripgrep".into()],
699                os_failed: vec![],
700                pip: vec!["pandas".into()],
701                missing: vec!["nosuch".into()]
702            }
703        );
704        let i = r.describe("");
705        assert!(i.failed && i.missing == vec!["nosuch".to_owned()]);
706        assert!(
707            i.text.contains("with apt-get: jq, ripgrep") && i.text.contains("pip: pandas") && i.text.contains("Not found with apt-get or pip: \"nosuch\""),
708            "{}",
709            i.text
710        );
711        let ok = parse_install("BYOB-PM apk\nBYOB-OS jq\n").describe("");
712        assert!(!ok.failed && ok.text.contains("with apk: jq"));
713    }
714
715    #[test]
716    fn stamps_change_with_the_config() {
717        let rt = Runtime { kind: RuntimeKind::Docker, program: "docker".into() };
718        let a = Spec::default_image("python:3-slim");
719        let b = Spec::default_image("debian:stable-slim");
720        assert_eq!(stamp(&a, &rt), stamp(&a.clone(), &rt));
721        assert_ne!(stamp(&a, &rt), stamp(&b, &rt));
722        let podman = Runtime { kind: RuntimeKind::Podman, program: "podman".into() };
723        assert_ne!(stamp(&a, &rt), stamp(&a, &podman));
724        assert_eq!(Containers::new(rt.clone(), Some("--bad".into())).default_image, DEFAULT_IMAGE);
725        assert_eq!(Containers::new(rt, Some("alpine:3".into())).default_image, "alpine:3");
726    }
727
728    #[test]
729    fn the_daemon_being_down_says_what_to_do() {
730        let rt = Runtime { kind: RuntimeKind::Docker, program: "docker".into() };
731        let m = unreachable_message(&rt, "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?");
732        assert!(m.contains("Docker isn't running") && m.contains("Cannot connect") && m.contains("workspace's settings"), "{m}");
733    }
734}