sandbox,deb,test: run builds through the Sandbox trait

Build and test code now takes Arc<dyn Sandbox>. Context implements the
trait as a bridge for the unshare driver, so the callers move in one
commit without rewriting the driver first.

Staging goes through stage_tree with explicit ReuseState upper and work
paths. The sources backup writes its copy explicitly, and is_host keeps
the keyring cache ownership check on the host only.
This commit is contained in:
vhaudiquet committed 2026-11-24 18:35:17 +01:00
1 parent f1a21e0923
commit 483e532baf
16 files changed
+362 -109

No files matched your search

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