docs: describe the implemented sandbox architecture
CI / build (push) Successful in 1m40s
CI / test (push) Skipped
CI / publish (push) Skipped
CI / snap (push) Successful in 2m39s
CI / release (push) Skipped

Update the design doc to the shipped shape: the public API, the module
layout, the crate-private Unshare constructors and what the conformance
tests actually cover. Refresh the AGENTS.md scope list and the test
mode wording in the README and CLI.

Rename the last context-named helpers (new_with_base,
unshare_test_sandbox, RunEnv) and the comments that still described the
old abstraction.
This commit is contained in:
vhaudiquet committed 2026-11-24 18:35:17 +01:00
1 parent d5bf2ceeb3
commit 674b99b00b
17 files changed
+207 -214

No files matched your search

+3 -2
View File
@@ -46,8 +46,9 @@ Rules:
- `new` — package scaffolding (`src/new/`) - `new` — package scaffolding (`src/new/`)
- `lint` — tree linting (`src/lint/`) - `lint` — tree linting (`src/lint/`)
- `prune`, `package_info` — remaining subcommand modules - `prune`, `package_info` — remaining subcommand modules
- `context` — build contexts: local, ssh, chroot/schroot, unshare - `sandbox` — the build environment trait, host and unshare backends,
(`src/context/`) staging (`src/sandbox/`)
- `exec` — subprocess line capture and host process helpers (`src/exec.rs`)
- `interrupt` — Ctrl+C interception and interrupt-time cleanup - `interrupt` — Ctrl+C interception and interrupt-time cleanup
(`src/interrupt.rs`) (`src/interrupt.rs`)
- `debian` — Debian format primitives: control, versions, checksums, - `debian` — Debian format primitives: control, versions, checksums,
+78 -81
View File
@@ -1,6 +1,6 @@
# Replacing Context with the Sandbox trait # Replacing Context with the Sandbox trait
Status: design proposal, not implemented. Status: implemented. The public build and test APIs take `Arc<dyn Sandbox>`; `src/context/` is gone.
## Why the old abstraction was wrong ## Why the old abstraction was wrong
@@ -23,7 +23,7 @@ process-global. New code has to say which one it means.
A small trait with explicit construction and explicit passing fixes both. The A small trait with explicit construction and explicit passing fixes both. The
Ecrou microVM implementation can be added without touching build logic. Ecrou microVM implementation can be added without touching build logic.
## What exists today ## What the old design was
| Piece | Where | Used by | | Piece | Where | Used by |
| --- | --- | --- | | --- | --- | --- |
@@ -257,9 +257,8 @@ commit to an archive format.
Overlayfs is specific to the unshare backend, so the mechanism stays in Overlayfs is specific to the unshare backend, so the mechanism stays in
`Unshare::put`. The shared policy is `PutOptions`: `Unshare::put`. The shared policy is `PutOptions`:
- `reuse` names backend state to reuse. `Unshare` treats it as the directory - `reuse` carries the backend's persistent overlay upper and work paths
that holds a persistent upper and work layer. A backend without resume (`ReuseState`). A backend without resume ignores it and returns `Fresh`.
ignores it and returns `Fresh`.
- `skip_dirs` lists directory names the backend may omit during a copy. - `skip_dirs` lists directory names the backend may omit during a copy.
`stage_tree` fills it with the VCS names. `stage_tree` fills it with the VCS names.
- `PutOutcome::Resumed` tells the caller that the previous attempt's build - `PutOutcome::Resumed` tells the caller that the previous attempt's build
@@ -273,31 +272,41 @@ depends on host-side overlay upperdirs.
### Implementations ### Implementations
`Unshare` is what `EphemeralContextGuard` and the old unshare `Context` are today: `Unshare` is what `EphemeralContextGuard` and the old unshare `Context` were:
an ephemeral unshare chroot with the same tarball cache, device nodes, `/proc`, an ephemeral unshare chroot with the same tarball cache, device nodes, `/proc`,
apt cache and ccache mounts. Its spec holds what the current guard takes: apt cache and ccache mounts. The crate-private constructors take the values the
old guard took:
```rust ```rust
pub struct UnshareSpec { impl Unshare {
pub root: PathBuf, pub(crate) async fn new_with_base(
pub series: String, series: &str,
pub arch: Option<String>, arch: Option<&str>,
pub mirror: Option<String>, mirror: Option<&str>,
pub ccache: Option<PathBuf>, base: Arc<dyn Sandbox>,
pub share_apt_cache: bool, view: &dyn BuildView,
pub teardown: Teardown, profiler: &mut BuildProfiler,
} ) -> Result<Self, Box<dyn Error>>;
pub enum Teardown { pub(crate) async fn new_for_session(
/// Remove the root on success and on failure. session: Session,
Always, series: &str,
/// Remove the root on success, keep it after a failure for inspection. arch: Option<&str>,
KeepOnFailure, mirror: Option<&str>,
/// The owner removes the root; the sandbox only unmounts. base: Arc<dyn Sandbox>,
Owner, view: &dyn BuildView,
keep_upper: bool,
ccache: Option<&Path>,
profiler: &mut BuildProfiler,
) -> Result<Self, Box<dyn Error>>;
} }
``` ```
The teardown policy is the old one: a successful build removes an anonymous
chroot, a failed one leaves it for inspection, and a session record removes the
per-run chroot in every case while retaining its staged tree exactly for
`--incremental`.
An absolute environment path such as `/etc/apt/sources.list` maps to An absolute environment path such as `/etc/apt/sources.list` maps to
`root/etc/apt/sources.list` in the unshare backend. The implementation strips `root/etc/apt/sources.list` in the unshare backend. The implementation strips
the leading slash before joining, because `Path::join` replaces the base on an the leading slash before joining, because `Path::join` replaces the base on an
@@ -309,8 +318,7 @@ overlay for a tree when possible, or the upper and work layer under
`Host` is the host machine. It runs commands with `std::process::Command`, `Host` is the host machine. It runs commands with `std::process::Command`,
uses `std::fs`, and has no teardown. It serves `pkh test --mode local` and the uses `std::fs`, and has no teardown. It serves `pkh test --mode local` and the
unit tests that currently build a `Context::new(ContextConfig::Local)`. It is unit tests. It is not a user-selectable backend.
not a user-selectable backend.
`Ecrou` is the future microVM backend. It runs commands through a guest agent and `Ecrou` is the future microVM backend. It runs commands through a guest agent and
moves files over its channel. Its spec will name the kernel, initrd, root moves files over its channel. Its spec will name the kernel, initrd, root
@@ -321,11 +329,12 @@ conformance tests. It does not need changes in `deb/local`, `apt` or
### Construction and selection ### Construction and selection
Each implementation owns its constructor, because each needs different inputs. Each implementation owns its constructor, because each needs different inputs.
`Unshare::create` is async because it downloads and extracts a tarball. `Unshare::new_with_base` and `Unshare::new_for_session` are async because they
`Host::new` is trivial. `Ecrou::create` will be async. download and extract a tarball. `Host::new` is trivial. `Ecrou::create` will be
async.
`pkh deb` calls `Unshare::create` today. Adding the Ecrou backend means adding a `pkh deb` calls `Unshare::new_with_base` today. Adding the Ecrou backend means
small `Backend` value to `DebBuildOptions` and a CLI flag, then choosing the adding a small `Backend` value to `DebBuildOptions` and a CLI flag, then choosing the
constructor there. Everything downstream already takes `Arc<dyn Sandbox>`. constructor there. Everything downstream already takes `Arc<dyn Sandbox>`.
A closed `Backend` enum is enough for the CLI. Library callers that want to A closed `Backend` enum is enough for the CLI. Library callers that want to
@@ -333,9 +342,9 @@ supply an implementation `pkh` does not know need an injection point, for
example `DebBuildOptions.sandbox: Option<Arc<dyn Sandbox>>`. That is a new example `DebBuildOptions.sandbox: Option<Arc<dyn Sandbox>>`. That is a new
field with a new meaning, not the old config-resolved `ctx`. field with a new meaning, not the old config-resolved `ctx`.
`Unshare::create` stays crate-private while it takes a `&mut BuildProfiler`. The `Unshare` constructors stay crate-private while they take a
Publishing a constructor for downstream callers means making the profiler `&mut BuildProfiler` and a `Session`. Publishing a constructor for downstream
optional in the signature first. callers means making both optional in the signature first.
`pkh test` maps its modes to implementations: `local` to `Host`, `chroot` to `pkh test` maps its modes to implementations: `local` to `Host`, `chroot` to
`Unshare`, and a future microVM mode to `Ecrou`. The existing `TestMode::Vm` `Unshare`, and a future microVM mode to `Ecrou`. The existing `TestMode::Vm`
@@ -352,10 +361,9 @@ different flag name.
applies the conservative teardown policy. `Unshare` keeps a failed anonymous applies the conservative teardown policy. `Unshare` keeps a failed anonymous
chroot for inspection and removes it on success, as today. chroot for inspection and removes it on success, as today.
- `cleanup` takes `Option<BuildOutcome>` so it works through - `cleanup` takes `Option<BuildOutcome>` so it works through
`Arc<dyn Sandbox>`. `deb` calls `cleanup(Some(Success))` after a good build `Arc<dyn Sandbox>`. `deb` marks success on the `Unshare` before it drops;
and `cleanup(Some(Failure))` before returning an error; `Drop` and the `Drop` and the interrupt hook call `cleanup(None)`. `Unshare` stores the
interrupt hook call `cleanup(None)`. `Unshare` stores the outcome in an outcome in an `AtomicBool`.
`AtomicBool` and the first call applies the teardown.
- A build record keeps its metadata and log outside the environment. Dropping a - A build record keeps its metadata and log outside the environment. Dropping a
sandbox never touches them. Backend-owned state, such as `<record>/chroot`, sandbox never touches them. Backend-owned state, such as `<record>/chroot`,
belongs to the backend and is removed by `cleanup`. belongs to the backend and is removed by `cleanup`.
@@ -383,23 +391,22 @@ different flag name.
`Option` on the keyring helpers. Every caller passes a value today; the `Option` on the keyring helpers. Every caller passes a value today; the
`context::current()` default goes away. `context::current()` default goes away.
After the migration the word does not appear in the code. This document The build and test APIs no longer expose the word. This document mentions it
mentions it only to describe what is removed. No setting, global, driver or only to describe what was removed; no setting, global, driver or command
command builder keeps the name. builder keeps the name.
## Public API changes ## Public API changes
- `pkh::sandbox::{Sandbox, SandboxExt, BuildCommand, Capture, CommandSpec, - `pkh::sandbox::{Sandbox, SandboxExt, BuildCommand, Capture, CommandSpec,
Execution, PutOptions, PutOutcome, BuildOutcome, StageOptions, stage_tree}`. Execution, PutOptions, PutOutcome, BuildOutcome, StageOptions, stage_tree}`.
- `pkh::sandbox::{Unshare, UnshareSpec, Teardown}` and `Host`. - `pkh::sandbox::{Host, Unshare, ReuseState}`. The `Unshare` constructors are
crate-private until their profiler and session inputs become optional.
- `pkh::exec::{LineSink, Stream}`. `report::BuildView::sink` returns the moved - `pkh::exec::{LineSink, Stream}`. `report::BuildView::sink` returns the moved
`LineSink`. `LineSink`.
- `pkh::deb::DebBuildOptions` loses `ctx` and `mode`. A later `Backend` value is - `pkh::deb::DebBuildOptions` loses `ctx` and `mode`. A later `Backend` value is
additive. additive.
- `pkh::apt::sources::{load, save}` and - `pkh::apt::sources::{load, save}` and the keyring helpers take
`pkh::apt::keyring::download_trust_ppa_key` take `&dyn Sandbox`. `Option<Arc<dyn Sandbox>>`; `None` means a `Host` sandbox.
- `pkh::apt::keyring::download_cache_keyrings` becomes host-only. The bootstrap
always runs on the host now.
`pkh` is a library and a binary at version `0.2.0`. These are breaking changes, `pkh` is a library and a binary at version `0.2.0`. These are breaking changes,
so the release that ships them should be `0.3.0`. so the release that ships them should be `0.3.0`.
@@ -415,22 +422,19 @@ src/
staging.rs StageOptions, stage_tree, VCS pruning staging.rs StageOptions, stage_tree, VCS pruning
host.rs Host host.rs Host
unshare/ unshare/
mod.rs Unshare, UnshareSpec, Teardown, Drop mod.rs Unshare, bootstrap, finalize, ccache, apt cache,
bootstrap.rs tarball cache, download, extraction teardown
finalize.rs device nodes, /proc, apt cache, ccache shim namespace.rs UnshareDriver, path mapping, overlay staging,
overlay.rs overlay mounting, resume state namespace and pivot scripts, MAPPED_BUILD_ID
namespace.rs namespace and pivot scripts, MAPPED_BUILD_ID
ecrou.rs future Ecrou ecrou.rs future Ecrou
build_profile.rs Phase, BuildProfiler, moved out of deb
``` ```
`Phase` and `BuildProfiler` move out of `deb` because `Unshare::create` needs `Phase` and `BuildProfiler` still live in `deb`; moving them to
them and `sandbox` must not depend on `deb`. `pkh::deb::Phase` can be `build_profile.rs` is the remaining separation between `sandbox` and `deb`.
re-exported for compatibility.
## Migration plan ## Migration plan (implemented)
Each step compiles and passes its tests. The work is additive first, subtractive Each step compiled and passed its tests. The work is additive first, subtractive
last. last.
1. `exec: move line capture out of context` adds `src/exec.rs` with `Stream`, 1. `exec: move line capture out of context` adds `src/exec.rs` with `Stream`,
@@ -446,13 +450,13 @@ last.
`Arc<dyn Sandbox>`. The SSH and schroot drivers are not moved. `Arc<dyn Sandbox>`. The SSH and schroot drivers are not moved.
4. `sandbox: move the chroot bootstrap out of deb` moves the tarball, 4. `sandbox: move the chroot bootstrap out of deb` moves the tarball,
extraction, finalize, ccache, apt cache and teardown helpers from extraction, finalize, ccache, apt cache and teardown helpers from
`deb/ephemeral.rs`, and folds `EphemeralContextGuard` into `Unshare::create` `deb/ephemeral.rs`, and folds `EphemeralContextGuard` into
and `Drop`. `Unshare::new_with_base`/`new_for_session` and `Drop`.
5. `deb: drop the ctx and mode options` removes 5. `deb: drop the ctx and mode options` removes
`DebBuildOptions.ctx`, `DebBuildOptions.mode` and `BuildMode`, and passes the `DebBuildOptions.ctx`, `DebBuildOptions.mode` and `BuildMode`, and passes the
`Arc<dyn Sandbox>` explicitly through `deb/local`. `Arc<dyn Sandbox>` explicitly through `deb/local`.
6. `test: make local mode use Host` replaces `Bed::Local(Arc<Context>)` with 6. `test: make local mode use Host` replaces `Bed::Local(Arc<Context>)` with
`Bed::Host` and the trait methods. `Bed::Local(Arc<dyn Sandbox>)` backed by `Host`.
7. `apt,build: take the sandbox explicitly` removes the `Option` 7. `apt,build: take the sandbox explicitly` removes the `Option`
parameters and the `context::current()` defaults, and passes `Host` in the parameters and the `context::current()` defaults, and passes `Host` in the
unit tests. unit tests.
@@ -491,8 +495,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 required methods and one provided capability 3. Trait size. The trait has 10 required methods and two provided methods
method (`is_host`), and every backend implement the required ones. One trait keeps `Arc<dyn Sandbox>` simple. If it grows, split (`is_host`, `cleanup`); every backend implements 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
@@ -530,24 +534,17 @@ The commit scopes follow `AGENTS.md`: add `sandbox`, `build_profile` and
## Testing ## Testing
- Add a conformance suite that takes `&dyn Sandbox` and checks the - `sandbox::tests::conformance` takes `&dyn Sandbox` and checks the contract:
contract: run a command, capture its output, read and write a file, list a run a command, capture its output, read and write a file, list a directory,
directory, stage a tree, copy a file out, create a temporary directory, and stage a tree, copy a file out, create a temporary directory, and clean up.
clean up. Run it against `Host` always and against `Unshare` when root and It runs against `Host`.
`unshare` are available. - `sandbox::unshare::namespace::path_tests` runs the path and staging half
- A future `Ecrou` runs the same suite. That is the main reason to keep the trait against `UnshareDriver` over a temp root, without namespace privileges.
small and behavior explicit. - A bootstrapped `Unshare` needs root, `unshare` and a tarball download, so its
- Use `Arc<dyn Sandbox>` in a test to catch object-safety regressions. full command conformance is left to the `pkh deb` and `pkh test` e2e runs.
- Port the existing `context` unit tests: staging strips VCS metadata, copies - The existing staging units moved with the code: VCS metadata is skipped,
dangling symlinks, maps unshare paths, prunes nested VCS directories, and dangling symlinks round-trip, unshare paths map below the root, and overlay
stages over an overlay upperdir. mounts prune the lower tree.
- Delete the `ContextManager` tests with the manager. - `Host` stays fast and unprivileged, so `build/binary.rs`, `deb/local.rs` and
- Add lifecycle tests: create an `Unshare` over a pre-populated fake root, drop `apt/sources.rs` unit tests run without a chroot.
it, and check the root is kept or removed per `Teardown`. These do not need
privileges if they stop before `unshare`.
- Keep the `Host` implementation, so `build/binary.rs`, `deb/local.rs` and
`apt/sources.rs` unit tests stay fast and unprivileged.
- Run `pkh test --mode local` and `--mode chroot` in the e2e harness.
- Run the full suite and `cargo fmt --all` plus
`cargo clippy --all-targets --all-features` before each commit, as
`AGENTS.md` requires.
+5 -5
View File
@@ -95,10 +95,10 @@ pub async fn download_cache_keyrings(
// Upgrade cache directories created by versions that made them // Upgrade cache directories created by versions that made them
// private: mmdebstrap's unshare-mode hooks cannot read them. // private: mmdebstrap's unshare-mode hooks cannot read them.
} else { } else {
// Remote contexts (e.g. ssh) have no stat/metadata access through // Non-host sandboxes have no host-side stat access, so the
// the sandbox API, so the ownership guard cannot be performed; // ownership guard cannot be performed; keep the previous
// keep the previous best-effort behavior of tightening the // best-effort behavior of tightening the directory permissions
// directory permissions instead (no group/others write). // instead (no group/others write).
} }
ctx.command("chmod").arg("755").arg(&keyring_dir).status()?; ctx.command("chmod").arg("755").arg(&keyring_dir).status()?;
} else { } else {
@@ -270,7 +270,7 @@ pub async fn download_trust_ppa_key(
); );
// Get PPA information from the Launchpad API to get the signing key // Get PPA information from the Launchpad API to get the signing key
// fingerprint. The query is context-independent metadata, so it goes // fingerprint. The query is sandbox-independent metadata, so it goes
// through the shared HTTP client (timeouts, retries) rather than // through the shared HTTP client (timeouts, retries) rather than
// shelling out to curl. // shelling out to curl.
let api_url = crate::launchpad::archive_url(ppa_owner, ppa_name); let api_url = crate::launchpad::archive_url(ppa_owner, ppa_name);
+11 -11
View File
@@ -4,7 +4,7 @@
//! //!
//! All tree/database access goes through a [`Sandbox`] 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 sandbox
//! with coreutils (`md5sum`, `sha1sum`, `sha256sum`, `stat`), keeping the //! with coreutils (`md5sum`, `sha1sum`, `sha256sum`, `stat`), keeping the
//! flow binary-safe regardless of the transport. //! flow binary-safe regardless of the transport.
@@ -39,7 +39,7 @@ pub struct BinaryMetadataOptions {
/// precedence over whatever the host process inherited, so the metadata /// precedence over whatever the host process inherited, so the metadata
/// describes the environment the build actually ran in. /// describes the environment the build actually ran in.
pub exported_env: BTreeMap<String, String>, pub exported_env: BTreeMap<String, String>,
/// Build architecture (the machine inside the build context). /// Build architecture (the machine inside the build sandbox).
pub build_arch: String, pub build_arch: String,
/// Host architecture (the packages' target); equals the build /// Host architecture (the packages' target); equals the build
/// architecture except for cross builds. /// architecture except for cross builds.
@@ -49,7 +49,7 @@ pub struct BinaryMetadataOptions {
/// Generate `<pkg>_<ver>_<arch>.buildinfo` and `.changes` for a finished /// Generate `<pkg>_<ver>_<arch>.buildinfo` and `.changes` for a finished
/// binary build, consuming `debian/files` from `package_dir` and the /// binary build, consuming `debian/files` from `package_dir` and the
/// artifacts sitting in `upload_dir`. Returns both paths (inside the /// artifacts sitting in `upload_dir`. Returns both paths (inside the
/// context). /// sandbox).
/// ///
/// Mirrors the observable behavior of `dpkg-genbuildinfo -b` and /// Mirrors the observable behavior of `dpkg-genbuildinfo -b` and
/// `dpkg-genchanges -b`: sorted `Binary` list, encounter-order `Architecture` /// `dpkg-genchanges -b`: sorted `Binary` list, encounter-order `Architecture`
@@ -63,7 +63,7 @@ pub fn generate_binary_metadata(
opts: &BinaryMetadataOptions, opts: &BinaryMetadataOptions,
) -> Result<(PathBuf, PathBuf), Box<dyn Error>> { ) -> Result<(PathBuf, PathBuf), Box<dyn Error>> {
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Metadata sources inside the context // Metadata sources inside the sandbox
// ------------------------------------------------------------------ // ------------------------------------------------------------------
let changelog_content = ctx.read_file(&package_dir.join("debian/changelog"))?; let changelog_content = ctx.read_file(&package_dir.join("debian/changelog"))?;
let mut entries = let mut entries =
@@ -216,7 +216,7 @@ pub fn generate_binary_metadata(
descriptions.sort(); descriptions.sort();
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Installed-Build-Depends closure over the context status database // Installed-Build-Depends closure over the sandbox status database
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// Like the source-build path, a status database that cannot be read is // Like the source-build path, a status database that cannot be read is
// a hard error: silently treating it as empty would drop (or gut) the // a hard error: silently treating it as empty would drop (or gut) the
@@ -276,7 +276,7 @@ pub fn generate_binary_metadata(
)); ));
ctx.write_file(&package_dir.join("debian/files"), &files_list.render())?; ctx.write_file(&package_dir.join("debian/files"), &files_list.render())?;
// Hash the freshly written .buildinfo inside the context. // Hash the freshly written .buildinfo inside the sandbox.
let buildinfo_hashes = let buildinfo_hashes =
hashes_in_context(ctx, upload_dir, std::slice::from_ref(&buildinfo_name))?; hashes_in_context(ctx, upload_dir, std::slice::from_ref(&buildinfo_name))?;
if let Some(h) = buildinfo_hashes.get(&buildinfo_name) { if let Some(h) = buildinfo_hashes.get(&buildinfo_name) {
@@ -328,7 +328,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. /// sandbox directory `dir`, using coreutils.
fn hashes_in_context( fn hashes_in_context(
ctx: &Arc<dyn Sandbox>, ctx: &Arc<dyn Sandbox>,
dir: &Path, dir: &Path,
@@ -349,10 +349,10 @@ fn hashes_in_context(
.arg("%s %n") .arg("%s %n")
.args(names) .args(names)
.output() .output()
.map_err(|e| format!("failed to run 'stat' inside the build context: {e}"))?; .map_err(|e| format!("failed to run 'stat' inside the build sandbox: {e}"))?;
if !output.status.success() { if !output.status.success() {
return Err(format!( return Err(format!(
"'stat' failed inside the build context: {}", "'stat' failed inside the build sandbox: {}",
String::from_utf8_lossy(&output.stderr).trim() String::from_utf8_lossy(&output.stderr).trim()
) )
.into()); .into());
@@ -381,10 +381,10 @@ fn hashes_in_context(
.current_dir(dir) .current_dir(dir)
.args(names) .args(names)
.output() .output()
.map_err(|e| format!("failed to run '{tool}' inside the build context: {e}"))?; .map_err(|e| format!("failed to run '{tool}' inside the build sandbox: {e}"))?;
if !output.status.success() { if !output.status.success() {
return Err(format!( return Err(format!(
"'{tool}' failed inside the build context: {}", "'{tool}' failed inside the build sandbox: {}",
String::from_utf8_lossy(&output.stderr).trim() String::from_utf8_lossy(&output.stderr).trim()
) )
.into()); .into());
+34 -34
View File
@@ -3,7 +3,7 @@ use crate::exec::LineSink;
use crate::logfmt::QuiltClassifier; use crate::logfmt::QuiltClassifier;
use crate::report::BuildView; use crate::report::BuildView;
/// Local binary package building /// Local binary package building
/// Directly calling 'debian/rules' in current context /// Directly calling 'debian/rules' in host
use crate::sandbox::{BuildCommand, Sandbox, SandboxExt, StageOptions}; 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};
@@ -94,7 +94,7 @@ pub(crate) fn apply_ccache_env(env: &mut HashMap<String, String>, enabled: bool,
/// The unprivileged user the rules run as inside a pkh-managed chroot: /// The unprivileged user the rules run as inside a pkh-managed chroot:
/// Launchpad's buildds and sbuild compile as a non-root user, and packages /// Launchpad's buildds and sbuild compile as a non-root user, and packages
/// rely on it (coreutils' configure refuses to run as root). The user is /// rely on it (coreutils' configure refuses to run as root). The user is
/// created on demand in the build context; contexts pkh does not control /// created on demand in the build sandbox; sandboxes pkh does not control
/// (ssh, schroot) keep running the rules as their own user. /// (ssh, schroot) keep running the rules as their own user.
pub const BUILD_USER: &str = "pkh-build"; pub const BUILD_USER: &str = "pkh-build";
@@ -102,7 +102,7 @@ pub const BUILD_USER: &str = "pkh-build";
enum RulesIdentity { enum RulesIdentity {
/// A nested user namespace maps the chroot's root ownership onto /// A nested user namespace maps the chroot's root ownership onto
/// [`crate::sandbox::unshare::MAPPED_BUILD_ID`]: the whole staged tree — the /// [`crate::sandbox::unshare::MAPPED_BUILD_ID`]: the whole staged tree — the
/// chroot's files are the invoking user's host-side, and the context /// chroot's files are the invoking user's host-side, and the sandbox
/// namespace maps that user to uid 0 — shows as already owned by the /// namespace maps that user to uid 0 — shows as already owned by the
/// build identity, so nothing is chowned and no data moves. Files the /// build identity, so nothing is chowned and no data moves. Files the
/// build writes come out as the invoking user's own host-side. /// build writes come out as the invoking user's own host-side.
@@ -113,7 +113,7 @@ enum RulesIdentity {
Setpriv(String, String), Setpriv(String, String),
} }
/// Whether the build context can establish the nested build-identity /// Whether the build sandbox can establish the nested build-identity
/// namespace: kernel user namespaces reachable, a new enough util-linux /// namespace: kernel user namespaces reachable, a new enough util-linux
/// (`--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
@@ -141,14 +141,14 @@ fn probe_mapped_namespace(ctx: &Arc<dyn Sandbox>) -> Result<(), String> {
} }
} }
/// Ensure [`BUILD_USER`] exists in the build context and owns everything /// Ensure [`BUILD_USER`] exists in the build sandbox and owns everything
/// the rules must write: the staged tree (whose parent is where /// the rules must write: the staged tree (whose parent is where
/// dh_builddeb drops the .debs), the scratch HOME and the shared ccache /// dh_builddeb drops the .debs), the scratch HOME and the shared ccache
/// directory. Returns how the rules drop privileges. /// directory. Returns how the rules drop privileges.
/// ///
/// The mapped namespace is the ownership by construction: the chroot's /// The mapped namespace is the ownership by construction: the chroot's
/// files are the invoking user's host-side and the context maps that user /// files are the invoking user's host-side and the sandbox maps that user
/// to uid 0, so a namespace nested inside the context's, mapping uid 0 /// to uid 0, so a namespace nested inside the sandbox's, mapping uid 0
/// onto [`crate::sandbox::unshare::MAPPED_BUILD_ID`], makes the build identity the /// onto [`crate::sandbox::unshare::MAPPED_BUILD_ID`], makes the build identity the
/// owner of everything without moving a byte. The fallback creates an /// owner of everything without moving a byte. The fallback creates an
/// ordinary chroot user and hands the tree over with a chown — through /// ordinary chroot user and hands the tree over with a chown — through
@@ -167,7 +167,7 @@ fn ensure_build_user(
Err(reason) => { Err(reason) => {
log::info!( log::info!(
"Nested user namespaces are unavailable in the build \ "Nested user namespaces are unavailable in the build \
context ({reason}); falling back to the chown handover" sandbox ({reason}); falling back to the chown handover"
); );
false false
} }
@@ -442,7 +442,7 @@ fn hand_over(
Ok(()) Ok(())
} }
/// Create [`BUILD_USER`] in the build context (the setpriv fallback). /// Create [`BUILD_USER`] in the build sandbox (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<dyn Sandbox>) -> Result<(), Box<dyn Error>> { fn create_build_user(ctx: &Arc<dyn Sandbox>) -> Result<(), Box<dyn Error>> {
@@ -498,7 +498,7 @@ fn shlex_quote(value: &str) -> String {
/// drops to the build user without touching the environment (a login /// drops to the build user without touching the environment (a login
/// shell would reset it), so the dpkg architecture variables and /// shell would reset it), so the dpkg architecture variables and
/// 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 sandbox's own.
fn rules_command<'a>( fn rules_command<'a>(
ctx: &'a Arc<dyn Sandbox>, ctx: &'a Arc<dyn Sandbox>,
identity: Option<&RulesIdentity>, identity: Option<&RulesIdentity>,
@@ -542,7 +542,7 @@ pub async fn build(
build_resume: bool, build_resume: bool,
ccache: bool, ccache: bool,
// Some(&BUILD_USER) hands the rules to an unprivileged build user // Some(&BUILD_USER) hands the rules to an unprivileged build user
// (rootless builds); none runs them as the build context's own user. // (rootless builds); none runs them as the build sandbox's own user.
build_user: Option<&str>, build_user: Option<&str>,
// Accumulator of the measured dependency-installation and build // Accumulator of the measured dependency-installation and build
// durations; the caller records it on the build record. // durations; the caller records it on the build record.
@@ -563,7 +563,7 @@ pub async fn build(
apply_ccache_env(&mut env, ccache, &ccache_maxsize()); apply_ccache_env(&mut env, ccache, &ccache_maxsize());
// Parallel building: honor an explicit -j/--jobs count, otherwise detect // Parallel building: honor an explicit -j/--jobs count, otherwise detect
// the number of cores available inside the build context (nproc). // the number of cores available inside the build sandbox (nproc).
let num_cores = match jobs { let num_cores = match jobs {
Some(j) => j, Some(j) => j,
None => ctx None => ctx
@@ -588,7 +588,7 @@ pub async fn build(
format!("parallel={} nocheck", num_cores), format!("parallel={} nocheck", num_cores),
); );
// The build context inherits pkh's environment: without an override, // The build sandbox inherits pkh's environment: without an override,
// HOME is the invoking user's host path, which does not exist inside // HOME is the invoking user's host path, which does not exist inside
// the chroot - tools keying user config on it (texi2dvi's TeX live // the chroot - tools keying user config on it (texi2dvi's TeX live
// setup, anything writing dotfiles) then fail mid-build. sbuild points // setup, anything writing dotfiles) then fail mid-build. sbuild points
@@ -770,7 +770,7 @@ pub async fn build(
.status() .status()
.map_err(|e| { .map_err(|e| {
format!( format!(
"Failed to run 'apt-get update' inside the build context: {}. \ "Failed to run 'apt-get update' inside the build sandbox: {}. \
If this is a local build, make sure apt-get is available and \ If this is a local build, make sure apt-get is available and \
try executing with sudo.", try executing with sudo.",
e e
@@ -778,7 +778,7 @@ pub async fn build(
})?; })?;
timings.add_deps(started.elapsed()); timings.add_deps(started.elapsed());
if !status.success() { if !status.success() {
return Err("apt-get update failed inside the build context. \ return Err("apt-get update failed inside the build sandbox. \
If this is a local build, try executing with sudo, \ If this is a local build, try executing with sudo, \
or re-run with RUST_LOG=debug for more details." or re-run with RUST_LOG=debug for more details."
.into()); .into());
@@ -958,7 +958,7 @@ pub async fn build(
// Rootless builds: the rules run as an unprivileged user owning the // Rootless builds: the rules run as an unprivileged user owning the
// staged tree. Everything before this point - dependency installation, // staged tree. Everything before this point - dependency installation,
// quilt patch application, staging cleanup - legitimately needs the // quilt patch application, staging cleanup - legitimately needs the
// context's root and stays with it. The build step runs BARE (no // sandbox's root and stays with it. The build step runs BARE (no
// fakeroot): fakeroot's IPC degrades under kernel-scale parallel // fakeroot): fakeroot's IPC degrades under kernel-scale parallel
// builds ('libfakeroot internal error: payload not recognized' per // builds ('libfakeroot internal error: payload not recognized' per
// LTO/make -j process flood), and a rules chown that fails for the // LTO/make -j process flood), and a rules chown that fails for the
@@ -1231,7 +1231,7 @@ fn next_install_pass(
specs specs
} }
/// Query the candidates available in the build context for `names`: one /// Query the candidates available in the build sandbox for `names`: one
/// entry per (package, architecture). The plain name surfaces the /// entry per (package, architecture). The plain name surfaces the
/// build-architecture and `all` candidates; the host-qualified name is /// build-architecture and `all` candidates; the host-qualified name is
/// what surfaces foreign-arch candidates. Names missing from the indexes /// what surfaces foreign-arch candidates. Names missing from the indexes
@@ -1273,8 +1273,8 @@ fn query_candidates(
map map
} }
/// Build architecture inside the build context. /// Build architecture inside the build sandbox.
fn context_build_arch(ctx: &Arc<dyn Sandbox>) -> String { fn sandbox_build_arch(ctx: &Arc<dyn Sandbox>) -> String {
ctx.command("dpkg") ctx.command("dpkg")
.arg("--print-architecture") .arg("--print-architecture")
.output() .output()
@@ -1306,14 +1306,14 @@ fn build_profiles_for(env: &HashMap<String, String>, ctx: &Arc<dyn Sandbox>) ->
} }
} }
/// Installed-package facts inside the build context. An unreadable status /// Installed-package facts inside the build sandbox. 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<dyn Sandbox>, build_arch: &str, host_arch: &str) -> Facts { fn load_sandbox_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) => {
log::debug!("cannot read the context dpkg status: {e}"); log::debug!("cannot read the sandbox dpkg status: {e}");
Facts::new(host_arch, build_arch) Facts::new(host_arch, build_arch)
} }
} }
@@ -1322,7 +1322,7 @@ fn load_context_facts(ctx: &Arc<dyn Sandbox>, build_arch: &str, host_arch: &str)
/// Resolve and install the Build-* dependencies with dpkg's cross /// Resolve and install the Build-* dependencies with dpkg's cross
/// semantics: the clauses of `debian/control` are evaluated natively (the /// semantics: the clauses of `debian/control` are evaluated natively (the
/// `crate::debian::deps` `dpkg-checkbuilddeps` equivalent) against the /// `crate::debian::deps` `dpkg-checkbuilddeps` equivalent) against the
/// context's installed-package state, and the unsatisfied ones install /// sandbox's installed-package state, and the unsatisfied ones install
/// through explicitly architecture-qualified names. /// through explicitly architecture-qualified names.
/// ///
/// Build conflicts abort before anything installs. The loop installs one /// Build conflicts abort before anything installs. The loop installs one
@@ -1349,7 +1349,7 @@ fn install_build_dependencies(
enter_phase(view, Phase::InstallingBuildDeps, profiler); enter_phase(view, Phase::InstallingBuildDeps, profiler);
let host_arch = arch.to_string(); let host_arch = arch.to_string();
let build_arch = context_build_arch(&ctx); let build_arch = sandbox_build_arch(&ctx);
let profiles = build_profiles_for(env, &ctx); let profiles = build_profiles_for(env, &ctx);
let control_content = ctx let control_content = ctx
@@ -1416,7 +1416,7 @@ fn install_build_dependencies(
let mut cursors = vec![0usize; clauses.len()]; let mut cursors = vec![0usize; clauses.len()];
loop { loop {
let facts = load_context_facts(&ctx, &build_arch, &host_arch); let facts = load_sandbox_facts(&ctx, &build_arch, &host_arch);
// Build conflicts use the same lookup as dependencies in dpkg's // Build conflicts use the same lookup as dependencies in dpkg's
// checker: a satisfied conflict clause aborts before anything // checker: a satisfied conflict clause aborts before anything
@@ -1522,7 +1522,7 @@ fn install_build_dependencies(
} }
/// Collect the binary artifacts (.deb/.udeb) registered by the build in /// Collect the binary artifacts (.deb/.udeb) registered by the build in
/// `debian/files`, returning their paths inside the build context /// `debian/files`, returning their paths inside the build sandbox
/// (`<upload_dir>/<filename>`, dh_builddeb's `..`: the package /// (`<upload_dir>/<filename>`, dh_builddeb's `..`: the package
/// directory's parent). `debian/files` is the canonical record of /// directory's parent). `debian/files` is the canonical record of
/// which binary packages `debian/rules binary` produced, so we retrieve /// which binary packages `debian/rules binary` produced, so we retrieve
@@ -1549,7 +1549,7 @@ fn collect_binary_artifacts(
} }
/// Generate `.buildinfo` and `.changes` for the finished binary build, /// Generate `.buildinfo` and `.changes` for the finished binary build,
/// inside the build context. /// inside the build sandbox.
fn generate_upload_metadata( fn generate_upload_metadata(
package_dir: &str, package_dir: &str,
upload_dir: &str, upload_dir: &str,
@@ -1558,7 +1558,7 @@ fn generate_upload_metadata(
env: &HashMap<String, String>, env: &HashMap<String, String>,
ctx: &Arc<dyn Sandbox>, 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 sandbox.
let build_arch = ctx let build_arch = ctx
.command("dpkg") .command("dpkg")
.arg("--print-architecture") .arg("--print-architecture")
@@ -1574,7 +1574,7 @@ fn generate_upload_metadata(
build_arch.clone() build_arch.clone()
}; };
// Vendor resolution inside the context (falls back to the host view); // Vendor resolution inside the sandbox (falls back to the host view);
// shared `Vendor:`/`Origin:` parsing with the source-build path. // shared `Vendor:`/`Origin:` parsing with the source-build path.
let vendor = ctx let vendor = ctx
.read_file(Path::new("/etc/dpkg/origins/default")) .read_file(Path::new("/etc/dpkg/origins/default"))
@@ -1715,7 +1715,7 @@ fn apply_quilt_patches(
); );
} }
// Make sure quilt is available in the build context // Make sure quilt is available in the build sandbox
log::debug!("Installing quilt for patch application..."); log::debug!("Installing quilt for patch application...");
let status = cap( let status = cap(
ctx.command("apt-get") ctx.command("apt-get")
@@ -1781,7 +1781,7 @@ fn apply_quilt_patches(
} }
/// Whether the source options of the package tree at `package_dir` (inside /// Whether the source options of the package tree at `package_dir` (inside
/// the build context) declare the `single-debian-patch` mode: either /// the build sandbox) declare the `single-debian-patch` mode: either
/// `debian/source/local-options` or `debian/source/options` contains a /// `debian/source/local-options` or `debian/source/options` contains a
/// line whose trimmed content — after stripping a leading `--` long-option /// line whose trimmed content — after stripping a leading `--` long-option
/// dash — is exactly `single-debian-patch` (both spellings exist in the /// dash — is exactly `single-debian-patch` (both spellings exist in the
@@ -1852,7 +1852,7 @@ pub(crate) fn install_injected_packages(
// Check if it's a .deb file path (ends with .deb and exists as a file) // Check if it's a .deb file path (ends with .deb and exists as a file)
let pkg_path = Path::new(pkg); let pkg_path = Path::new(pkg);
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 sandbox
let dest_root = ctx.create_temp_dir()?; let dest_root = ctx.create_temp_dir()?;
let chroot_path = let chroot_path =
Path::new(&dest_root).join(pkg_path.file_name().unwrap_or(pkg_path.as_os_str())); Path::new(&dest_root).join(pkg_path.file_name().unwrap_or(pkg_path.as_os_str()));
@@ -2275,10 +2275,10 @@ mod tests {
} }
/// A tree with `single-debian-patch` in its local-options is detected /// A tree with `single-debian-patch` in its local-options is detected
/// through the real build-context file access; a tree without the /// through the real build-sandbox file access; a tree without the
/// 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_sandbox() {
let ctx: Arc<dyn Sandbox> = Arc::new(Host::new()); let ctx: Arc<dyn Sandbox> = Arc::new(Host::new());
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
+26 -29
View File
@@ -217,7 +217,7 @@ pub struct DebBuildOptions<'a> {
/// (.deb paths, archive names or PPA packages). /// (.deb paths, archive names or PPA packages).
pub inject: Vec<String>, pub inject: Vec<String>,
/// Parallel build jobs; defaults to the core count available in the /// Parallel build jobs; defaults to the core count available in the
/// build context. /// build sandbox.
pub jobs: Option<usize>, pub jobs: Option<usize>,
/// Incremental request (`pkh deb --incremental [<id>]`): which /// Incremental request (`pkh deb --incremental [<id>]`): which
/// record to fork as the base of this build's staged tree, and /// record to fork as the base of this build's staged tree, and
@@ -459,9 +459,9 @@ async fn build_binary_package_impl(
tee_log: true, tee_log: true,
}); });
// Create an ephemeral unshare context for all Local builds. It is kept in // Create the build's unshare sandbox. It stays in this scope so it
// this scope so it outlives the guarded section below and is only dropped // outlives the guarded section below and is only dropped once the live
// once the live view has been cleared. // view has been cleared.
// //
// Every build runs in its own record under the sessions directory // Every build runs in its own record under the sessions directory
// (forked from a previous one with `--incremental`, thrown away // (forked from a previous one with `--incremental`, thrown away
@@ -500,7 +500,7 @@ async fn build_binary_package_impl(
// inherit the terminal — the wrapper removes that fallback, so the // inherit the terminal — the wrapper removes that fallback, so the
// raw lines are written by a terminal sink instead, and --verbose // raw lines are written by a terminal sink instead, and --verbose
// keeps showing raw output. A record-less build (non-local base // keeps showing raw output. A record-less build (non-local base
// context) keeps the plain view. // record) keeps the plain view.
let record_log: Option<Result<Arc<session::RecordLogSink>, std::io::Error>> = let record_log: Option<Result<Arc<session::RecordLogSink>, std::io::Error>> =
session.as_ref().map(|s| { session.as_ref().map(|s| {
session::RecordLogSink::new( session::RecordLogSink::new(
@@ -547,7 +547,7 @@ async fn build_binary_package_impl(
)) ))
} else { } else {
Some(Arc::new( Some(Arc::new(
Unshare::new_with_context( Unshare::new_with_base(
series, series,
chroot_arch, chroot_arch,
mirror_arg, mirror_arg,
@@ -559,11 +559,9 @@ async fn build_binary_package_impl(
)) ))
}; };
// Determine the build context explicitly: for Local builds it is the // The build runs in the unshare sandbox the guard created, taken from
// ephemeral context the guard just created (taken from the guard itself, // the guard itself rather than any global that concurrent builds could
// never from the process-global, which concurrent builds may have // re-point at their own chroot.
// re-pointed at their own chroot); otherwise the base context is used
// directly.
let build_ctx: Arc<dyn Sandbox> = match guard.as_ref() { let build_ctx: Arc<dyn Sandbox> = match guard.as_ref() {
Some(g) => Arc::clone(g) as Arc<dyn Sandbox>, Some(g) => Arc::clone(g) as Arc<dyn Sandbox>,
None => base_ctx.clone(), None => base_ctx.clone(),
@@ -704,7 +702,7 @@ async fn build_binary_package_impl(
session.as_ref(), session.as_ref(),
build_resume, build_resume,
ccache, ccache,
// Rootless builds: only a context pkh controls (the // Rootless builds: only a sandbox pkh controls (the
// ephemeral chroot) can carry the on-demand build user. // ephemeral chroot) can carry the on-demand build user.
Some(local::BUILD_USER), Some(local::BUILD_USER),
&mut timings, &mut timings,
@@ -1060,9 +1058,9 @@ pub(crate) fn find_package_directory(
let entries = ctx.list_files(package_parent)?; let entries = ctx.list_files(package_parent)?;
let mut found_dirs = Vec::new(); let mut found_dirs = Vec::new();
for entry in entries { for entry in entries {
// list_files yields context-relative paths (e.g. rooted inside // list_files yields sandbox-relative paths (e.g. rooted inside
// the chroot for an unshare context): classify through the // the chroot for an unshare sandbox): classify through the
// context, a host-side stat would miss every entry. // sandbox, a host-side stat would miss every entry.
let is_dir = ctx.is_dir(&entry)?; let is_dir = ctx.is_dir(&entry)?;
log::debug!(" - {}", entry.display()); log::debug!(" - {}", entry.display());
if is_dir && let Some(file_name) = entry.file_name() { if is_dir && let Some(file_name) = entry.file_name() {
@@ -1101,7 +1099,7 @@ fn find_dsc_file(
let dsc_name = format!("{}_{}.dsc", package, version_without_epoch); let dsc_name = format!("{}_{}.dsc", package, version_without_epoch);
let dsc_path = PathBuf::from(build_root).join(&dsc_name); let dsc_path = PathBuf::from(build_root).join(&dsc_name);
// Check if the .dsc file exists in context // Check if the .dsc file exists in the sandbox
if !ctx.exists(&dsc_path)? { if !ctx.exists(&dsc_path)? {
return Err(format!("Could not find .dsc file at {}", dsc_path.display()).into()); return Err(format!("Could not find .dsc file at {}", dsc_path.display()).into());
} }
@@ -1231,24 +1229,23 @@ mod tests {
assert!(profiler.finish().is_empty()); assert!(profiler.finish().is_empty());
} }
/// An unshare context mapped over `chroot_root`, parented on a local /// An unshare sandbox mapped over `chroot_root` on a host base:
/// context like the ephemeral build contexts are: exists/list_files/ /// exists/list_files/is_dir answer through the path mapping, no
/// is_dir answer through the path mapping, no namespace privileges /// namespace privileges needed.
/// needed. fn unshare_test_sandbox(chroot_root: &Path) -> Arc<dyn Sandbox> {
fn unshare_test_context(chroot_root: &Path) -> Arc<dyn Sandbox> {
Arc::new(crate::sandbox::unshare::UnshareDriver::new( Arc::new(crate::sandbox::unshare::UnshareDriver::new(
chroot_root.to_path_buf(), chroot_root.to_path_buf(),
Arc::new(Host::new()), Arc::new(Host::new()),
)) ))
} }
/// The staging-area listing must classify entries through the context: /// The staging-area listing must classify entries through the sandbox:
/// an unshare context returns build-root-relative paths that a host-side /// an unshare sandbox returns build-root-relative paths that a host-side
/// stat never sees (they live under the chroot root on the host), which /// stat never sees (they live under the chroot root on the host), which
/// used to silently empty the 'Found directories' list of the search /// used to silently empty the 'Found directories' list of the search
/// failure message — and with it every hint about the actual layout. /// failure message — and with it every hint about the actual layout.
#[test] #[test]
fn find_package_directory_lists_staged_directories_through_the_context() { fn find_package_directory_lists_staged_directories_through_the_sandbox() {
let chroot = tempfile::tempdir().unwrap(); let chroot = tempfile::tempdir().unwrap();
// Staged tree holding a single nested checkout whose name matches // Staged tree holding a single nested checkout whose name matches
// none of the search patterns (the embedded-caller layout: // none of the search patterns (the embedded-caller layout:
@@ -1256,7 +1253,7 @@ mod tests {
let staged_tree = chroot.path().join("tmp/pkh-build-1/j-42"); let staged_tree = chroot.path().join("tmp/pkh-build-1/j-42");
std::fs::create_dir_all(staged_tree.join("tree/debian")).unwrap(); std::fs::create_dir_all(staged_tree.join("tree/debian")).unwrap();
let ctx = unshare_test_context(chroot.path()); let ctx = unshare_test_sandbox(chroot.path());
let err = find_package_directory( let err = find_package_directory(
Path::new("/tmp/pkh-build-1/j-42"), Path::new("/tmp/pkh-build-1/j-42"),
"bc", "bc",
@@ -1269,7 +1266,7 @@ mod tests {
let message = err.to_string(); let message = err.to_string();
assert!( assert!(
message.contains("Found directories: tree"), message.contains("Found directories: tree"),
"error should list the staged directories through the context: {message}" "error should list the staged directories through the sandbox: {message}"
); );
} }
@@ -1283,7 +1280,7 @@ mod tests {
let staged_tree = chroot.path().join("tmp/pkh-build-1/tree"); let staged_tree = chroot.path().join("tmp/pkh-build-1/tree");
std::fs::create_dir_all(staged_tree.join("debian/source")).unwrap(); std::fs::create_dir_all(staged_tree.join("debian/source")).unwrap();
let ctx = unshare_test_context(chroot.path()); let ctx = unshare_test_sandbox(chroot.path());
let resolved = resolve_package_directory( let resolved = resolve_package_directory(
Path::new("/tmp/pkh-build-1/tree"), Path::new("/tmp/pkh-build-1/tree"),
"bc", "bc",
@@ -1307,7 +1304,7 @@ mod tests {
// <pkg>/<pkg>-<origversion> // <pkg>/<pkg>-<origversion>
std::fs::create_dir_all(staged_tree.join("bc/bc-1.07.1/debian")).unwrap(); std::fs::create_dir_all(staged_tree.join("bc/bc-1.07.1/debian")).unwrap();
let ctx = unshare_test_context(chroot.path()); let ctx = unshare_test_sandbox(chroot.path());
let resolved = resolve_package_directory( let resolved = resolve_package_directory(
Path::new("/tmp/pkh-build-1/checkout"), Path::new("/tmp/pkh-build-1/checkout"),
"bc", "bc",
@@ -1427,7 +1424,7 @@ mod tests {
} }
// Tests no longer need to be 'serial' since each test uses its own // Tests no longer need to be 'serial' since each test uses its own
// explicit context instead of shared global state. // explicit sandbox instead of shared global state.
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_deb_hello_ubuntu_end_to_end() { async fn test_deb_hello_ubuntu_end_to_end() {
+1 -1
View File
@@ -399,7 +399,7 @@ fn main() {
.long_help("Inject a package into the build environment before build-dep. Can be a .deb file path, a package name from the archive, or a package from a previously added PPA. Can be specified multiple times.").required(false).action(clap::ArgAction::Append)) .long_help("Inject a package into the build environment before build-dep. Can be a .deb file path, a package name from the archive, or a package from a previously added PPA. Can be specified multiple times.").required(false).action(clap::ArgAction::Append))
.arg(arg!(--cross "Cross-compile for target architecture (instead of qemu-binfmt)") .arg(arg!(--cross "Cross-compile for target architecture (instead of qemu-binfmt)")
.long_help("Cross-compile for target architecture (instead of using qemu-binfmt)\nNote that most packages cannot be cross-compiled").required(false)) .long_help("Cross-compile for target architecture (instead of using qemu-binfmt)\nNote that most packages cannot be cross-compiled").required(false))
.arg(arg!(-j --jobs <jobs> "Number of parallel build jobs (default: number of CPUs available in the build context)").required(false)) .arg(arg!(-j --jobs <jobs> "Number of parallel build jobs (default: number of CPUs available in the build sandbox)").required(false))
.arg( .arg(
clap::Arg::new("incremental") clap::Arg::new("incremental")
.long("incremental") .long("incremental")
+1 -1
View File
@@ -4,7 +4,7 @@
//! //!
//! - **Residual build/chroot directories** under the system temp directory, //! - **Residual build/chroot directories** under the system temp directory,
//! named `pkh-<timestamp>` (or `pkh-<timestamp>-<attempt>` on collision). //! named `pkh-<timestamp>` (or `pkh-<timestamp>-<attempt>` on collision).
//! They are created by the local and ephemeral build contexts and are //! They are created by the local and ephemeral build sandboxs and are
//! *intentionally kept* when a build fails so they can be inspected. They //! *intentionally kept* when a build fails so they can be inspected. They
//! may contain root-owned device nodes (created via `mknod`), a //! may contain root-owned device nodes (created via `mknod`), a
//! bind-mounted `/proc` and overlay filesystems, so they require careful //! bind-mounted `/proc` and overlay filesystems, so they require careful
+1 -1
View File
@@ -11,7 +11,7 @@
//! server fails the upload instead of hanging it forever. //! server fails the upload instead of hanging it forever.
//! //!
//! This replaces dput-ng's paramiko transport with the `ssh2` (libssh2) //! This replaces dput-ng's paramiko transport with the `ssh2` (libssh2)
//! stack the rest of pkh already uses for build contexts. //! stack the rest of pkh already uses for build sandboxs.
use std::collections::HashMap; use std::collections::HashMap;
use std::fs; use std::fs;
+1 -1
View File
@@ -11,7 +11,7 @@ use super::{BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcom
/// ///
/// Commands run with [`std::process::Command`], files use [`std::fs`], and /// Commands run with [`std::process::Command`], files use [`std::fs`], and
/// there is no teardown. This serves `pkh test --mode local` and the unit /// there is no teardown. This serves `pkh test --mode local` and the unit
/// tests that build a local context. /// tests that build on the host.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct Host; pub struct Host;
+3 -3
View File
@@ -215,7 +215,7 @@ impl<'a> BuildCommand<'a> {
self.sandbox self.sandbox
.run(&self.spec, capture) .run(&self.spec, capture)
.map(|execution| execution.status) .map(|execution| execution.status)
.map_err(|e| contextualize_spawn_error(&self.spec.program.to_string_lossy(), e)) .map_err(|e| explain_spawn_error(&self.spec.program.to_string_lossy(), e))
} }
/// Run the command and capture its complete output. /// Run the command and capture its complete output.
@@ -227,7 +227,7 @@ impl<'a> BuildCommand<'a> {
stdout: execution.stdout, stdout: execution.stdout,
stderr: execution.stderr, stderr: execution.stderr,
}) })
.map_err(|e| contextualize_spawn_error(&self.spec.program.to_string_lossy(), e)) .map_err(|e| explain_spawn_error(&self.spec.program.to_string_lossy(), e))
} }
} }
@@ -272,7 +272,7 @@ impl SandboxExt for dyn Sandbox + '_ {
} }
/// Wrap an I/O error from launching a command with a more helpful message. /// Wrap an I/O error from launching a command with a more helpful message.
pub(crate) fn contextualize_spawn_error(program: &str, e: io::Error) -> io::Error { pub(crate) fn explain_spawn_error(program: &str, e: io::Error) -> io::Error {
if e.kind() == io::ErrorKind::NotFound { if e.kind() == io::ErrorKind::NotFound {
io::Error::new( io::Error::new(
e.kind(), e.kind(),
+19 -21
View File
@@ -26,7 +26,7 @@ use xz2::read::XzDecoder;
// Interrupt-time cleanup // Interrupt-time cleanup
// //
// On Ctrl-C, the watchdog in `crate::interrupt` runs the hook registered in // On Ctrl-C, the watchdog in `crate::interrupt` runs the hook registered in
// [`Unshare::new_with_context`] right before exiting — the // [`Unshare::new_with_base`] right before exiting — the
// interrupt sequence skips all destructors, which would otherwise leak the // interrupt sequence skips all destructors, which would otherwise leak the
// freshly bootstrapped chroot under /tmp together with its bind-mounted // freshly bootstrapped chroot under /tmp together with its bind-mounted
// /proc and any overlayfs mounts. // /proc and any overlayfs mounts.
@@ -51,10 +51,10 @@ fn sigint_cleanup_chroot(chroot_path: &Path) {
/// interrupt included. /// interrupt included.
/// ///
/// Unlike [`Unshare::drop`], this deliberately does NOT go /// Unlike [`Unshare::drop`], this deliberately does NOT go
/// through the context manager, the ephemeral context's driver (whose /// through the sandbox's driver (whose `cleanup()` unmounts the tracked
/// `cleanup()` unmounts the tracked overlays) or the base context's /// overlays) or the base sandbox's command builder: interrupt-time hooks
/// command builder: interrupt-time hooks must be self-contained, and /// must be self-contained, and those machineries may be mid-mutation on
/// those machineries may be mid-mutation on the interrupted thread. /// the interrupted thread.
/// Instead it only reads /proc/mounts and spawns umount/rm directly. /// Instead it only reads /proc/mounts and spawns umount/rm directly.
/// ///
/// Best-effort by design: if a child process still holds a mount busy or /// Best-effort by design: if a child process still holds a mount busy or
@@ -478,8 +478,8 @@ fn unescape_mount_field(field: &str) -> String {
String::from_utf8_lossy(&out).into_owned() String::from_utf8_lossy(&out).into_owned()
} }
/// An ephemeral unshare context guard that creates and manages a temporary chroot environment /// An ephemeral unshare sandbox that creates and manages a temporary chroot
/// for building packages with unshare permissions. /// environment for building packages with unshare permissions.
/// ///
/// In session mode ([`Unshare::new_for_session`]) the chroot /// In session mode ([`Unshare::new_for_session`]) the chroot
/// lives inside a [`Session`] record's `chroot/` directory — extracted /// lives inside a [`Session`] record's `chroot/` directory — extracted
@@ -488,10 +488,8 @@ fn unescape_mount_field(field: &str) -> String {
/// always kept as metadata and log; its staged tree is retained exactly /// always kept as metadata and log; its staged tree is retained exactly
/// for `--incremental` runs (`keep_upper`). /// for `--incremental` runs (`keep_upper`).
pub struct Unshare { pub struct Unshare {
/// The ephemeral build context this guard created (an unshare context /// The chroot driver this sandbox owns: path mapping, namespace
/// bound to the chroot, parented on the base context). Held explicitly so /// wrappers and overlay staging.
/// cleanup and the build itself never depend on the process-global
/// "current" context, which concurrent builds swap for their own.
driver: UnshareDriver, driver: UnshareDriver,
chroot_path: PathBuf, chroot_path: PathBuf,
build_succeeded: AtomicBool, build_succeeded: AtomicBool,
@@ -513,16 +511,16 @@ pub struct Unshare {
} }
impl Unshare { impl Unshare {
/// Create a new ephemeral unshare context with an explicit base context /// Create a new unshare sandbox with an explicit base sandbox
/// ///
/// # Arguments /// # Arguments
/// * `series` - The distribution series (e.g., "noble", "sid") /// * `series` - The distribution series (e.g., "noble", "sid")
/// * `arch` - Optional target architecture. If provided and different from host, /// * `arch` - Optional target architecture. If provided and different from host,
/// downloads a chroot for that architecture (uses qemu_binfmt transparently) /// downloads a chroot for that architecture (uses qemu_binfmt transparently)
/// * `base_ctx` - The base context to use for creating the chroot /// * `base_ctx` - The base sandbox used to create the chroot
/// * `profiler` - The per-phase build profile to feed (the chroot /// * `profiler` - The per-phase build profile to feed (the chroot
/// bootstrap's phases of the record's `pkh deb profile`) /// bootstrap's phases of the record's `pkh deb profile`)
pub(crate) async fn new_with_context( pub(crate) async fn new_with_base(
series: &str, series: &str,
arch: Option<&str>, arch: Option<&str>,
mirror: Option<&str>, mirror: Option<&str>,
@@ -536,15 +534,15 @@ impl Unshare {
.await .await
} }
/// Create the ephemeral build context inside `session`'s chroot. /// Create the unshare sandbox inside `session`'s chroot.
/// ///
/// # Arguments /// # Arguments
/// * `session` - The build record owning the chroot (locked by the /// * `session` - The build record owning the chroot (locked by the
/// caller) /// caller)
/// * `series` - The distribution series (e.g., "noble", "sid") /// * `series` - The distribution series (e.g., "noble", "sid")
/// * `arch` - Optional target architecture, as for /// * `arch` - Optional target architecture, as for
/// [`Unshare::new_with_context`] /// [`Unshare::new_with_base`]
/// * `base_ctx` - The base context to use for chroot work /// * `base_ctx` - The base sandbox used for chroot work
/// * `keep_upper` - Retain the record's staged tree after the build /// * `keep_upper` - Retain the record's staged tree after the build
/// (`pkh deb --incremental`); a plain run's record keeps metadata /// (`pkh deb --incremental`); a plain run's record keeps metadata
/// and log only /// and log only
@@ -613,7 +611,7 @@ impl Unshare {
// the user hits Ctrl-C during bootstrap or the build itself, the // the user hits Ctrl-C during bootstrap or the build itself, the
// interrupt watchdog unmounts the chroot's mounts through this hook // interrupt watchdog unmounts the chroot's mounts through this hook
// (see `sigint_cleanup_chroot`). This only works for a local // (see `sigint_cleanup_chroot`). This only works for a local
// base context: the hook must be self-contained (stored path + // base sandbox: the hook must be self-contained (stored path +
// direct umount/rm subprocesses) and cannot go through `base_ctx`. // direct umount/rm subprocesses) and cannot go through `base_ctx`.
// For remote or nested bases the chroot lives elsewhere, and // For remote or nested bases the chroot lives elsewhere, and
// leftovers stay handled by `pkh prune` as before. // leftovers stay handled by `pkh prune` as before.
@@ -635,7 +633,7 @@ impl Unshare {
Some(crate::interrupt::register_cleanup_hook(hook)) Some(crate::interrupt::register_cleanup_hook(hook))
} else { } else {
log::debug!( log::debug!(
"Base context is not local; skipping interrupt-time cleanup registration for {}", "Base sandbox is not the host; skipping interrupt-time cleanup registration for {}",
chroot_path.display() chroot_path.display()
); );
None None
@@ -1266,9 +1264,9 @@ impl Drop for Unshare {
cleanup_hook.deregister(); cleanup_hook.deregister();
} }
log::debug!("Cleaning up ephemeral context ({:?})...", self.chroot_path); log::debug!("Cleaning up unshare sandbox ({:?})...", self.chroot_path);
// Clean up any overlay mounts before resetting the context. This // Clean up any overlay mounts before tearing the sandbox down. This
// explicitly targets the driver this guard created, never a global // explicitly targets the driver this guard created, never a global
// handle another concurrent build may have swapped. The actual // handle another concurrent build may have swapped. The actual
// unmount commands run through the base sandbox. // unmount commands run through the base sandbox.
+1 -1
View File
@@ -22,7 +22,7 @@ pub(crate) const MAPPED_BUILD_ID: u32 = 65536;
const _: () = assert!( const _: () = assert!(
MAPPED_BUILD_ID > 65535, MAPPED_BUILD_ID > 65535,
"the mapped identity must not alias a context-namespace uid" "the mapped identity must not alias a user-namespace uid"
); );
/// The unshare implementation of [`Sandbox`]. /// The unshare implementation of [`Sandbox`].
+4 -4
View File
@@ -38,7 +38,7 @@ impl Bed {
// foreign-arch chroot, so the native case shares deb's // foreign-arch chroot, so the native case shares deb's
// unsuffixed `<series>-buildd.tar.xz` cache entry. // unsuffixed `<series>-buildd.tar.xz` cache entry.
let chroot_arch = (arch != crate::get_current_arch()).then(|| arch.to_string()); let chroot_arch = (arch != crate::get_current_arch()).then(|| arch.to_string());
let guard = Unshare::new_with_context( let guard = Unshare::new_with_base(
series, series,
chroot_arch.as_deref(), chroot_arch.as_deref(),
None, None,
@@ -55,7 +55,7 @@ impl Bed {
} }
} }
/// The context to run testbed commands in. /// The sandbox to run testbed commands in.
pub(crate) fn ctx(&self) -> Arc<dyn Sandbox> { pub(crate) fn ctx(&self) -> Arc<dyn Sandbox> {
match self { match self {
Bed::Chroot(guard) => Arc::clone(guard) as Arc<dyn Sandbox>, Bed::Chroot(guard) => Arc::clone(guard) as Arc<dyn Sandbox>,
@@ -75,8 +75,8 @@ impl Bed {
} }
/// Whether root-requiring tests can run: always inside a chroot /// Whether root-requiring tests can run: always inside a chroot
/// (commands run as mapped root), on the local context only when the /// (commands run as mapped root), on the host only when the sandbox
/// context itself runs as root. /// itself runs as root.
pub(crate) fn supports_root(&self) -> bool { pub(crate) fn supports_root(&self) -> bool {
match self { match self {
Bed::Chroot(_) => true, Bed::Chroot(_) => true,
+5 -5
View File
@@ -247,7 +247,7 @@ pub async fn run(opts: TestOptions<'_>) -> Result<TestRunReport, Box<dyn std::er
.iter() .iter()
.filter_map(|deb| deb_binary_name(deb)) .filter_map(|deb| deb_binary_name(deb))
.collect(); .collect();
let run_ctx = runner::RunContext { let run_ctx = runner::RunEnv {
ctx, ctx,
tree: staged_tree.clone(), tree: staged_tree.clone(),
staging_root, staging_root,
@@ -458,7 +458,7 @@ async fn configure_testbed(
series: &str, series: &str,
arch: &str, arch: &str,
opts: &TestOptions<'_>, opts: &TestOptions<'_>,
local_context: bool, host_sandbox: bool,
view: &dyn BuildView, view: &dyn BuildView,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let mut sources = crate::apt::sources::load(Some(ctx.clone()))?; let mut sources = crate::apt::sources::load(Some(ctx.clone()))?;
@@ -539,7 +539,7 @@ async fn configure_testbed(
if !status.success() { if !status.success() {
return Err(format!( return Err(format!(
"apt-get update failed inside the testbed{}", "apt-get update failed inside the testbed{}",
if local_context { if host_sandbox {
" (a local run needs root to install packages: \ " (a local run needs root to install packages: \
use sudo, or the default chroot mode)" use sudo, or the default chroot mode)"
} else { } else {
@@ -781,8 +781,8 @@ mod tests {
return; // not requested: nothing to compare return; // not requested: nothing to compare
}; };
// pkh's native runner, on the host context (autopkgtest's null // pkh's native runner, on the host (autopkgtest's null runner
// runner equivalent). // equivalent).
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let native = rt.block_on(crate::test::run(TestOptions { let native = rt.block_on(crate::test::run(TestOptions {
tree: Some(tree.clone()), tree: Some(tree.clone()),
+1 -1
View File
@@ -6,7 +6,7 @@ use std::path::PathBuf;
/// Testbed mode: where the tests run. /// Testbed mode: where the tests run.
/// ///
/// The default is [`TestMode::Chroot`]: `pkh deb` defaults to the local /// The default is [`TestMode::Chroot`]: `pkh deb` defaults to the local
/// context because builds are non-destructive, but autopkgtests install /// sandbox because builds are non-destructive, but autopkgtests install
/// packages and are destructive by design — isolation is the default and /// packages and are destructive by design — isolation is the default and
/// running on the host is the explicit choice. /// running on the host is the explicit choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+13 -13
View File
@@ -29,12 +29,12 @@ use crate::test::outcome::{TestOutcome, Verdict};
const KILL_AFTER_SECS: u64 = 15; 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 RunEnv<'a> {
/// The testbed context. /// The testbed sandbox.
pub ctx: Arc<dyn Sandbox>, pub ctx: Arc<dyn Sandbox>,
/// Context-side path of the staged source tree. /// Sandbox-side path of the staged source tree.
pub tree: String, pub tree: String,
/// Context-side scratch root (temporary directories, artifacts). /// Sandbox-side scratch root (temporary directories, artifacts).
pub staging_root: String, pub staging_root: String,
/// The testbed architecture. /// The testbed architecture.
pub arch: String, pub arch: String,
@@ -61,7 +61,7 @@ pub(crate) struct RunContext<'a> {
/// Run the tests in declaration order, filtered by the caller's /// Run the tests in declaration order, filtered by the caller's
/// selection, and return one outcome per selected test. /// selection, and return one outcome per selected test.
pub(crate) fn run_tests( pub(crate) fn run_tests(
run: &RunContext<'_>, run: &RunEnv<'_>,
tests: &[Test], tests: &[Test],
only: &[String], only: &[String],
skipped: &[String], skipped: &[String],
@@ -158,7 +158,7 @@ pub(crate) fn restriction_skip(
} }
/// Run one test through the DEP-8 contract. /// Run one test through the DEP-8 contract.
fn run_one(run: &RunContext<'_>, test: &Test) -> TestOutcome { fn run_one(run: &RunEnv<'_>, test: &Test) -> TestOutcome {
let started = Instant::now(); let started = Instant::now();
if let Some(reason) = restriction_skip(test, run.supports_root, run.arch != run.host_arch) { if let Some(reason) = restriction_skip(test, run.supports_root, run.arch != run.host_arch) {
return TestOutcome { return TestOutcome {
@@ -215,7 +215,7 @@ fn outcome_fail(test: &Test, started: Instant, reason: String) -> TestOutcome {
} }
/// Execute a test once, returning the raw result and its duration. /// Execute a test once, returning the raw result and its duration.
fn execute(run: &RunContext<'_>, test: &Test) -> (RawRun, Duration) { fn execute(run: &RunEnv<'_>, test: &Test) -> (RawRun, Duration) {
let started = Instant::now(); let started = Instant::now();
// Fresh per-test scratch and artifact directories. // Fresh per-test scratch and artifact directories.
@@ -293,7 +293,7 @@ fn execute(run: &RunContext<'_>, test: &Test) -> (RawRun, Duration) {
} }
/// Install a test stanza's expanded dependencies. /// Install a test stanza's expanded dependencies.
fn install_test_deps(run: &RunContext<'_>, test: &Test) -> Result<(), String> { fn install_test_deps(run: &RunEnv<'_>, test: &Test) -> Result<(), String> {
let specs = expand_depends( let specs = expand_depends(
test.depends.as_deref(), test.depends.as_deref(),
&run.control, &run.control,
@@ -328,7 +328,7 @@ fn install_test_deps(run: &RunContext<'_>, test: &Test) -> Result<(), String> {
/// Bring the staged tree to its built state (`build-needed` tests): the /// Bring the staged tree to its built state (`build-needed` tests): the
/// autopkgtest build, with the nocheck profile — the tests need the /// autopkgtest build, with the nocheck profile — the tests need the
/// build products, not another set of binaries. /// build products, not another set of binaries.
fn build_tree(run: &RunContext<'_>) -> Result<(), String> { fn build_tree(run: &RunEnv<'_>) -> Result<(), String> {
let mut env = run.env.clone(); let mut env = run.env.clone();
env.insert("DEB_BUILD_OPTIONS".to_string(), "nocheck".to_string()); env.insert("DEB_BUILD_OPTIONS".to_string(), "nocheck".to_string());
let mut cmd = run.ctx.command("dpkg-buildpackage"); let mut cmd = run.ctx.command("dpkg-buildpackage");
@@ -345,16 +345,16 @@ fn build_tree(run: &RunContext<'_>) -> Result<(), String> {
} }
} }
/// The context-side path of a test script: `Tests-Directory:` replaces /// The sandbox-side path of a test script: `Tests-Directory:` replaces
/// the `debian/tests` path segment. /// the `debian/tests` path segment.
fn test_script_path(run: &RunContext<'_>, test: &Test, script: &str) -> String { fn test_script_path(run: &RunEnv<'_>, test: &Test, script: &str) -> String {
let base = test.tests_directory.as_deref().unwrap_or("debian/tests"); let base = test.tests_directory.as_deref().unwrap_or("debian/tests");
format!("{}/{base}/{script}", run.tree) format!("{}/{base}/{script}", run.tree)
} }
/// Retrieve a test's artifacts directory from the testbed into the run's /// Retrieve a test's artifacts directory from the testbed into the run's
/// host directory (best-effort: tests may not have written anything). /// host directory (best-effort: tests may not have written anything).
fn retrieve_artifacts(run: &RunContext<'_>, test_name: &str) { fn retrieve_artifacts(run: &RunEnv<'_>, test_name: &str) {
let remote = PathBuf::from(format!( let remote = PathBuf::from(format!(
"{}/artifacts/{}", "{}/artifacts/{}",
run.staging_root, run.staging_root,
@@ -369,7 +369,7 @@ fn retrieve_artifacts(run: &RunContext<'_>, test_name: &str) {
} }
/// The host-side artifacts directory of one test. /// The host-side artifacts directory of one test.
fn host_artifacts_dir(run: &RunContext<'_>, test_name: &str) -> PathBuf { fn host_artifacts_dir(run: &RunEnv<'_>, test_name: &str) -> PathBuf {
run.artifacts_dir run.artifacts_dir
.join("artifacts") .join("artifacts")
.join(safe_name(test_name)) .join(safe_name(test_name))