diff --git a/docs/sandbox.md b/docs/sandbox.md index 0a68762..d188a2f 100644 --- a/docs/sandbox.md +++ b/docs/sandbox.md @@ -142,15 +142,25 @@ pub struct BuildCommand<'a> { } pub trait SandboxExt: Sandbox { - fn command(&self, program: &str) -> BuildCommand<'_> { /* ... */ } + fn command(&self, program: &str) -> BuildCommand<'_>; + fn stage_tree( + &self, + host: &Path, + dest: &Path, + opts: &StageOptions, + ) -> io::Result; } -impl SandboxExt for T {} +impl SandboxExt for T { /* forward to free functions */ } +impl SandboxExt for dyn Sandbox + '_ { /* same */ } ``` The extension trait keeps `sandbox.command("apt-get")` working on `Arc` without putting a generic or `Self: Sized` method on the -trait. `status`, `output` and `capture` keep their current behavior. +trait. Two impls are needed: a default method cannot coerce `&Self` to +`&dyn Sandbox` when `Self` is unsized, so the blanket impl covers sized +backends and a second impl covers `dyn Sandbox`. Both forward to the same +free functions. `status`, `output` and `capture` keep their current behavior. `src/exec.rs` holds the parts that are about processes, not environments: `Stream`, `LineSink`, `pump`, the `sanitize_fds` pre-exec hook, the diff --git a/src/context/api.rs b/src/context/api.rs index 138ce11..478dbff 100644 --- a/src/context/api.rs +++ b/src/context/api.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use std::sync::Mutex; use crate::exec::LineSink; +use crate::sandbox::contextualize_spawn_error; use super::local::LocalDriver; use super::schroot::SchrootDriver; @@ -534,26 +535,6 @@ impl<'a> ContextCommand<'a> { } } -/// Wrap an I/O error from launching a command with a more helpful message. -/// -/// In particular, a `NotFound` error (e.g. "No such file or directory") is almost always -/// caused by the requested program not being installed or not on `PATH`; we make that -/// explicit instead of leaking the raw OS error. -fn contextualize_spawn_error(program: &str, e: io::Error) -> io::Error { - if e.kind() == io::ErrorKind::NotFound { - io::Error::new( - e.kind(), - format!( - "Could not run '{program}': {e}. \ - The program does not seem to be installed or is not on PATH; \ - install the corresponding package and retry.", - ), - ) - } else { - io::Error::new(e.kind(), format!("Could not run '{program}': {e}")) - } -} - #[cfg(test)] mod endpoint_tests { use super::*; diff --git a/src/context/mod.rs b/src/context/mod.rs index 59bbaf1..cfdc041 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -26,21 +26,7 @@ pub fn current() -> Arc { manager::MANAGER.current() } -/// Version-control metadata directories that must never leak into a -/// prepared build tree. -/// -/// Their presence flips autotools' "building from VCS" detection (e.g. GNU -/// hello's `BUILD_FROM_GIT`, triggered by a `.git` directory next to -/// `configure.ac`), which activates maintainer-only regeneration rules -/// requiring tools that are deliberately not declared as build-dependencies -/// (e.g. `help2man`). Source packages produced by dpkg-source never contain -/// them, so package builds must not see them either. -pub(crate) fn is_vcs_dir_name(name: &std::ffi::OsStr) -> bool { - matches!( - name.to_str(), - Some(".git") | Some(".hg") | Some(".svn") | Some(".bzr") | Some("CVS") - ) -} +pub(crate) use crate::sandbox::staging::is_vcs_dir_name; /// Recursively remove version-control metadata directories below `root`. /// diff --git a/src/lib.rs b/src/lib.rs index a40646b..999a2d6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -47,6 +47,10 @@ pub mod quirks; /// Run a source package's DEP-8 as-installed tests (`pkh test`) pub mod test; +/// A place builds run: the command and filesystem interface, its host +/// implementation and the source-tree staging helper +pub mod sandbox; + /// Line classifiers rewriting raw subprocess output into display actions /// and countable progress (pure logic, shared by build views) pub mod logfmt; diff --git a/src/sandbox/host.rs b/src/sandbox/host.rs new file mode 100644 index 0000000..355800a --- /dev/null +++ b/src/sandbox/host.rs @@ -0,0 +1,150 @@ +//! The host machine as a sandbox. + +use std::fs; +use std::io; +use std::os::unix::fs::symlink; +use std::path::{Path, PathBuf}; + +use super::{BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcome, Sandbox}; + +/// The host machine. +/// +/// Commands run with [`std::process::Command`], files use [`std::fs`], and +/// there is no teardown. This serves `pkh test --mode local` and the unit +/// tests that build a local context. +#[derive(Debug, Default)] +pub struct Host; + +impl Host { + /// Create a host sandbox. + pub fn new() -> Self { + Host + } +} + +impl Sandbox for Host { + fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result { + let args: Vec = cmd + .args + .iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect(); + let env: Vec<(String, String)> = cmd + .env + .iter() + .map(|(key, value)| { + ( + key.to_string_lossy().into_owned(), + value.to_string_lossy().into_owned(), + ) + }) + .collect(); + let cwd = cmd.cwd.as_deref().map(|path| path.to_string_lossy()); + let program = cmd.program.to_string_lossy(); + + match capture { + Capture::Inherit => { + let status = crate::exec::run(&program, &args, &env, cwd.as_deref())?; + Ok(Execution { + status, + stdout: Vec::new(), + stderr: Vec::new(), + }) + } + Capture::Lines(sink) => { + let status = + crate::exec::run_captured(&program, &args, &env, cwd.as_deref(), sink)?; + Ok(Execution { + status, + stdout: Vec::new(), + stderr: Vec::new(), + }) + } + Capture::Output => { + let output = crate::exec::run_output(&program, &args, &env, cwd.as_deref())?; + Ok(Execution { + status: output.status, + stdout: output.stdout, + stderr: output.stderr, + }) + } + } + } + + fn read_file(&self, path: &Path) -> io::Result { + fs::read_to_string(path) + } + + fn write_file(&self, path: &Path, content: &str) -> io::Result<()> { + fs::write(path, content) + } + + fn exists(&self, path: &Path) -> io::Result { + Ok(path.exists()) + } + + fn is_dir(&self, path: &Path) -> io::Result { + Ok(path.is_dir()) + } + + fn list_files(&self, path: &Path) -> io::Result> { + let mut entries = Vec::new(); + for entry in fs::read_dir(path)? { + entries.push(entry?.path()); + } + Ok(entries) + } + + fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> io::Result { + copy_tree(host, dest, &opts.skip_dirs)?; + Ok(PutOutcome::Fresh) + } + + fn get(&self, src: &Path, dest: &Path) -> io::Result<()> { + copy_tree(src, dest, &[]) + } + + fn remove(&self, path: &Path) -> io::Result<()> { + match fs::symlink_metadata(path) { + Ok(meta) if meta.is_dir() => fs::remove_dir_all(path), + Ok(_) => fs::remove_file(path), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), + } + } + + fn create_temp_dir(&self) -> io::Result { + super::unique_dir(&std::env::temp_dir(), "pkh-") + .map(|path| path.to_string_lossy().into_owned()) + } + + fn cleanup(&self, _outcome: Option) -> io::Result<()> { + Ok(()) + } +} + +/// Copy `src` to `dest`, reproducing symlinks and skipping `skip_dirs` by +/// name at any depth. +fn copy_tree(src: &Path, dest: &Path, skip_dirs: &[std::ffi::OsString]) -> io::Result<()> { + let meta = fs::symlink_metadata(src)?; + if meta.file_type().is_symlink() { + let target = fs::read_link(src)?; + let _ = fs::remove_file(dest); + return symlink(target, dest); + } + + if meta.is_dir() { + fs::create_dir_all(dest)?; + for entry in fs::read_dir(src)? { + let entry = entry?; + let name = entry.file_name(); + if entry.file_type()?.is_dir() && skip_dirs.iter().any(|skip| skip == &name) { + continue; + } + copy_tree(&entry.path(), &dest.join(&name), skip_dirs)?; + } + } else { + fs::copy(src, dest)?; + } + Ok(()) +} diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs new file mode 100644 index 0000000..d7fe9c1 --- /dev/null +++ b/src/sandbox/mod.rs @@ -0,0 +1,397 @@ +//! A place builds run: a command runner and a filesystem. +//! +//! Build code receives a `Sandbox` explicitly. Paths passed to the trait are +//! paths inside the sandbox; only [`Sandbox::put`] and [`Sandbox::get`] cross +//! the host boundary. + +use std::ffi::{OsStr, OsString}; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::{ExitStatus, Output}; +use std::sync::Arc; + +use crate::exec::LineSink; + +mod host; +pub(crate) mod staging; + +pub use host::Host; +pub use staging::{StageOptions, stage_tree}; + +/// A place a build runs: a command runner and a filesystem. +pub trait Sandbox: Send + Sync { + /// Run a command inside the environment. + fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result; + + /// Read a small text file from inside the environment. + fn read_file(&self, path: &Path) -> io::Result; + + /// Write a small text file inside the environment. + fn write_file(&self, path: &Path, content: &str) -> io::Result<()>; + + /// Check whether a path exists inside the environment. + fn exists(&self, path: &Path) -> io::Result; + + /// Check whether a path is a directory inside the environment. + fn is_dir(&self, path: &Path) -> io::Result; + + /// List the entries of a directory inside the environment. + fn list_files(&self, path: &Path) -> io::Result>; + + /// Copy a host file or tree to `dest` inside the environment. + /// + /// `dest` is the copied entry's full path, not a parent directory. + fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> io::Result; + + /// Copy a file or tree from the environment to `dest` on the host. + /// + /// `dest` is the copied entry's full path, not a parent directory. + fn get(&self, src: &Path, dest: &Path) -> io::Result<()>; + + /// Remove a file or directory tree inside the environment. + /// + /// Removing a path that does not exist succeeds. + fn remove(&self, path: &Path) -> io::Result<()>; + + /// Create a fresh temporary directory inside the environment. + fn create_temp_dir(&self) -> io::Result; + + /// Release mounts, devices or guest state and apply the teardown policy. + /// + /// Idempotent. `outcome` is `None` when the owner did not report one. + fn cleanup(&self, outcome: Option) -> io::Result<()> { + let _ = outcome; + Ok(()) + } +} + +/// A command description, independent of the backend that runs it. +#[derive(Debug, Clone, Default)] +pub struct CommandSpec { + /// Program to run. + pub program: OsString, + /// Arguments passed to the program. + pub args: Vec, + /// Environment variables set for the program. + pub env: Vec<(OsString, OsString)>, + /// Working directory inside the environment. + pub cwd: Option, +} + +/// How a command's output is handled. +#[derive(Clone)] +pub enum Capture { + /// Let the child use the parent's standard streams. + Inherit, + /// Pipe the output and forward each decoded line to a sink. + Lines(Arc), + /// Capture the complete output. + Output, +} + +/// The result of running a command. +#[derive(Debug)] +pub struct Execution { + /// Exit status of the command. + pub status: ExitStatus, + /// Standard output, filled only for [`Capture::Output`]. + pub stdout: Vec, + /// Standard error, filled only for [`Capture::Output`]. + pub stderr: Vec, +} + +/// Copy policies a backend applies when importing a host tree. +#[derive(Debug, Clone, Default)] +pub struct PutOptions { + /// Backend state to reuse for a resumable tree copy. + pub reuse: Option, + /// Directory names to skip at any depth. + pub skip_dirs: Vec, +} + +/// Whether a `put` copied from scratch or reused earlier state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PutOutcome { + /// The destination was copied from the host. + Fresh, + /// A previous copy's state was reused. + Resumed, +} + +/// Final outcome reported to [`Sandbox::cleanup`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BuildOutcome { + /// The build completed successfully. + Success, + /// The build failed. + Failure, +} + +/// Builder for one command run through a [`Sandbox`]. +pub struct BuildCommand<'a> { + sandbox: &'a dyn Sandbox, + spec: CommandSpec, + capture: Capture, +} + +impl<'a> BuildCommand<'a> { + /// Add an argument to the command. + pub fn arg>(&mut self, arg: S) -> &mut Self { + self.spec.args.push(arg.as_ref().to_os_string()); + self + } + + /// Add several arguments to the command. + pub fn args(&mut self, args: I) -> &mut Self + where + I: IntoIterator, + S: AsRef, + { + for arg in args { + self.arg(arg); + } + self + } + + /// Set an environment variable for the command. + pub fn env(&mut self, key: K, val: V) -> &mut Self + where + K: AsRef, + V: AsRef, + { + self.spec + .env + .push((key.as_ref().to_os_string(), val.as_ref().to_os_string())); + self + } + + /// Set several environment variables for the command. + pub fn envs(&mut self, vars: I) -> &mut Self + where + I: IntoIterator, + K: AsRef, + V: AsRef, + { + for (key, val) in vars { + self.env(key, val); + } + self + } + + /// Set the command's working directory inside the environment. + pub fn current_dir>(&mut self, dir: P) -> &mut Self { + self.spec.cwd = Some(dir.as_ref().to_path_buf()); + self + } + + /// Forward the command's output line by line to `sink`. + pub fn capture(&mut self, sink: Arc) -> &mut Self { + self.capture = Capture::Lines(sink); + self + } + + /// Run the command and return its exit status. + pub fn status(&mut self) -> io::Result { + let capture = self.capture.clone(); + self.sandbox + .run(&self.spec, capture) + .map(|execution| execution.status) + .map_err(|e| contextualize_spawn_error(&self.spec.program.to_string_lossy(), e)) + } + + /// Run the command and capture its complete output. + pub fn output(&mut self) -> io::Result { + self.sandbox + .run(&self.spec, Capture::Output) + .map(|execution| Output { + status: execution.status, + stdout: execution.stdout, + stderr: execution.stderr, + }) + .map_err(|e| contextualize_spawn_error(&self.spec.program.to_string_lossy(), e)) + } +} + +/// Convenience methods available on every [`Sandbox`]. +pub trait SandboxExt: Sandbox { + /// Start building a command to run in this sandbox. + fn command(&self, program: &str) -> BuildCommand<'_>; + + /// Copy a host source tree into the sandbox, applying the build policy. + fn stage_tree(&self, host: &Path, dest: &Path, opts: &StageOptions) -> io::Result; +} + +fn command_for<'a>(sandbox: &'a dyn Sandbox, program: &str) -> BuildCommand<'a> { + BuildCommand { + sandbox, + spec: CommandSpec { + program: OsString::from(program), + ..CommandSpec::default() + }, + capture: Capture::Inherit, + } +} + +impl SandboxExt for T { + fn command(&self, program: &str) -> BuildCommand<'_> { + command_for(self, program) + } + + fn stage_tree(&self, host: &Path, dest: &Path, opts: &StageOptions) -> io::Result { + staging::stage_tree(self, host, dest, opts) + } +} + +impl SandboxExt for dyn Sandbox + '_ { + fn command(&self, program: &str) -> BuildCommand<'_> { + command_for(self, program) + } + + fn stage_tree(&self, host: &Path, dest: &Path, opts: &StageOptions) -> io::Result { + staging::stage_tree(self, host, dest, opts) + } +} + +/// Wrap an I/O error from launching a command with a more helpful message. +pub(crate) fn contextualize_spawn_error(program: &str, e: io::Error) -> io::Error { + if e.kind() == io::ErrorKind::NotFound { + io::Error::new( + e.kind(), + format!( + "Could not run '{program}': {e}. \ + The program does not seem to be installed or is not on PATH; \ + install the corresponding package and retry.", + ), + ) + } else { + io::Error::new(e.kind(), format!("Could not run '{program}': {e}")) + } +} + +/// Create a uniquely named directory under `base`. +pub(crate) fn unique_dir(base: &Path, prefix: &str) -> io::Result { + let base_timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + + let mut attempt = 0; + loop { + let name = if attempt == 0 { + format!("{prefix}{base_timestamp}") + } else { + format!("{prefix}{base_timestamp}-{attempt}") + }; + let path = base.join(name); + match std::fs::create_dir(&path) { + Ok(()) => return Ok(path), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => attempt += 1, + Err(e) => return Err(e), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::exec::{LineSink, Stream}; + use std::sync::Mutex; + + struct CollectingSink(Mutex>); + + impl CollectingSink { + fn new() -> Self { + CollectingSink(Mutex::new(Vec::new())) + } + } + + impl LineSink for CollectingSink { + fn line(&self, stream: Stream, line: &str) { + self.0.lock().unwrap().push((stream, line.to_string())); + } + } + + fn conformance(sandbox: &dyn Sandbox) { + let root = PathBuf::from(sandbox.create_temp_dir().unwrap()); + assert!(sandbox.is_dir(&root).unwrap()); + + let file = root.join("hello.txt"); + sandbox.write_file(&file, "hello").unwrap(); + assert!(sandbox.exists(&file).unwrap()); + assert_eq!(sandbox.read_file(&file).unwrap(), "hello"); + assert_eq!(sandbox.list_files(&root).unwrap().len(), 1); + + let host = tempfile::tempdir().unwrap(); + let src = host.path().join("src.txt"); + std::fs::write(&src, "host").unwrap(); + let dest = root.join("imported.txt"); + let outcome = sandbox.put(&src, &dest, &PutOptions::default()).unwrap(); + assert_eq!(outcome, PutOutcome::Fresh); + assert_eq!(sandbox.read_file(&dest).unwrap(), "host"); + + let out = host.path().join("out.txt"); + sandbox.get(&dest, &out).unwrap(); + assert_eq!(std::fs::read_to_string(&out).unwrap(), "host"); + + let tree = host.path().join("tree"); + std::fs::create_dir_all(tree.join(".git")).unwrap(); + std::fs::write(tree.join("keep.txt"), "keep").unwrap(); + std::fs::write(tree.join(".git/HEAD"), "ref").unwrap(); + let staged = root.join("tree"); + let opts = PutOptions { + reuse: None, + skip_dirs: vec![".git".into()], + }; + sandbox.put(&tree, &staged, &opts).unwrap(); + assert!(sandbox.exists(&staged.join("keep.txt")).unwrap()); + assert!(!sandbox.exists(&staged.join(".git")).unwrap()); + + let staged_by_helper = root.join("tree-helper"); + let stage_opts = StageOptions { + reuse: None, + prune_vcs: true, + }; + sandbox + .stage_tree(&tree, &staged_by_helper, &stage_opts) + .unwrap(); + assert!(sandbox.exists(&staged_by_helper.join("keep.txt")).unwrap()); + assert!(!sandbox.exists(&staged_by_helper.join(".git")).unwrap()); + + let output = sandbox + .command("sh") + .args(["-c", "echo out; echo err >&2"]) + .output() + .unwrap(); + assert!(output.status.success()); + assert_eq!(output.stdout, b"out\n"); + assert_eq!(output.stderr, b"err\n"); + + let sink = Arc::new(CollectingSink::new()); + let status = sandbox + .command("sh") + .args(["-c", "echo line"]) + .capture(sink.clone()) + .status() + .unwrap(); + assert!(status.success()); + assert_eq!( + sink.0.lock().unwrap().as_slice(), + &[(Stream::Stdout, "line".to_string())] + ); + + sandbox.remove(&root).unwrap(); + assert!(!sandbox.exists(&root).unwrap()); + sandbox.cleanup(None).unwrap(); + } + + #[test] + fn host_conforms() { + conformance(&Host::new()); + } + + #[test] + fn command_works_through_arc() { + let sandbox: Arc = Arc::new(Host::new()); + assert!(sandbox.command("true").status().unwrap().success()); + } +} diff --git a/src/sandbox/staging.rs b/src/sandbox/staging.rs new file mode 100644 index 0000000..a0b685d --- /dev/null +++ b/src/sandbox/staging.rs @@ -0,0 +1,82 @@ +//! Source-tree staging: VCS pruning and resumable copies. + +use std::ffi::{OsStr, OsString}; +use std::io; +use std::path::{Path, PathBuf}; + +use super::{PutOptions, PutOutcome, Sandbox}; + +/// Policy for [`stage_tree`]. +#[derive(Debug, Clone, Default)] +pub struct StageOptions { + /// Backend state to reuse for a resumable tree copy. + pub reuse: Option, + /// Remove VCS metadata from the staged tree. + pub prune_vcs: bool, +} + +/// Version-control metadata directories that must never leak into a build +/// tree. +/// +/// Their presence flips autotools' "building from VCS" detection (e.g. GNU +/// hello's `BUILD_FROM_GIT`, triggered by a `.git` directory next to +/// `configure.ac`), which activates maintainer-only regeneration rules +/// requiring tools that are deliberately not declared as build-dependencies +/// (e.g. `help2man`). Source packages produced by dpkg-source never contain +/// them, so package builds must not see them either. +pub(crate) const VCS_DIR_NAMES: &[&str] = &[".git", ".hg", ".svn", ".bzr", "CVS"]; + +/// Copy a host source tree into `sandbox`, applying the staging policy. +pub fn stage_tree( + sandbox: &dyn Sandbox, + host: &Path, + dest: &Path, + opts: &StageOptions, +) -> io::Result { + let put = PutOptions { + reuse: opts.reuse.clone(), + skip_dirs: if opts.prune_vcs { + vcs_dir_names() + } else { + Vec::new() + }, + }; + let outcome = sandbox.put(host, dest, &put)?; + if opts.prune_vcs { + // An overlay mount exposes the lower tree, so skipping during the + // copy is not enough. + prune_vcs_dirs(sandbox, dest)?; + } + Ok(outcome) +} + +/// Check whether a directory name is version-control metadata. +pub(crate) fn is_vcs_dir_name(name: &OsStr) -> bool { + name.to_str() + .is_some_and(|name| VCS_DIR_NAMES.contains(&name)) +} + +fn vcs_dir_names() -> Vec { + VCS_DIR_NAMES.iter().map(OsString::from).collect() +} + +/// Recursively remove version-control metadata directories below `root`. +pub(crate) fn prune_vcs_dirs(sandbox: &dyn Sandbox, root: &Path) -> io::Result<()> { + let mut pending = vec![root.to_path_buf()]; + while let Some(dir) = pending.pop() { + for entry in sandbox.list_files(&dir)? { + let Some(name) = entry.file_name() else { + continue; + }; + if !sandbox.is_dir(&entry)? { + continue; + } + if is_vcs_dir_name(name) { + sandbox.remove(&entry)?; + } else { + pending.push(entry); + } + } + } + Ok(()) +}