From 7c689e8c399ca84a13e8f608d136a072b118d8b9 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Tue, 24 Nov 2026 14:35:58 +0100 Subject: [PATCH] deb,test: drop explicit context selection DebBuildOptions no longer carries a Context or a BuildMode. Every build starts from a local base, resolves a record and bootstraps an Unshare. The testbed's local mode uses Host instead of the process-global context, and apt falls back to Host when no sandbox is passed. Remove the context swap from Unshare: callers now hold the sandbox they use, so no global current context is needed. --- src/apt/keyring.rs | 5 +- src/apt/sources.rs | 5 +- src/context/manager.rs | 2 +- src/deb/local.rs | 12 +- src/deb/mod.rs | 179 ++++++------------ src/deb/session.rs | 20 +- src/main.rs | 1 - src/prune.rs | 8 +- src/sandbox/mod.rs | 2 + .../ephemeral.rs => sandbox/unshare/mod.rs} | 129 +++++++------ src/test/bed.rs | 17 +- src/test/mod.rs | 5 +- 12 files changed, 177 insertions(+), 208 deletions(-) rename src/{deb/ephemeral.rs => sandbox/unshare/mod.rs} (95%) diff --git a/src/apt/keyring.rs b/src/apt/keyring.rs index 5f9c144..8c5219e 100644 --- a/src/apt/keyring.rs +++ b/src/apt/keyring.rs @@ -3,7 +3,6 @@ //! Provides functions to ensure that archive keyrings are available //! for mmdebstrap operations and for PPA packages by downloading them. -use crate::context; use crate::data::embed_data; use crate::distro_info; use crate::sandbox::{Sandbox, SandboxExt}; @@ -63,7 +62,7 @@ pub async fn download_cache_keyrings( ) -> Result> { let ctx: Arc = match ctx { Some(ctx) => ctx, - None => context::current(), + None => Arc::new(crate::sandbox::Host::new()), }; // Obtain keyring URLs from distro_info @@ -252,7 +251,7 @@ pub async fn download_trust_ppa_key( ) -> Result<(), Box> { let ctx: Arc = match ctx { Some(ctx) => ctx, - None => context::current(), + None => Arc::new(crate::sandbox::Host::new()), }; // Create trusted.gpg.d directory if it doesn't exist diff --git a/src/apt/sources.rs b/src/apt/sources.rs index ff8cc65..3c3e550 100644 --- a/src/apt/sources.rs +++ b/src/apt/sources.rs @@ -5,7 +5,6 @@ //! 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; use crate::debian::control::{Paragraph, parse_paragraphs, write_paragraph}; use crate::sandbox::Sandbox; use std::error::Error; @@ -337,7 +336,7 @@ pub fn load(ctx: Option>) -> Result, Box = match ctx { Some(ctx) => ctx, - None => context::current(), + None => Arc::new(crate::sandbox::Host::new()), }; // Try DEB822 format first (Ubuntu 24.04+ and Debian Trixie+) @@ -389,7 +388,7 @@ pub fn save( ) -> Result<(), Box> { let ctx: Arc = match ctx { Some(ctx) => ctx, - None => context::current(), + None => Arc::new(crate::sandbox::Host::new()), }; for (path, _format, content) in plan_writes(&sources) { diff --git a/src/context/manager.rs b/src/context/manager.rs index 13b20fa..b944d0d 100644 --- a/src/context/manager.rs +++ b/src/context/manager.rs @@ -267,7 +267,7 @@ impl ContextManager { /// /// Accepts either an owned [`Context`] or an already-shared /// `Arc`: callers that keep their own handle to the context - /// they install (e.g. [`crate::deb::ephemeral::EphemeralContextGuard`]) + /// they install (e.g. [`crate::sandbox::Unshare`]) /// pass the Arc so they can restore exactly this context afterwards /// instead of relying on whatever happens to be current at that time. pub fn set_current_ephemeral(&self, context: impl Into>) { diff --git a/src/deb/local.rs b/src/deb/local.rs index 035ef23..b2d6841 100644 --- a/src/deb/local.rs +++ b/src/deb/local.rs @@ -75,11 +75,11 @@ pub(crate) fn apply_ccache_env(env: &mut HashMap, enabled: bool, .unwrap_or_default(); env.insert( "PATH".to_string(), - format!("{}:{path}", crate::deb::ephemeral::CCACHE_SHIM_DIR), + format!("{}:{path}", crate::sandbox::unshare::CCACHE_SHIM_DIR), ); env.insert( "CCACHE_DIR".to_string(), - crate::deb::ephemeral::CCACHE_MOUNT.to_string(), + crate::sandbox::unshare::CCACHE_MOUNT.to_string(), ); env.insert("CCACHE_COMPILERCHECK".to_string(), "content".to_string()); env.insert("CCACHE_MAXSIZE".to_string(), maxsize.to_string()); @@ -347,7 +347,7 @@ pub(crate) fn migrate_upper_ownership(session: &session::Session) -> Result<(), let owner = format!("{}:{}", unsafe { libc::geteuid() }, unsafe { libc::getegid() }); - let status = crate::deb::ephemeral::privileged_command("chown", is_root) + let status = crate::sandbox::unshare::privileged_command("chown", is_root) .arg("-R") .arg(owner) .arg(&upper) @@ -382,7 +382,7 @@ fn migrate_ccache_ownership(ccache_host_dir: &Path) { let owner = format!("{}:{}", unsafe { libc::geteuid() }, unsafe { libc::getegid() }); - let status = crate::deb::ephemeral::privileged_command("chown", is_root) + let status = crate::sandbox::unshare::privileged_command("chown", is_root) .arg("-R") .arg(owner) .arg(ccache_host_dir) @@ -2007,12 +2007,12 @@ mod tests { assert_eq!( env.get("PATH").unwrap(), - &format!("{}:/usr/bin:/bin", crate::deb::ephemeral::CCACHE_SHIM_DIR), + &format!("{}:/usr/bin:/bin", crate::sandbox::unshare::CCACHE_SHIM_DIR), "the shim must shadow the real compilers" ); assert_eq!( env.get("CCACHE_DIR").unwrap(), - crate::deb::ephemeral::CCACHE_MOUNT + crate::sandbox::unshare::CCACHE_MOUNT ); assert_eq!( env.get("CCACHE_COMPILERCHECK").unwrap(), diff --git a/src/deb/mod.rs b/src/deb/mod.rs index dbd5dbf..6779599 100644 --- a/src/deb/mod.rs +++ b/src/deb/mod.rs @@ -1,30 +1,20 @@ mod cross; -/// Ephemeral (per-build) unshare contexts, including the process-global -/// cleanup-hook registry drained by the SIGINT handler -pub(crate) mod ephemeral; pub(crate) mod local; /// Resumable build sessions: manifest, discovery, `pkh deb list` and the /// host-tree snapshot/sync that keeps build artifacts alive across attempts pub mod session; -use crate::context::{self, Context}; +use crate::context::{Context, ContextConfig}; use crate::logfmt::{ AptInstallClassifier, AptUpdateClassifier, Classifier, GenericClassifier, MakeClassifier, MmdebstrapClassifier, QuiltClassifier, }; use crate::report::{BuildTarget, BuildView, TargetKind}; -use crate::sandbox::{PutOutcome, ReuseState, Sandbox, SandboxExt, StageOptions}; +use crate::sandbox::{PutOutcome, ReuseState, Sandbox, SandboxExt, StageOptions, Unshare}; use std::error::Error; use std::path::{Path, PathBuf}; use std::sync::Arc; -/// Build mode for the binary build -#[derive(PartialEq)] -pub enum BuildMode { - /// Local build, directly on the context - Local, -} - /// Phases of a binary build, announced to the [`BuildView`] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Phase { @@ -222,8 +212,6 @@ pub struct DebBuildOptions<'a> { /// Cross-compile for the target architecture instead of using /// qemu-binfmt. pub cross: bool, - /// Build mode; defaults to [`BuildMode::Local`]. - pub mode: Option, /// PPAs to add for build-dependencies (`user/ppa_name`). pub ppa: Vec, /// Packages to inject into the build environment before build-dep @@ -232,8 +220,6 @@ pub struct DebBuildOptions<'a> { /// Parallel build jobs; defaults to the core count available in the /// build context. pub jobs: Option, - /// Explicit build context; defaults to the current context. - pub ctx: Option>, /// Incremental request (`pkh deb --incremental []`): which /// record to fork as the base of this build's staged tree, and /// whether this build's own staged tree is retained. Defaults to a @@ -334,11 +320,9 @@ impl Default for DebBuildOptions<'_> { mirror: None, cwd: None, cross: false, - mode: None, ppa: Vec::new(), inject: Vec::new(), jobs: None, - ctx: None, incremental: Incremental::Off, ccache: true, view: &QUIET, @@ -379,11 +363,9 @@ async fn build_binary_package_impl( ref mirror, ref cwd, cross, - ref mode, ref ppa, ref inject, ref jobs, - ref ctx, ref incremental, ccache, view, @@ -457,21 +439,15 @@ async fn build_binary_package_impl( let current_arch = crate::get_current_arch(); let arch = arch.as_deref().unwrap_or(¤t_arch); - // Make sure we select a specific mode, either using user-requested - // or by using default for user-supplied parameters - let default_mode = BuildMode::Local; - let mode = mode.as_ref().unwrap_or(&default_mode); - - // Create an ephemeral unshare context for all Local builds - // Use qemu_binfmt when target architecture differs from host and cross is not requested - let chroot_arch = if mode == &BuildMode::Local && arch != current_arch && !cross { + // Every build starts from a local base and bootstraps an unshare + // chroot. Use qemu_binfmt when the target architecture differs from the + // host and cross is not requested. + let chroot_arch = if arch != current_arch && !cross { Some(arch) } else { None }; - - // Use provided context or get current - let base_ctx = ctx.clone().unwrap_or_else(context::current); + let base_ctx = Arc::new(Context::new(ContextConfig::Local)?); // Identify the target in the live view once the changelog is parsed, so // even the chroot download output is attributed and tee'd @@ -488,13 +464,9 @@ async fn build_binary_package_impl( // this scope so it outlives the guarded section below and is only dropped // once the live view has been cleared. // - // Build records are a local-only feature: with a local base context - // every build runs in its own record under the sessions directory + // Every build runs in its own record under the sessions directory // (forked from a previous one with `--incremental`, thrown away - // otherwise); every other base context keeps the historical anonymous - // temp chroot. - let session_enabled = *mode == BuildMode::Local - && matches!(base_ctx.config, crate::context::ContextConfig::Local); + // otherwise). let host_tree = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf()); let identity = session::SessionIdentity { package: package.clone(), @@ -503,29 +475,21 @@ async fn build_binary_package_impl( cross, }; - let mut keep_upper = false; - let session = if session_enabled { - match resolve_record( - incremental, - &host_tree, - &identity, - &version, - series, - chroot_arch, - mirror.as_deref(), - view, - ) { - Ok((record, keep)) => { - keep_upper = keep; - Some(record) - } - Err(e) => { - view.finish_failure(); - return Err(e); - } + let (session, keep_upper) = match resolve_record( + incremental, + &host_tree, + &identity, + &version, + series, + chroot_arch, + mirror.as_deref(), + view, + ) { + Ok((record, keep)) => (Some(record), keep), + Err(e) => { + view.finish_failure(); + return Err(e); } - } else { - None }; // Tee every captured build line into the record's log: the wrapper @@ -561,15 +525,15 @@ async fn build_binary_package_impl( }; // The shared ccache of this target — skipped with --no-ccache. - let ccache_dir = (session_enabled && ccache).then(|| session::ccache_dir(&identity)); + let ccache_dir = ccache.then(|| session::ccache_dir(&identity)); let mirror_arg = mirror.as_deref(); // The per-phase wall-clock profile of this run: fed by every // enter_phase call from the chroot bootstrap to the artifact // retrieval, recorded on the record at the end of the run. let mut profiler = BuildProfiler::new(); let mut guard = if let Some(s) = session.clone() { - Some( - ephemeral::EphemeralContextGuard::new_for_session( + Some(Arc::new( + Unshare::new_for_session( s, series, chroot_arch, @@ -581,10 +545,10 @@ async fn build_binary_package_impl( &mut profiler, ) .await?, - ) - } else if *mode == BuildMode::Local { - Some( - ephemeral::EphemeralContextGuard::new_with_context( + )) + } else { + Some(Arc::new( + Unshare::new_with_context( series, chroot_arch, mirror_arg, @@ -593,9 +557,7 @@ async fn build_binary_package_impl( &mut profiler, ) .await?, - ) - } else { - None + )) }; // Determine the build context explicitly: for Local builds it is the @@ -604,7 +566,7 @@ async fn build_binary_package_impl( // re-pointed at their own chroot); otherwise the base context is used // directly. let build_ctx: Arc = match guard.as_ref() { - Some(g) => g.context(), + Some(g) => Arc::clone(g) as Arc, None => base_ctx.clone(), }; @@ -614,7 +576,7 @@ async fn build_binary_package_impl( let result = async { // Prepare build directory: the stable /tmp/pkh-build for session - // builds (see EphemeralContextGuard::build_root — the overlay + // builds (see Unshare::build_root — the overlay // upperdir mirrors paths relative to the merge point), a fresh // timestamped temp dir otherwise. let build_root = match guard.as_ref() { @@ -723,38 +685,33 @@ async fn build_binary_package_impl( &build_ctx, )?; - // Run the build using target build mode. It returns the exact set of - // artifacts produced by this build (binary packages registered in - // debian/files plus the generated .buildinfo/.changes), as paths - // inside the build context. - let remote_files: Vec = match mode { - BuildMode::Local => { - local::build( - &package, - &version, - arch, - series, - pocket.as_deref(), - mirror.as_deref(), - &package_dir, - cross, - ppa, - inject, - build_ctx.clone(), - view, - *jobs, - session.as_ref(), - build_resume, - ccache, - // Rootless builds: only a context pkh controls (the - // ephemeral chroot) can carry the on-demand build user. - guard.is_some().then_some(local::BUILD_USER), - &mut timings, - &mut profiler, - ) - .await? - } - }; + // Run the build. It returns the exact set of artifacts produced by + // this build (binary packages registered in debian/files plus the + // generated .buildinfo/.changes), as paths inside the sandbox. + let remote_files: Vec = local::build( + &package, + &version, + arch, + series, + pocket.as_deref(), + mirror.as_deref(), + &package_dir, + cross, + ppa, + inject, + build_ctx.clone(), + view, + *jobs, + session.as_ref(), + build_resume, + ccache, + // Rootless builds: only a context pkh controls (the + // ephemeral chroot) can carry the on-demand build user. + Some(local::BUILD_USER), + &mut timings, + &mut profiler, + ) + .await?; // Retrieve the produced artifacts (binary packages plus the upload // metadata) to the parent directory: the .debs land next to the @@ -1408,9 +1365,9 @@ mod tests { .expect("Cannot pull package"); log::info!("Successfully pulled package {}", package); - // 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(); + // Resolve the package directory through a local sandbox. + let ctx_sandbox: Arc = + Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap()); // Change directory to the package directory let cwd = crate::deb::find_package_directory( @@ -1429,7 +1386,6 @@ mod tests { series: Some(series.to_string()), cross, cwd: Some(cwd.to_path_buf()), - ctx: Some(ctx), ..Default::default() }) .await @@ -1633,14 +1589,11 @@ mod tests { let temp_dir = tempfile::tempdir().unwrap(); let pkg_dir = create_indep_cross_test_source(temp_dir.path()); - let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap()); - crate::deb::build_binary_package(DebBuildOptions { arch: Some("arm64".to_string()), series: Some("noble".to_string()), cwd: Some(pkg_dir), cross: true, - ctx: Some(ctx), ..Default::default() }) .await @@ -1718,14 +1671,11 @@ mod tests { std::fs::write(pkg_dir.join("debian/source/format"), "3.0 (native)\n").unwrap(); - let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap()); - let err = crate::deb::build_binary_package(DebBuildOptions { arch: Some("arm64".to_string()), series: Some("noble".to_string()), cwd: Some(pkg_dir), cross: true, - ctx: Some(ctx), ..Default::default() }) .await @@ -1789,12 +1739,9 @@ mod tests { std::fs::write(pkg_dir.join("debian/source/format"), "3.0 (native)\n").unwrap(); - let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap()); - crate::deb::build_binary_package(DebBuildOptions { series: Some("noble".to_string()), cwd: Some(pkg_dir), - ctx: Some(ctx), ..Default::default() }) .await diff --git a/src/deb/session.rs b/src/deb/session.rs index 5feaf4e..60c7432 100644 --- a/src/deb/session.rs +++ b/src/deb/session.rs @@ -541,7 +541,7 @@ impl Session { /// claim about the tree (`kept_upper`). fn wipe_upper(&self) { for path in [self.upper_dir(), self.work_dir(), self.snapshot_file()] { - if let Err(e) = crate::deb::ephemeral::privileged_remove(&path) + if let Err(e) = crate::sandbox::unshare::privileged_remove(&path) && e.kind() != io::ErrorKind::NotFound { log::warn!("Failed to remove '{}': {}", path.display(), e); @@ -613,7 +613,7 @@ impl Session { pub(crate) fn remove_run_state(&self) { for path in [self.chroot_path(), self.work_dir()] { unmount_under(&path); - if let Err(e) = crate::deb::ephemeral::privileged_remove(&path) + if let Err(e) = crate::sandbox::unshare::privileged_remove(&path) && e.kind() != io::ErrorKind::NotFound { log::warn!( @@ -713,7 +713,7 @@ impl Session { /// would merge stale build artifacts and resurrect host-deleted files /// into the build. pub fn wipe_staged_tree(&self) -> io::Result<()> { - crate::deb::ephemeral::clear_dir(&self.chroot_path().join("tmp/pkh-build")) + crate::sandbox::unshare::clear_dir(&self.chroot_path().join("tmp/pkh-build")) } /// Remove the whole record tree (unmounting anything mounted under it @@ -1119,7 +1119,7 @@ fn copy_dir(src: &Path, dst: &Path) -> io::Result<()> { fs::create_dir_all(dst)?; let from = format!("{}/.", src.display()); let run = |privileged: bool| { - crate::deb::ephemeral::privileged_command("cp", privileged || is_root) + crate::sandbox::unshare::privileged_command("cp", privileged || is_root) .arg("-a") .arg("--reflink=auto") .arg(&from) @@ -1359,11 +1359,11 @@ pub(crate) fn sweep_identity_run_state(root: &Path, identity: &SessionIdentity) /// used before removing per-run state and record roots. pub(crate) fn unmount_under(path: &Path) { let is_root = crate::utils::root::is_root().unwrap_or(false); - for mount in crate::deb::ephemeral::host_mounts_under(path) + for mount in crate::sandbox::unshare::host_mounts_under(path) .into_iter() .rev() { - if !crate::deb::ephemeral::unmount_path(&mount, is_root) { + if !crate::sandbox::unshare::unmount_path(&mount, is_root) { log::warn!( "Failed to unmount {} under {}", mount.display(), @@ -1409,14 +1409,14 @@ pub(crate) fn lock_is_held(path: &Path) -> io::Result { /// extract, empty when the cache does not hold one yet (the bootstrap /// downloads it during the run). This is the fork gate's reference /// against the sha recorded in a base's manifest. `mirror` keys the -/// cache (see [`crate::deb::ephemeral::chroot_tarball_path`]), so records +/// cache (see [`crate::sandbox::unshare::chroot_tarball_path`]), so records /// never fork across a mirror change. pub(crate) fn cache_tarball_sha256( series: &str, arch: Option<&str>, mirror: Option<&str>, ) -> String { - crate::deb::ephemeral::chroot_tarball_path(series, arch, mirror) + crate::sandbox::unshare::chroot_tarball_path(series, arch, mirror) .ok() .and_then(|path| sha256_file(&path).ok()) .unwrap_or_default() @@ -2234,7 +2234,7 @@ pub(crate) fn apply_upper_sync(upper_root: &Path, ops: &[UpperOp]) -> io::Result if !meta.is_dir() && !meta.is_file() { continue; } - crate::deb::ephemeral::privileged_remove(&path)?; + crate::sandbox::unshare::privileged_remove(&path)?; removed += 1; if *dir { let mut prefix = rel.clone(); @@ -2379,7 +2379,7 @@ pub(crate) mod record_fixtures { /// the chroot holds root-owned device nodes). pub(crate) fn remove_session_dir(root: &Path) -> io::Result<()> { unmount_under(root); - crate::deb::ephemeral::privileged_remove(root) + crate::sandbox::unshare::privileged_remove(root) } #[cfg(test)] diff --git a/src/main.rs b/src/main.rs index a1b247a..851c137 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1081,7 +1081,6 @@ fn main() { incremental, ccache: !sub_matches.get_flag("no-ccache"), view, - ..Default::default() }) .await }); diff --git a/src/prune.rs b/src/prune.rs index 128eaef..d49e7a3 100644 --- a/src/prune.rs +++ b/src/prune.rs @@ -20,7 +20,7 @@ //! newest successful staged trees per target are kept by `pkh deb`, //! two by default). //! - **Shared apt download caches** under `/var/tmp/pkh/apt-cache/` -//! (see [`crate::deb::ephemeral::apt_cache_dir`]): the default policy +//! (see [`crate::sandbox::unshare::apt_cache_dir`]): the default policy //! removes the ones untouched for longer than the retention window, //! `--all` removes them all; the `.debs` they hold are cheap to //! re-download. @@ -139,7 +139,7 @@ pub(crate) const KEEP_LOGS: usize = 10; /// Lockfiles younger than this are not pruned: a recently touched /// `.lock` may belong to a concurrent `pkh` run, whose chroot /// tarball download uses the lockfile's mere existence as a mutual-exclusion -/// signal (see `deb::ephemeral`). Deleting such a lockfile mid-download would +/// signal (see `sandbox::unshare`). Deleting such a lockfile mid-download would /// let two builds corrupt the shared tarball cache. Only lockfiles untouched /// for at least this long are considered stale. const LOCK_STALE_AFTER: Duration = Duration::from_secs(24 * 60 * 60); @@ -164,7 +164,7 @@ enum Artifact { /// A `pkh test` run directory (report artifacts). TestRun(PathBuf), /// A shared apt download cache of one target (see - /// [`crate::deb::ephemeral::apt_cache_dir`]). + /// [`crate::sandbox::unshare::apt_cache_dir`]). AptCache(PathBuf), /// An orphaned record lock file (`.lock` whose record /// root is gone). @@ -877,7 +877,7 @@ pub fn plan(options: PruneOptions) -> PrunePlan { cache.as_deref(), Some(&crate::deb::session::sessions_root()), Some(&crate::test::runs_root()), - Some(&PathBuf::from(crate::deb::ephemeral::APT_CACHE_ROOT)), + Some(&PathBuf::from(crate::sandbox::unshare::APT_CACHE_ROOT)), options, ) } diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index ebd5601..c8dcd7a 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -14,9 +14,11 @@ use crate::exec::LineSink; mod host; pub(crate) mod staging; +pub(crate) mod unshare; pub use host::Host; pub use staging::{StageOptions, stage_tree}; +pub use unshare::Unshare; /// A place a build runs: a command runner and a filesystem. pub trait Sandbox: Send + Sync { diff --git a/src/deb/ephemeral.rs b/src/sandbox/unshare/mod.rs similarity index 95% rename from src/deb/ephemeral.rs rename to src/sandbox/unshare/mod.rs index 9e31b6b..9514e4e 100644 --- a/src/deb/ephemeral.rs +++ b/src/sandbox/unshare/mod.rs @@ -3,6 +3,9 @@ use crate::deb::session::{self, Session}; use crate::deb::{BuildProfiler, Phase, enter_phase}; use crate::interrupt::CleanupHookGuard; use crate::report::BuildView; +use crate::sandbox::{ + BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcome, Sandbox, +}; use directories::ProjectDirs; use sha2::{Digest, Sha256}; use std::error::Error; @@ -11,6 +14,7 @@ use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use std::process::Command; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use tar::Archive; use xz2::read::XzDecoder; @@ -18,7 +22,7 @@ use xz2::read::XzDecoder; // Interrupt-time cleanup // // On Ctrl-C, the watchdog in `crate::interrupt` runs the hook registered in -// [`EphemeralContextGuard::new_with_context`] right before exiting — the +// [`Unshare::new_with_context`] right before exiting — the // interrupt sequence skips all destructors, which would otherwise leak the // freshly bootstrapped chroot under /tmp together with its bind-mounted // /proc and any overlayfs mounts. @@ -42,7 +46,7 @@ fn sigint_cleanup_chroot(chroot_path: &Path) { /// the build log always stay: every build leaves a metadata record, the /// interrupt included. /// -/// Unlike [`EphemeralContextGuard::drop`], this deliberately does NOT go +/// Unlike [`Unshare::drop`], this deliberately does NOT go /// through the context manager, the ephemeral context's driver (whose /// `cleanup()` unmounts the tracked overlays) or the base context's /// command builder: interrupt-time hooks must be self-contained, and @@ -473,24 +477,20 @@ fn unescape_mount_field(field: &str) -> String { /// An ephemeral unshare context guard that creates and manages a temporary chroot environment /// for building packages with unshare permissions. /// -/// In session mode ([`EphemeralContextGuard::new_for_session`]) the chroot +/// In session mode ([`Unshare::new_for_session`]) the chroot /// lives inside a [`Session`] record's `chroot/` directory — extracted /// fresh from the tarball cache on every run (nothing chroot-shaped is /// persisted) and removed at the end of the run. The record itself is /// always kept as metadata and log; its staged tree is retained exactly /// for `--incremental` runs (`keep_upper`). -pub struct EphemeralContextGuard { +pub struct Unshare { /// The ephemeral build context this guard created (an unshare context /// bound to the chroot, parented on the base context). Held explicitly so /// cleanup and the build itself never depend on the process-global /// "current" context, which concurrent builds swap for their own. ephemeral_ctx: Arc, - /// The context that was current (globally) when this guard was created, - /// restored on drop. Saving the handle instead of a config name is what - /// keeps concurrent builds from restoring over each other. - previous_context: Arc, chroot_path: PathBuf, - build_succeeded: bool, + build_succeeded: AtomicBool, base_ctx: Arc, /// Registration of the interrupt-time cleanup hook; deregistered when /// this guard drops, so the hook can never fire after the normal cleanup @@ -502,13 +502,13 @@ pub struct EphemeralContextGuard { keep_upper: bool, /// The host-side lock of the shared apt download cache, held while /// its bind mount is up (see - /// [`EphemeralContextGuard::share_apt_cache`]); released when the + /// [`Unshare::share_apt_cache`]); released when the /// guard drops, together with the mount. Held for its drop side /// effect alone, hence the underscore: it is never read. _apt_cache_lock: Option, } -impl EphemeralContextGuard { +impl Unshare { /// Create a new ephemeral unshare context with an explicit base context /// /// # Arguments @@ -518,7 +518,7 @@ impl EphemeralContextGuard { /// * `base_ctx` - The base context to use for creating the chroot /// * `profiler` - The per-phase build profile to feed (the chroot /// bootstrap's phases of the record's `pkh deb profile`) - pub async fn new_with_context( + pub(crate) async fn new_with_context( series: &str, arch: Option<&str>, mirror: Option<&str>, @@ -539,7 +539,7 @@ impl EphemeralContextGuard { /// caller) /// * `series` - The distribution series (e.g., "noble", "sid") /// * `arch` - Optional target architecture, as for - /// [`EphemeralContextGuard::new_with_context`] + /// [`Unshare::new_with_context`] /// * `base_ctx` - The base context to use for chroot work /// * `keep_upper` - Retain the record's staged tree after the build /// (`pkh deb --incremental`); a plain run's record keeps metadata @@ -550,7 +550,7 @@ impl EphemeralContextGuard { /// * `profiler` - The per-phase build profile to feed (the chroot /// bootstrap's phases of the record's `pkh deb profile`) #[allow(clippy::too_many_arguments)] - pub async fn new_for_session( + pub(crate) async fn new_for_session( session: Session, series: &str, arch: Option<&str>, @@ -587,12 +587,6 @@ impl EphemeralContextGuard { ccache_dir: Option<&Path>, profiler: &mut BuildProfiler, ) -> Result> { - // Save the globally-installed context so Drop can restore exactly - // this handle: concurrent builds install their own ephemeral - // overrides, so the only safe restoration value is the one observed - // before this guard swapped anything in. - let previous_context = context::current(); - // In session mode the chroot lives inside the record root, as // per-run scratch; otherwise it is a fresh temp dir. let chroot_path = match &session { @@ -703,13 +697,10 @@ impl EphemeralContextGuard { }, base_ctx.clone(), )); - context::manager().set_current_ephemeral(ephemeral_ctx.clone()); - Ok(Self { - previous_context, ephemeral_ctx, chroot_path, - build_succeeded: false, + build_succeeded: AtomicBool::new(false), base_ctx, cleanup_hook, session, @@ -718,16 +709,6 @@ impl EphemeralContextGuard { }) } - /// The ephemeral build context created by this guard - /// - /// Callers must take the context from here rather than from - /// [`crate::context::current()`]: the process-global is a shared swap - /// slot that another concurrent build may have re-pointed at its own - /// chroot, while this handle is guaranteed to be this guard's context. - pub fn context(&self) -> Arc { - Arc::clone(&self.ephemeral_ctx) - } - #[allow(clippy::too_many_arguments)] async fn download_and_extract_chroot( series: &str, @@ -832,7 +813,7 @@ impl EphemeralContextGuard { /// and the shared ccache for a fresh chroot: idempotent /// finalization, safe to run on every run. Returns the shared apt /// cache's lock, held while its mount is up (see - /// [`EphemeralContextGuard::share_apt_cache`]). + /// [`Unshare::share_apt_cache`]). fn finalize_chroot( series: &str, arch: Option<&str>, @@ -1203,8 +1184,8 @@ impl EphemeralContextGuard { } /// Mark the build as successful, which will trigger chroot cleanup on drop - pub fn mark_build_successful(&mut self) { - self.build_succeeded = true; + pub(crate) fn mark_build_successful(&self) { + self.build_succeeded.store(true, Ordering::Relaxed); } /// The staged build root inside the chroot: the stable @@ -1212,7 +1193,7 @@ impl EphemeralContextGuard { /// paths relative to the merge point, so the staged tree must live at /// the same in-chroot path on every attempt for the build artifacts to /// be reusable), a fresh timestamped temp dir otherwise. - pub fn build_root(&self) -> Result> { + pub(crate) fn build_root(&self) -> Result> { match &self.session { Some(s) => { std::fs::create_dir_all(s.chroot_path().join("tmp/pkh-build"))?; @@ -1223,7 +1204,53 @@ impl EphemeralContextGuard { } } -impl Drop for EphemeralContextGuard { +impl Sandbox for Unshare { + fn run(&self, cmd: &CommandSpec, capture: Capture) -> std::io::Result { + Sandbox::run(self.ephemeral_ctx.as_ref(), cmd, capture) + } + + fn read_file(&self, path: &Path) -> std::io::Result { + Sandbox::read_file(self.ephemeral_ctx.as_ref(), path) + } + + fn write_file(&self, path: &Path, content: &str) -> std::io::Result<()> { + Sandbox::write_file(self.ephemeral_ctx.as_ref(), path, content) + } + + fn exists(&self, path: &Path) -> std::io::Result { + Sandbox::exists(self.ephemeral_ctx.as_ref(), path) + } + + fn is_dir(&self, path: &Path) -> std::io::Result { + Sandbox::is_dir(self.ephemeral_ctx.as_ref(), path) + } + + fn list_files(&self, path: &Path) -> std::io::Result> { + Sandbox::list_files(self.ephemeral_ctx.as_ref(), path) + } + + fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> std::io::Result { + Sandbox::put(self.ephemeral_ctx.as_ref(), host, dest, opts) + } + + fn get(&self, src: &Path, dest: &Path) -> std::io::Result<()> { + Sandbox::get(self.ephemeral_ctx.as_ref(), src, dest) + } + + fn remove(&self, path: &Path) -> std::io::Result<()> { + Sandbox::remove(self.ephemeral_ctx.as_ref(), path) + } + + fn create_temp_dir(&self) -> std::io::Result { + Sandbox::create_temp_dir(self.ephemeral_ctx.as_ref()) + } + + fn cleanup(&self, outcome: Option) -> std::io::Result<()> { + Sandbox::cleanup(self.ephemeral_ctx.as_ref(), outcome) + } +} + +impl Drop for Unshare { fn drop(&mut self) { // On Ctrl+C the interrupt watchdog owns the chroot teardown through // the registered hook: duplicating it here would race the hook's @@ -1232,7 +1259,6 @@ impl Drop for EphemeralContextGuard { // must be leaked instead to keep it registered (if it was already // drained, forgetting is a harmless no-op). if crate::interrupt::interrupted() { - context::manager().set_current_ephemeral(self.previous_context.clone()); // The record keeps its metadata: record the aborted build // honestly before the hook tears the per-run state down — // failed, and kept_upper only if a staged tree exists. @@ -1265,14 +1291,6 @@ impl Drop for EphemeralContextGuard { log::warn!("Failed to clean up overlay mounts: {}", e); } - // Restore the context that was current when this guard was created, - // not whatever is globally current at drop time (another concurrent - // build's override may be installed there). This only swaps the - // in-memory handle: the persisted configuration still names the - // context selected by the user, as `set_current_ephemeral` never - // touches it. - context::manager().set_current_ephemeral(self.previous_context.clone()); - // Session mode: the record's per-run chroot comes down in every // case (nothing chroot-shaped is persisted — success, failure and // interrupt all end the run), then the record is retained: @@ -1292,12 +1310,15 @@ impl Drop for EphemeralContextGuard { }; session.remove_run_state(); - session.retain_upper(self.keep_upper, self.build_succeeded); + session.retain_upper( + self.keep_upper, + self.build_succeeded.load(Ordering::Relaxed), + ); return; } // Remove chroot directory only if build succeeded - if self.build_succeeded { + if self.build_succeeded.load(Ordering::Relaxed) { log::debug!( "Build succeeded, removing chroot directory: {}", self.chroot_path.display() @@ -1439,12 +1460,12 @@ mod chroot_cleanup_tests { let dir = tempfile::tempdir().unwrap(); let chroot = dir.path().join("chroot"); std::fs::create_dir_all(chroot.join("dev")).unwrap(); - for (name, _, _) in EphemeralContextGuard::DEVICE_NODES { + for (name, _, _) in Unshare::DEVICE_NODES { std::fs::write(chroot.join("dev").join(name), b"").unwrap(); } assert!( - !EphemeralContextGuard::device_nodes_ready(&chroot), + !Unshare::device_nodes_ready(&chroot), "regular files must not count as ready device nodes" ); } @@ -1456,12 +1477,12 @@ mod chroot_cleanup_tests { let dir = tempfile::tempdir().unwrap(); let chroot = dir.path().join("chroot"); std::fs::create_dir_all(chroot.join("dev")).unwrap(); - for (name, _, _) in EphemeralContextGuard::DEVICE_NODES { + for (name, _, _) in Unshare::DEVICE_NODES { std::os::unix::fs::symlink(format!("/dev/{name}"), chroot.join("dev").join(name)) .unwrap(); } - assert!(EphemeralContextGuard::device_nodes_ready(&chroot)); + assert!(Unshare::device_nodes_ready(&chroot)); } /// A real directory with no mounts under it is simply removed. Skipped diff --git a/src/test/bed.rs b/src/test/bed.rs index 67ce7a9..1ca45f4 100644 --- a/src/test/bed.rs +++ b/src/test/bed.rs @@ -2,7 +2,7 @@ //! //! A testbed is a [`Context`] plus its teardown. chroot mode reuses the //! `pkh deb` machinery wholesale (an ephemeral unshare context guarded by -//! [`crate::deb::ephemeral::EphemeralContextGuard`], bootstrapped from the +//! [`crate::sandbox::Unshare`], bootstrapped from the //! same cached mmdebstrap tarballs); local mode is the current context //! used directly. The testbed itself is disposable per run: autopkgtests //! may break it, and the next run starts from a clean bootstrap. @@ -12,17 +12,16 @@ use std::sync::Arc; use crate::context::Context; use crate::deb::BuildProfiler; -use crate::deb::ephemeral::EphemeralContextGuard; use crate::report::BuildView; -use crate::sandbox::Sandbox; +use crate::sandbox::{Host, Sandbox, SandboxExt, Unshare}; use crate::test::options::TestMode; /// A prepared testbed, torn down on drop. pub(crate) enum Bed { /// An ephemeral unshare chroot. - Chroot(EphemeralContextGuard), + Chroot(Arc), /// The current context, used directly. - Local(Arc), + Local(Arc), } impl Bed { @@ -40,7 +39,7 @@ impl Bed { // foreign-arch chroot, so the native case shares deb's // unsuffixed `-buildd.tar.xz` cache entry. let chroot_arch = (arch != crate::get_current_arch()).then(|| arch.to_string()); - let guard = EphemeralContextGuard::new_with_context( + let guard = Unshare::new_with_context( series, chroot_arch.as_deref(), None, @@ -49,9 +48,9 @@ impl Bed { &mut BuildProfiler::new(), ) .await?; - Ok(Bed::Chroot(guard)) + Ok(Bed::Chroot(Arc::new(guard))) } - TestMode::Local => Ok(Bed::Local(base_ctx)), + TestMode::Local => Ok(Bed::Local(Arc::new(Host::new()))), // The vm mode never builds a Bed: run_vm execs autopkgtest. TestMode::Vm => unreachable!("vm mode does not prepare a Bed"), } @@ -60,7 +59,7 @@ impl Bed { /// The context to run testbed commands in. pub(crate) fn ctx(&self) -> Arc { match self { - Bed::Chroot(guard) => guard.context(), + Bed::Chroot(guard) => Arc::clone(guard) as Arc, Bed::Local(ctx) => ctx.clone(), } } diff --git a/src/test/mod.rs b/src/test/mod.rs index e3d372f..31be4a1 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -164,7 +164,10 @@ pub async fn run(opts: TestOptions<'_>) -> Result) }); - let base_ctx = crate::context::current(); + let base_ctx = Arc::new( + crate::context::Context::new(crate::context::ContextConfig::Local) + .map_err(|e| format!("cannot create a local testbed context: {e}"))?, + ); let bed = Bed::prepare(mode, &series, &arch, base_ctx, view).await?; let ctx = bed.ctx();