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
//! 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<PathBuf, Box<dyn Error>> {
let ctx: Arc<dyn Sandbox> = 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<dyn Error>> {
let ctx: Arc<dyn Sandbox> = 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
+2 -3
View File
@@ -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<Arc<dyn Sandbox>>) -> Result<Vec<SourceEntry>, Box<dyn E
let mut sources = Vec::new();
let ctx: Arc<dyn Sandbox> = 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<dyn Error>> {
let ctx: Arc<dyn Sandbox> = match ctx {
Some(ctx) => ctx,
None => context::current(),
None => Arc::new(crate::sandbox::Host::new()),
};
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
/// `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
/// instead of relying on whatever happens to be current at that time.
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();
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(),
+63 -116
View File
@@ -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<BuildMode>,
/// PPAs to add for build-dependencies (`user/ppa_name`).
pub ppa: Vec<String>,
/// 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<usize>,
/// Explicit build context; defaults to the current context.
pub ctx: Option<Arc<Context>>,
/// Incremental request (`pkh deb --incremental [<id>]`): 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(&current_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<dyn Sandbox> = match guard.as_ref() {
Some(g) => g.context(),
Some(g) => Arc::clone(g) as Arc<dyn Sandbox>,
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<PathBuf> = 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<PathBuf> = 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<dyn Sandbox> = ctx.clone();
// Resolve the package directory through a local sandbox.
let ctx_sandbox: Arc<dyn Sandbox> =
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
+10 -10
View File
@@ -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<bool> {
/// 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)]
-1
View File
@@ -1081,7 +1081,6 @@ fn main() {
incremental,
ccache: !sub_matches.get_flag("no-ccache"),
view,
..Default::default()
})
.await
});
+4 -4
View File
@@ -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
/// `<tarball>.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 (`<record id>.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,
)
}
+2
View File
@@ -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 {
@@ -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<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,
build_succeeded: bool,
build_succeeded: AtomicBool,
base_ctx: Arc<Context>,
/// 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<fs::File>,
}
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<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
// 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<Context> {
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<String, Box<dyn Error>> {
pub(crate) fn build_root(&self) -> Result<String, Box<dyn Error>> {
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<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) {
// 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
+8 -9
View File
@@ -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<Unshare>),
/// The current context, used directly.
Local(Arc<Context>),
Local(Arc<dyn Sandbox>),
}
impl Bed {
@@ -40,7 +39,7 @@ impl Bed {
// foreign-arch chroot, so the native case shares deb's
// unsuffixed `<series>-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<dyn Sandbox> {
match self {
Bed::Chroot(guard) => guard.context(),
Bed::Chroot(guard) => Arc::clone(guard) as Arc<dyn Sandbox>,
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>)
});
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();