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

+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();