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.
This commit is contained in:
vhaudiquet committed 2026-11-24 18:35:17 +01:00
1 parent 483e532baf
commit 7c689e8c39
12 files changed
+177 -208

No files matched your search

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