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