diff --git a/docs/sandbox.md b/docs/sandbox.md index d188a2f..b6116c6 100644 --- a/docs/sandbox.md +++ b/docs/sandbox.md @@ -84,6 +84,11 @@ pub trait Sandbox: Send + Sync { /// A fresh temporary directory inside the environment. fn create_temp_dir(&self) -> io::Result; + /// Whether this sandbox is the host machine. Defaults to `false`. + fn is_host(&self) -> bool { + false + } + /// Release mounts, devices or guest state and apply the teardown /// policy. Idempotent. `outcome` is `None` when the owner did not /// report one. Defaults to a no-op. @@ -179,9 +184,16 @@ The trait has three transfer primitives: `put` takes the copy policies the backend needs to apply: ```rust +pub struct ReuseState { + /// Overlay upper directory. + pub upper: PathBuf, + /// Overlay work directory. + pub work: PathBuf, +} + pub struct PutOptions { /// Backend state to reuse for a resumable tree copy. - pub reuse: Option, + pub reuse: Option, /// Directory names to skip at any depth. pub skip_dirs: Vec, } @@ -204,7 +216,7 @@ directory. The caller builds the final name. ```rust pub struct StageOptions { /// Backend state to reuse for a resumable tree copy. - pub reuse: Option, + pub reuse: Option, /// Remove VCS metadata from the staged tree. pub prune_vcs: bool, } @@ -479,8 +491,8 @@ The commit scopes follow `AGENTS.md`: add `sandbox`, `build_profile` and 2. Staging and `--incremental`. Host-side overlayfs is specific to the unshare backend. The `put` and `stage_tree` API must be settled before `Ecrou`, or the Ecrou backend will not support incremental builds. -3. Trait size. The trait has 11 methods, and every backend must implement all - of them. One trait keeps `Arc` simple. If it grows, split +3. Trait size. The trait has 11 required methods and one provided capability + method (`is_host`), and every backend implement the required ones. One trait keeps `Arc` simple. If it grows, split it into `CommandRunner` and `FileSystem` supertraits rather than adding optional methods. 4. Per-call cost over a microVM channel. A file read is cheap on the host and a @@ -510,10 +522,11 @@ The commit scopes follow `AGENTS.md`: add `sandbox`, `build_profile` and state fields. Pruning and the `--incremental` base check also assume a tarball; the microVM image identity has to replace or extend that check. Add the backend tag before the Ecrou work, not after. -11. Resume state shape. `PutOptions.reuse` is a host `PathBuf` because - `Unshare` keeps its upper and work layers on the host. An Ecrou overlay may - live inside the guest. Decide whether `reuse` becomes an opaque token - before Ecrou, or whether Ecrou also keeps its resume state on the host. +11. Resume state shape. `PutOptions.reuse` is a `ReuseState` holding host + paths because `Unshare` keeps its upper and work layers on the host. An + Ecrou overlay may live inside the guest. Decide whether `reuse` becomes an + opaque token before Ecrou, or whether Ecrou also keeps its resume state on + the host. ## Testing diff --git a/src/apt/keyring.rs b/src/apt/keyring.rs index 40eec9c..5f9c144 100644 --- a/src/apt/keyring.rs +++ b/src/apt/keyring.rs @@ -6,6 +6,7 @@ use crate::context; use crate::data::embed_data; use crate::distro_info; +use crate::sandbox::{Sandbox, SandboxExt}; use serde::Deserialize; use std::error::Error; use std::os::unix::fs::MetadataExt; @@ -57,10 +58,13 @@ struct LaunchpadPpaResponse { /// # Returns /// The path to the keyring directory containing all downloaded keyring files pub async fn download_cache_keyrings( - ctx: Option>, + ctx: Option>, series: &str, ) -> Result> { - let ctx = ctx.unwrap_or_else(context::current); + let ctx: Arc = match ctx { + Some(ctx) => ctx, + None => context::current(), + }; // Obtain keyring URLs from distro_info let keyring_urls = distro_info::get_keyring_urls(series).await?; @@ -76,7 +80,7 @@ pub async fn download_cache_keyrings( let keyring_dir = temp_dir.join(format!("pkh-keyrings-{euid}")); if ctx.exists(&keyring_dir)? { - if let context::ContextConfig::Local = ctx.config { + if ctx.is_host() { // Cached keyrings are trusted as-is whenever they already exist, // so refuse to reuse a directory that is not owned by the current // user or is writable by group/others (it could have been planted @@ -242,11 +246,14 @@ fn validate_keyring_dir(dir_uid: u32, mode: u32, euid: u32) -> Result<(), String /// # Returns /// Result indicating success or failure pub async fn download_trust_ppa_key( - ctx: Option>, + ctx: Option>, ppa_owner: &str, ppa_name: &str, ) -> Result<(), Box> { - let ctx = ctx.unwrap_or_else(context::current); + let ctx: Arc = match ctx { + Some(ctx) => ctx, + None => context::current(), + }; // Create trusted.gpg.d directory if it doesn't exist let trusted_gpg_d = "/etc/apt/trusted.gpg.d"; diff --git a/src/apt/sources.rs b/src/apt/sources.rs index 82c376e..ff8cc65 100644 --- a/src/apt/sources.rs +++ b/src/apt/sources.rs @@ -5,8 +5,9 @@ //! be written back without loss, and remember the file they were loaded //! from ([`SourceEntry::origin`]) so that saving writes each entry back to //! its own file, in that file's own format. -use crate::context::{self, Context}; +use crate::context; use crate::debian::control::{Paragraph, parse_paragraphs, write_paragraph}; +use crate::sandbox::Sandbox; use std::error::Error; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -332,19 +333,22 @@ pub fn parse_legacy(data: &str) -> Vec { /// Reads the deb822 distro sources (ubuntu.sources or debian.sources), the /// legacy '/etc/apt/sources.list' and the pkh-owned added-sources file when /// they exist. Every entry remembers the file and format it came from. -pub fn load(ctx: Option>) -> Result, Box> { +pub fn load(ctx: Option>) -> Result, Box> { let mut sources = Vec::new(); - let ctx = ctx.unwrap_or_else(context::current); + let ctx: Arc = match ctx { + Some(ctx) => ctx, + None => context::current(), + }; // Try DEB822 format first (Ubuntu 24.04+ and Debian Trixie+) load_file( - &ctx, + ctx.as_ref(), "/etc/apt/sources.list.d/ubuntu.sources", SourceFormat::Deb822, &mut sources, )?; load_file( - &ctx, + ctx.as_ref(), "/etc/apt/sources.list.d/debian.sources", SourceFormat::Deb822, &mut sources, @@ -352,14 +356,19 @@ pub fn load(ctx: Option>) -> Result, Box>) -> Result, Box.pkh-backup' copy is created once /// before the first overwrite. -pub fn save(ctx: Option>, sources: Vec) -> Result<(), Box> { - let ctx = ctx.unwrap_or_else(context::current); +pub fn save( + ctx: Option>, + sources: Vec, +) -> Result<(), Box> { + let ctx: Arc = match ctx { + Some(ctx) => ctx, + None => context::current(), + }; for (path, _format, content) in plan_writes(&sources) { let original = if ctx.exists(&path)? { @@ -389,10 +404,10 @@ pub fn save(ctx: Option>, sources: Vec) -> Result<(), } // One-time backup before overwriting an existing file - if original.is_some() { + if let Some(original) = &original { let backup = backup_path(&path); if !ctx.exists(&backup)? { - ctx.copy_path(&path, &backup)?; + ctx.write_file(&backup, original)?; } } @@ -405,7 +420,7 @@ pub fn save(ctx: Option>, sources: Vec) -> Result<(), /// Load entries from one sources file, if it exists, tagging them with /// their origin fn load_file( - ctx: &Context, + ctx: &dyn Sandbox, path: &str, format: SourceFormat, out: &mut Vec, @@ -477,7 +492,7 @@ fn backup_path(path: &Path) -> PathBuf { #[cfg(test)] mod tests { use super::*; - use crate::context::ContextConfig; + use crate::context::{Context, ContextConfig}; #[tokio::test] async fn test_parse_deb822() { diff --git a/src/build/binary.rs b/src/build/binary.rs index b85923f..1937ed6 100644 --- a/src/build/binary.rs +++ b/src/build/binary.rs @@ -2,7 +2,7 @@ //! production for binary-only builds (`pkh deb`), the equivalent of //! `dpkg-genbuildinfo -b` + `dpkg-genchanges -b`. //! -//! All tree/database access goes through a [`Context`] so the generation can +//! All tree/database access goes through a [`Sandbox`] so the generation can //! run against a build tree living in a local directory, an ephemeral //! chroot or a remote host. Artifact digests are computed inside the context //! with coreutils (`md5sum`, `sha1sum`, `sha256sum`, `stat`), keeping the @@ -13,8 +13,8 @@ use std::error::Error; use std::path::{Path, PathBuf}; use std::sync::Arc; -use crate::context::Context; use crate::debian::{ChecksumEntry, ControlInfo, FileChecksums, FilesList}; +use crate::sandbox::{Sandbox, SandboxExt}; /// Digests of one artifact. #[derive(Debug, Clone, Default)] @@ -57,7 +57,7 @@ pub struct BinaryMetadataOptions { /// registration in `debian/files`, and binary-NMU handling (`Source: /// pkg (prev)` + `Binary-Only-Changes`, with no source files distributed). pub fn generate_binary_metadata( - ctx: &Arc, + ctx: &Arc, package_dir: &Path, upload_dir: &Path, opts: &BinaryMetadataOptions, @@ -330,7 +330,7 @@ pub fn generate_binary_metadata( /// Compute md5/sha1/sha256 digests and sizes for the named files inside the /// context directory `dir`, using coreutils. fn hashes_in_context( - ctx: &Arc, + ctx: &Arc, dir: &Path, names: &[String], ) -> Result, Box> { @@ -488,7 +488,7 @@ Description: test package std::fs::write(base.path().join("hello_1.0-1+b1_all.deb"), "deb payload") .expect("write deb"); - let ctx = Arc::new( + let ctx: Arc = Arc::new( crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"), ); let opts = BinaryMetadataOptions { @@ -547,7 +547,7 @@ Description: test package .expect("chmod files"); } - let ctx = Arc::new( + let ctx: Arc = Arc::new( crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"), ); let opts = BinaryMetadataOptions { @@ -622,7 +622,7 @@ Description: test package std::fs::write(base.path().join("hello_1.0.orig.tar.xz"), "tarball bytes") .expect("write previous tarball"); - let ctx = Arc::new( + let ctx: Arc = Arc::new( crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"), ); let opts = BinaryMetadataOptions { diff --git a/src/build/mod.rs b/src/build/mod.rs index 4185ed4..3ffc45a 100644 --- a/src/build/mod.rs +++ b/src/build/mod.rs @@ -2005,7 +2005,7 @@ Provides: virtual-thing (= 2.0), plain-virtual assert!(status.success(), "debian/rules {target} failed"); } - let ctx = std::sync::Arc::new( + let ctx: std::sync::Arc = std::sync::Arc::new( crate::context::Context::new(crate::context::ContextConfig::Local).unwrap(), ); let native_arch = crate::debian::arch::native().unwrap_or_else(|_| "amd64".into()); diff --git a/src/context/mod.rs b/src/context/mod.rs index cfdc041..55991f3 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,6 +1,7 @@ mod api; mod local; mod manager; +mod sandbox_impl; mod schroot; pub(crate) mod shell; mod ssh; diff --git a/src/context/sandbox_impl.rs b/src/context/sandbox_impl.rs new file mode 100644 index 0000000..55a7581 --- /dev/null +++ b/src/context/sandbox_impl.rs @@ -0,0 +1,148 @@ +//! The `Sandbox` bridge for the old `Context` API. +//! +//! The build code receives `Arc` while the unshare driver is +//! still a `ContextDriver`. This bridge maps the trait onto the driver until +//! the driver moves into `sandbox::unshare`. + +use std::io; +use std::path::Path; + +use crate::sandbox::{ + BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcome, Sandbox, +}; + +use super::Context; + +impl Sandbox for Context { + fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result { + let driver_guard = self.driver(); + let driver = driver_guard.as_ref().unwrap(); + let program = cmd.program.to_string_lossy().into_owned(); + 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()); + + match capture { + Capture::Inherit => { + let status = driver.run(&program, &args, &env, cwd.as_deref())?; + Ok(Execution { + status, + stdout: Vec::new(), + stderr: Vec::new(), + }) + } + Capture::Lines(sink) => { + let status = driver.run_captured(&program, &args, &env, cwd.as_deref(), sink)?; + Ok(Execution { + status, + stdout: Vec::new(), + stderr: Vec::new(), + }) + } + Capture::Output => { + let output = driver.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 { + Context::read_file(self, path) + } + + fn write_file(&self, path: &Path, content: &str) -> io::Result<()> { + Context::write_file(self, path, content) + } + + fn exists(&self, path: &Path) -> io::Result { + Context::exists(self, path) + } + + fn is_dir(&self, path: &Path) -> io::Result { + Context::is_dir(self, path) + } + + fn list_files(&self, path: &Path) -> io::Result> { + Context::list_files(self, path) + } + + fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> io::Result { + let dest_root = dest.parent().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "destination has no parent") + })?; + let dest_root = dest_root.to_string_lossy(); + + if let Some(reuse) = &opts.reuse { + let staging = Context::ensure_available_with_overlay( + self, + host, + &dest_root, + &reuse.upper, + &reuse.work, + )?; + return Ok(if staging.overlay { + PutOutcome::Resumed + } else { + PutOutcome::Fresh + }); + } + + let staged = Context::ensure_available(self, host, &dest_root)?; + if staged != dest { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!( + "put destination '{}' does not match the staged path '{}'", + dest.display(), + staged.display() + ), + )); + } + Ok(PutOutcome::Fresh) + } + + fn get(&self, src: &Path, dest: &Path) -> io::Result<()> { + Context::retrieve_path(self, src, dest) + } + + fn remove(&self, path: &Path) -> io::Result<()> { + let status = Context::command(self, "rm").arg("-rf").arg(path).status()?; + if status.success() { + Ok(()) + } else { + Err(io::Error::other(format!( + "failed to remove '{}': rm exited with {status}", + path.display() + ))) + } + } + + fn create_temp_dir(&self) -> io::Result { + Context::create_temp_dir(self) + } + + fn is_host(&self) -> bool { + matches!(self.config, crate::context::ContextConfig::Local) + } + + fn cleanup(&self, _outcome: Option) -> io::Result<()> { + Context::cleanup(self) + } +} diff --git a/src/deb/cross.rs b/src/deb/cross.rs index 5a28439..3569203 100644 --- a/src/deb/cross.rs +++ b/src/deb/cross.rs @@ -1,4 +1,4 @@ -use crate::context::Context; +use crate::sandbox::{Sandbox, SandboxExt}; use log::debug; use std::collections::HashMap; use std::error::Error; @@ -31,7 +31,7 @@ pub fn parse_dpkg_architecture_output(output: &str, env: &mut HashMap, arch: &str, - ctx: Arc, + ctx: Arc, ) -> Result<(), Box> { let output = ctx .command("dpkg-architecture") @@ -113,7 +113,7 @@ pub fn ensure_repositories( series: &str, pocket: Option<&str>, mirror: Option<&str>, - ctx: Arc, + ctx: Arc, ) -> Result<(), Box> { let local_arch = crate::get_current_arch(); @@ -227,6 +227,7 @@ pub fn ensure_repositories( #[cfg(test)] mod tests { use super::*; + use crate::context::Context; #[test] fn test_parse_dpkg_architecture_output() { diff --git a/src/deb/local.rs b/src/deb/local.rs index 700fe69..035ef23 100644 --- a/src/deb/local.rs +++ b/src/deb/local.rs @@ -1,10 +1,10 @@ -/// Local binary package building -/// Directly calling 'debian/rules' in current context -use crate::context::{Context, ContextCommand}; use crate::deb::{BuildProfiler, Phase, enter_phase, find_dsc_file}; use crate::exec::LineSink; use crate::logfmt::QuiltClassifier; use crate::report::BuildView; +/// Local binary package building +/// Directly calling 'debian/rules' in current context +use crate::sandbox::{BuildCommand, Sandbox, SandboxExt, StageOptions}; use log::warn; use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::error::Error; @@ -21,9 +21,9 @@ use std::time::Instant; /// Attach the capture sink to a command when the live UI is active fn cap<'a>( - cmd: &'a mut ContextCommand<'a>, + cmd: &'a mut BuildCommand<'a>, sink: &Option>, -) -> &'a mut ContextCommand<'a> { +) -> &'a mut BuildCommand<'a> { if let Some(s) = sink { cmd.capture(s.clone()); } @@ -118,7 +118,7 @@ enum RulesIdentity { /// (`--map-user`), the pivot wrapper working, and the mapping actually /// taken. The probe runs the real wrapper over a `sh` test, so a failure /// here means the fallback would fail the same way. -fn probe_mapped_namespace(ctx: &Arc) -> Result<(), String> { +fn probe_mapped_namespace(ctx: &Arc) -> Result<(), String> { let mut cmd = ctx.command("sh"); cmd.env(crate::context::MAPPED_IDENTITY_ENV, "1") .arg("-c") @@ -155,7 +155,7 @@ fn probe_mapped_namespace(ctx: &Arc) -> Result<(), String> { /// the overlay staging every chowned lower-layer file copy-ups, which on /// a kernel tree costs minutes (see [`hand_over_script`]). fn ensure_build_user( - ctx: &Arc, + ctx: &Arc, workroot: &Path, session: Option<&session::Session>, build_resume: bool, @@ -199,7 +199,7 @@ fn ensure_build_user( // Through sh with the stderr dropped: a missing user is the expected // state in a fresh chroot, not a message the build log needs. - let id_of = |ctx: &Arc, what: &str| { + let id_of = |ctx: &Arc, what: &str| { ctx.command("sh") .arg("-c") .arg(format!("id {what} {BUILD_USER} 2>/dev/null")) @@ -243,7 +243,7 @@ fn ensure_build_user( /// the chroot carries no useradd). Minimal mmdebstrap chroots carry no /// passwd package, so the entries are appended directly, as sbuild's /// build-user setup does. -fn write_build_user_entries(ctx: &Arc, id: u32) -> Result<(), Box> { +fn write_build_user_entries(ctx: &Arc, id: u32) -> Result<(), Box> { // Through sh with the stderr dropped: a missing entry is the expected // state in a fresh chroot, not a message the build log needs. let known = ctx @@ -425,7 +425,11 @@ fn hand_over_script(dir: &str, uid: &str, gid: &str) -> String { /// Run [`hand_over_script`] against `dir`, failing the build when the /// escalation cannot complete: a tree half-owned by root fails the rules /// on their first write into it. -fn hand_over(ctx: &Arc, dir: &Path, ids: &(String, String)) -> Result<(), Box> { +fn hand_over( + ctx: &Arc, + dir: &Path, + ids: &(String, String), +) -> Result<(), Box> { let status = ctx .command("sh") .arg("-c") @@ -441,7 +445,7 @@ fn hand_over(ctx: &Arc, dir: &Path, ids: &(String, String)) -> Result<( /// Create [`BUILD_USER`] in the build context (the setpriv fallback). /// Chroots carrying the passwd package take the useradd path; minimal /// mmdebstrap ones append the entries directly at a fixed, free id. -fn create_build_user(ctx: &Arc) -> Result<(), Box> { +fn create_build_user(ctx: &Arc) -> Result<(), Box> { let have_useradd = ctx .command("sh") .arg("-c") @@ -496,10 +500,10 @@ fn shlex_quote(value: &str) -> String { /// DEB_BUILD_OPTIONS survive the transition. Without an identity the /// rules run as the context's own. fn rules_command<'a>( - ctx: &'a Arc, + ctx: &'a Arc, identity: Option<&RulesIdentity>, program: &str, -) -> ContextCommand<'a> { +) -> BuildCommand<'a> { match identity { Some(RulesIdentity::MappedNamespace) => { let mut cmd = ctx.command(program); @@ -531,7 +535,7 @@ pub async fn build( cross: bool, ppa: &[String], inject_packages: &[String], - ctx: Arc, + ctx: Arc, view: &dyn BuildView, jobs: Option, session: Option<&session::Session>, @@ -1233,7 +1237,7 @@ fn next_install_pass( /// what surfaces foreign-arch candidates. Names missing from the indexes /// and virtual names simply produce no stanza. fn query_candidates( - ctx: &Arc, + ctx: &Arc, names: &[String], build_arch: &str, host_arch: &str, @@ -1270,7 +1274,7 @@ fn query_candidates( } /// Build architecture inside the build context. -fn context_build_arch(ctx: &Arc) -> String { +fn context_build_arch(ctx: &Arc) -> String { ctx.command("dpkg") .arg("--print-architecture") .output() @@ -1284,7 +1288,7 @@ fn context_build_arch(ctx: &Arc) -> String { /// Active build profiles for the dependency evaluation: what the build /// steps run with (`DEB_BUILD_PROFILES`, set to `cross` for cross /// builds), else the vendor defaults. -fn build_profiles_for(env: &HashMap, ctx: &Arc) -> Vec { +fn build_profiles_for(env: &HashMap, ctx: &Arc) -> Vec { match env.get("DEB_BUILD_PROFILES") { Some(value) => value .split(',') @@ -1305,7 +1309,7 @@ fn build_profiles_for(env: &HashMap, ctx: &Arc) -> Vec< /// Installed-package facts inside the build context. An unreadable status /// database (fresh chroot) yields empty facts: everything declared then /// installs. -fn load_context_facts(ctx: &Arc, build_arch: &str, host_arch: &str) -> Facts { +fn load_context_facts(ctx: &Arc, build_arch: &str, host_arch: &str) -> Facts { match ctx.read_file(Path::new("/var/lib/dpkg/status")) { Ok(content) => Facts::from_status(&content, host_arch, build_arch), Err(e) => { @@ -1336,7 +1340,7 @@ fn install_build_dependencies( upload_dir: &str, cross: bool, env: &HashMap, - ctx: Arc, + ctx: Arc, view: &dyn BuildView, sink: &Option>, timings: &mut session::BuildTimings, @@ -1525,7 +1529,7 @@ fn install_build_dependencies( /// exactly those instead of globbing the build root (which would also pick /// up stale files copied alongside the package tree). fn collect_binary_artifacts( - ctx: &Arc, + ctx: &Arc, package_dir: &str, upload_dir: &str, ) -> Result, Box> { @@ -1552,7 +1556,7 @@ fn generate_upload_metadata( arch: &str, cross: bool, env: &HashMap, - ctx: &Arc, + ctx: &Arc, ) -> Result<(PathBuf, PathBuf), Box> { // Build architecture: the machine inside the build context. let build_arch = ctx @@ -1643,7 +1647,7 @@ fn series_patches_to_apply(series_content: &str, single_debian_patch: bool) -> V fn apply_quilt_patches( package_dir: &str, env: &HashMap, - ctx: Arc, + ctx: Arc, view: &dyn BuildView, sink: &Option>, pop_first: bool, @@ -1783,7 +1787,7 @@ fn apply_quilt_patches( /// dash — is exactly `single-debian-patch` (both spellings exist in the /// wild). A line merely containing the token as a substring (e.g. /// `--single-debian-patch-foo`) does not count. -fn uses_single_debian_patch(ctx: &Context, package_dir: &Path) -> bool { +fn uses_single_debian_patch(ctx: &Arc, package_dir: &Path) -> bool { let local_options = ctx .read_file(&package_dir.join("debian/source/local-options")) .ok(); @@ -1816,7 +1820,7 @@ fn options_declare_single_debian_patch(local_options: Option<&str>, options: Opt /// suite on every repository carrying it (archive, security and ports), /// for all architectures, so this also covers cross-builds pulling /// dependencies from 'ports.ubuntu.com'. -pub(crate) fn pin_pocket(pocket_suite: &str, ctx: &Arc) -> Result<(), Box> { +pub(crate) fn pin_pocket(pocket_suite: &str, ctx: &Arc) -> Result<(), Box> { let pin_path = format!("/etc/apt/preferences.d/pkh-{}", pocket_suite); let pin_content = format!( "Package: *\nPin: release a={}\nPin-Priority: 600\n", @@ -1830,7 +1834,7 @@ pub(crate) fn pin_pocket(pocket_suite: &str, ctx: &Arc) -> Result<(), B pub(crate) fn install_injected_packages( packages: &[String], env: &HashMap, - ctx: Arc, + ctx: Arc, view: &dyn BuildView, sink: &Option>, timings: &mut session::BuildTimings, @@ -1850,7 +1854,16 @@ pub(crate) fn install_injected_packages( if pkg.ends_with(".deb") && pkg_path.exists() { // Copy the .deb file into the build context let dest_root = ctx.create_temp_dir()?; - let chroot_path = ctx.ensure_available(pkg_path, &dest_root)?; + let chroot_path = + Path::new(&dest_root).join(pkg_path.file_name().unwrap_or(pkg_path.as_os_str())); + ctx.stage_tree( + pkg_path, + &chroot_path, + &StageOptions { + reuse: None, + prune_vcs: true, + }, + )?; log::debug!( "Copied .deb file '{}' to chroot path '{}'", pkg, @@ -1894,7 +1907,7 @@ fn dose3_explain_dependencies( arch: &str, upload_dir: &str, cross: bool, - ctx: Arc, + ctx: Arc, ) -> Result<(), Box> { // Construct the list of Packages files let mut bg_args = Vec::new(); @@ -1948,7 +1961,7 @@ fn dose3_explain_dependencies( #[cfg(test)] mod tests { use super::*; - use crate::context::ContextConfig; + use crate::context::{Context, ContextConfig}; fn cand(arch: &str, ma: &str) -> Candidate { Candidate { @@ -2266,7 +2279,7 @@ mod tests { /// declaration is not. #[test] fn detector_on_a_real_tree_through_the_context() { - let ctx = Context::new(ContextConfig::Local).unwrap(); + let ctx: Arc = Arc::new(Context::new(ContextConfig::Local).unwrap()); let dir = tempfile::tempdir().unwrap(); let tree = dir.path().join("pkg"); @@ -2293,7 +2306,7 @@ mod tests { /// application entirely and succeed. #[test] fn apply_phase_skips_single_debian_patch_trees() { - let ctx = Arc::new(Context::new(ContextConfig::Local).unwrap()); + let ctx: Arc = Arc::new(Context::new(ContextConfig::Local).unwrap()); // Dashed spelling through debian/source/options this time. let dir = tempfile::tempdir().unwrap(); diff --git a/src/deb/mod.rs b/src/deb/mod.rs index a68fd64..dbd5dbf 100644 --- a/src/deb/mod.rs +++ b/src/deb/mod.rs @@ -13,6 +13,7 @@ use crate::logfmt::{ MmdebstrapClassifier, QuiltClassifier, }; use crate::report::{BuildTarget, BuildView, TargetKind}; +use crate::sandbox::{PutOutcome, ReuseState, Sandbox, SandboxExt, StageOptions}; use std::error::Error; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -602,7 +603,7 @@ async fn build_binary_package_impl( // never from the process-global, which concurrent builds may have // re-pointed at their own chroot); otherwise the base context is used // directly. - let build_ctx = match guard.as_ref() { + let build_ctx: Arc = match guard.as_ref() { Some(g) => g.context(), None => base_ctx.clone(), }; @@ -653,7 +654,12 @@ async fn build_binary_package_impl( } } } - let staged_path = if let Some(s) = &session { + let tree_name = host_tree + .file_name() + .map(PathBuf::from) + .unwrap_or_else(|| host_tree.clone()); + let staged_path = Path::new(&build_root).join(tree_name); + if let Some(s) = &session { // Re-mount the session's persistent upperdir over the host // tree. If overlay staging is unavailable (no overlayfs, mount // failure, non-overlay driver), wipe the staged tree and @@ -661,13 +667,16 @@ async fn build_binary_package_impl( // tree would merge stale build artifacts and resurrect // host-deleted files into the build. Still environment- // resumable, just not artifact-resumable. - let staging = match build_ctx.ensure_available_with_overlay( - &host_tree, - &build_root, - &s.upper_dir(), - &s.work_dir(), - ) { - Ok(staging) => staging, + let opts = StageOptions { + reuse: Some(ReuseState { + upper: s.upper_dir(), + work: s.work_dir(), + }), + prune_vcs: true, + }; + match build_ctx.stage_tree(&host_tree, &staged_path, &opts) { + Ok(PutOutcome::Resumed) => {} + Ok(PutOutcome::Fresh) => build_resume = false, Err(e) => { log::info!( "Overlay staging unavailable ({}): the staged tree is \ @@ -675,23 +684,24 @@ async fn build_binary_package_impl( e ); s.wipe_staged_tree()?; - let path = build_ctx.ensure_available(&host_tree, &build_root)?; + let opts = StageOptions { + reuse: None, + prune_vcs: true, + }; + build_ctx.stage_tree(&host_tree, &staged_path, &opts)?; build_resume = false; - crate::context::OverlayStaging { - path, - overlay: false, - } } - }; - if !staging.overlay { - // Copy fallback: the staged tree is fresh, there is nothing - // incremental to build on. - build_resume = false; } - staging.path } else { - build_ctx.ensure_available(&host_tree, &build_root)? - }; + build_ctx.stage_tree( + &host_tree, + &staged_path, + &StageOptions { + reuse: None, + prune_vcs: true, + }, + )?; + } // The staged tree (build root + tree name) is where the build // steps and the artifact collection work. let build_root = staged_path.to_string_lossy().into_owned(); @@ -760,7 +770,7 @@ async fn build_binary_package_impl( for (idx, remote_file) in remote_files.iter().enumerate() { let file_name = remote_file.file_name().ok_or("Invalid remote filename")?; let local_dest = parent_dir.join(file_name); - build_ctx.retrieve_path(remote_file, &local_dest)?; + build_ctx.get(remote_file, &local_dest)?; artifacts.push(local_dest); view.progress("Retrieving artifacts", idx + 1, total_debs); @@ -998,7 +1008,7 @@ pub(crate) fn resolve_package_directory( package: &str, version: &str, series: &str, - ctx: &context::Context, + ctx: &Arc, ) -> Result> { if ctx.is_dir(build_root)? && ctx.exists(&build_root.join("debian"))? { log::debug!( @@ -1019,7 +1029,7 @@ pub(crate) fn find_package_directory( package: &str, version: &str, series: &str, - ctx: &context::Context, + ctx: &Arc, ) -> Result> { // Check quirks first for custom package directories let custom_dirs = crate::quirks::get_package_directories(package, series); @@ -1128,7 +1138,7 @@ fn find_dsc_file( build_root: &str, package: &str, version: &str, - ctx: &Arc, + ctx: &Arc, ) -> Result> { // Strip epoch from version (e.g., "1:2.3.4-5" -> "2.3.4-5") let version_without_epoch = version.split_once(':').map(|(_, v)| v).unwrap_or(version); @@ -1269,15 +1279,15 @@ mod tests { /// context like the ephemeral build contexts are: exists/list_files/ /// is_dir answer through the path mapping, no namespace privileges /// needed. - fn unshare_test_context(chroot_root: &Path) -> Context { + fn unshare_test_context(chroot_root: &Path) -> Arc { let base = Context::new(crate::context::ContextConfig::Local).unwrap(); - Context::with_parent( + Arc::new(Context::with_parent( crate::context::ContextConfig::Unshare { path: chroot_root.to_string_lossy().to_string(), parent: None, }, Arc::new(base), - ) + )) } /// The staging-area listing must classify entries through the context: @@ -1400,6 +1410,7 @@ mod tests { // Create a fresh local context for this test let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap()); + let ctx_sandbox: Arc = ctx.clone(); // Change directory to the package directory let cwd = crate::deb::find_package_directory( @@ -1407,7 +1418,7 @@ mod tests { package, &package_info.stanza.version, series, - &ctx, + &ctx_sandbox, ) .expect("Cannot find package directory"); log::debug!("Package directory: {}", cwd.display()); diff --git a/src/sandbox/host.rs b/src/sandbox/host.rs index 355800a..a12390e 100644 --- a/src/sandbox/host.rs +++ b/src/sandbox/host.rs @@ -118,6 +118,10 @@ impl Sandbox for Host { .map(|path| path.to_string_lossy().into_owned()) } + fn is_host(&self) -> bool { + true + } + fn cleanup(&self, _outcome: Option) -> io::Result<()> { Ok(()) } diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index d7fe9c1..ebd5601 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -56,6 +56,14 @@ pub trait Sandbox: Send + Sync { /// Create a fresh temporary directory inside the environment. fn create_temp_dir(&self) -> io::Result; + /// Whether this sandbox is the host machine. + /// + /// Host-only checks use it, for example the keyring cache ownership + /// guard. Defaults to `false`. + fn is_host(&self) -> bool { + false + } + /// Release mounts, devices or guest state and apply the teardown policy. /// /// Idempotent. `outcome` is `None` when the owner did not report one. @@ -100,11 +108,20 @@ pub struct Execution { pub stderr: Vec, } +/// Persistent overlay state a backend can reuse for a resumable copy. +#[derive(Debug, Clone, Default)] +pub struct ReuseState { + /// Overlay upper directory. + pub upper: PathBuf, + /// Overlay work directory. + pub work: PathBuf, +} + /// 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, + pub reuse: Option, /// Directory names to skip at any depth. pub skip_dirs: Vec, } diff --git a/src/sandbox/staging.rs b/src/sandbox/staging.rs index a0b685d..f86f1fa 100644 --- a/src/sandbox/staging.rs +++ b/src/sandbox/staging.rs @@ -2,15 +2,15 @@ use std::ffi::{OsStr, OsString}; use std::io; -use std::path::{Path, PathBuf}; +use std::path::Path; -use super::{PutOptions, PutOutcome, Sandbox}; +use super::{PutOptions, PutOutcome, ReuseState, Sandbox}; /// Policy for [`stage_tree`]. #[derive(Debug, Clone, Default)] pub struct StageOptions { /// Backend state to reuse for a resumable tree copy. - pub reuse: Option, + pub reuse: Option, /// Remove VCS metadata from the staged tree. pub prune_vcs: bool, } @@ -62,6 +62,9 @@ fn vcs_dir_names() -> Vec { /// Recursively remove version-control metadata directories below `root`. pub(crate) fn prune_vcs_dirs(sandbox: &dyn Sandbox, root: &Path) -> io::Result<()> { + if !sandbox.is_dir(root)? { + return Ok(()); + } let mut pending = vec![root.to_path_buf()]; while let Some(dir) = pending.pop() { for entry in sandbox.list_files(&dir)? { diff --git a/src/test/bed.rs b/src/test/bed.rs index 02bc109..67ce7a9 100644 --- a/src/test/bed.rs +++ b/src/test/bed.rs @@ -14,6 +14,7 @@ use crate::context::Context; use crate::deb::BuildProfiler; use crate::deb::ephemeral::EphemeralContextGuard; use crate::report::BuildView; +use crate::sandbox::Sandbox; use crate::test::options::TestMode; /// A prepared testbed, torn down on drop. @@ -57,10 +58,10 @@ impl Bed { } /// The context to run testbed commands in. - pub(crate) fn ctx(&self) -> Arc { + pub(crate) fn ctx(&self) -> Arc { match self { Bed::Chroot(guard) => guard.context(), - Bed::Local(ctx) => Arc::clone(ctx), + Bed::Local(ctx) => ctx.clone(), } } diff --git a/src/test/mod.rs b/src/test/mod.rs index dd1920e..e3d372f 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -32,6 +32,7 @@ use crate::debian::tests_control::TestsControl; use crate::exec::{LineSink, Stream}; use crate::logfmt::GenericClassifier; use crate::report::{BuildTarget, BuildView, TargetKind}; +use crate::sandbox::{Sandbox, SandboxExt, StageOptions}; use crate::test::bed::Bed; use crate::test::outcome::Verdict; @@ -191,11 +192,28 @@ pub async fn run(opts: TestOptions<'_>) -> Result bool { /// the archive sources (the same rules as the deb build), an optional /// upgrade, the caller's setup commands and injected packages. async fn configure_testbed( - ctx: &Arc, + ctx: &Arc, env: &HashMap, series: &str, arch: &str, diff --git a/src/test/runner.rs b/src/test/runner.rs index 524fa8b..bd2c3f4 100644 --- a/src/test/runner.rs +++ b/src/test/runner.rs @@ -16,11 +16,12 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; -use crate::context::{Context, LineSink, Stream}; use crate::debian::control::ControlInfo; use crate::debian::tests_control::Test; +use crate::exec::{LineSink, Stream}; use crate::logfmt::GenericClassifier; use crate::report::BuildView; +use crate::sandbox::{Sandbox, SandboxExt}; use crate::test::expand::expand_depends; use crate::test::outcome::{TestOutcome, Verdict}; @@ -30,7 +31,7 @@ const KILL_AFTER_SECS: u64 = 15; /// Everything one test run needs from the orchestration. pub(crate) struct RunContext<'a> { /// The testbed context. - pub ctx: Arc, + pub ctx: Arc, /// Context-side path of the staged source tree. pub tree: String, /// Context-side scratch root (temporary directories, artifacts). @@ -364,7 +365,7 @@ fn retrieve_artifacts(run: &RunContext<'_>, test_name: &str) { } let host = host_artifacts_dir(run, test_name); let _ = fs::create_dir_all(&host); - let _ = run.ctx.retrieve_path(&remote, &host); + let _ = run.ctx.get(&remote, &host); } /// The host-side artifacts directory of one test.