From 674b99b00bc0976991136ce609100c9f74179d0c Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Tue, 24 Nov 2026 14:41:34 +0100 Subject: [PATCH] docs: describe the implemented sandbox architecture 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. --- AGENTS.md | 5 +- docs/sandbox.md | 159 +++++++++++++++---------------- src/apt/keyring.rs | 10 +- src/build/binary.rs | 22 ++--- src/deb/local.rs | 68 ++++++------- src/deb/mod.rs | 55 +++++------ src/main.rs | 2 +- src/prune.rs | 2 +- src/put/ssh.rs | 2 +- src/sandbox/host.rs | 2 +- src/sandbox/mod.rs | 6 +- src/sandbox/unshare/mod.rs | 40 ++++---- src/sandbox/unshare/namespace.rs | 2 +- src/test/bed.rs | 8 +- src/test/mod.rs | 10 +- src/test/options.rs | 2 +- src/test/runner.rs | 26 ++--- 17 files changed, 207 insertions(+), 214 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7ae3b3e..4dc59a2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,8 +46,9 @@ Rules: - `new` — package scaffolding (`src/new/`) - `lint` — tree linting (`src/lint/`) - `prune`, `package_info` — remaining subcommand modules - - `context` — build contexts: local, ssh, chroot/schroot, unshare - (`src/context/`) + - `sandbox` — the build environment trait, host and unshare backends, + staging (`src/sandbox/`) + - `exec` — subprocess line capture and host process helpers (`src/exec.rs`) - `interrupt` — Ctrl+C interception and interrupt-time cleanup (`src/interrupt.rs`) - `debian` — Debian format primitives: control, versions, checksums, diff --git a/docs/sandbox.md b/docs/sandbox.md index b6116c6..3988e6d 100644 --- a/docs/sandbox.md +++ b/docs/sandbox.md @@ -1,6 +1,6 @@ # Replacing Context with the Sandbox trait -Status: design proposal, not implemented. +Status: implemented. The public build and test APIs take `Arc`; `src/context/` is gone. ## 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 Ecrou microVM implementation can be added without touching build logic. -## What exists today +## What the old design was | 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 `Unshare::put`. The shared policy is `PutOptions`: -- `reuse` names backend state to reuse. `Unshare` treats it as the directory - that holds a persistent upper and work layer. A backend without resume - ignores it and returns `Fresh`. +- `reuse` carries the backend's persistent overlay upper and work paths + (`ReuseState`). A backend without resume ignores it and returns `Fresh`. - `skip_dirs` lists directory names the backend may omit during a copy. `stage_tree` fills it with the VCS names. - `PutOutcome::Resumed` tells the caller that the previous attempt's build @@ -273,31 +272,41 @@ depends on host-side overlay upperdirs. ### 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`, -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 -pub struct UnshareSpec { - pub root: PathBuf, - pub series: String, - pub arch: Option, - pub mirror: Option, - pub ccache: Option, - pub share_apt_cache: bool, - pub teardown: Teardown, -} +impl Unshare { + pub(crate) async fn new_with_base( + series: &str, + arch: Option<&str>, + mirror: Option<&str>, + base: Arc, + view: &dyn BuildView, + profiler: &mut BuildProfiler, + ) -> Result>; -pub enum Teardown { - /// Remove the root on success and on failure. - Always, - /// Remove the root on success, keep it after a failure for inspection. - KeepOnFailure, - /// The owner removes the root; the sandbox only unmounts. - Owner, + pub(crate) async fn new_for_session( + session: Session, + series: &str, + arch: Option<&str>, + mirror: Option<&str>, + base: Arc, + view: &dyn BuildView, + keep_upper: bool, + ccache: Option<&Path>, + profiler: &mut BuildProfiler, + ) -> Result>; } ``` +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 `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 @@ -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`, 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 -not a user-selectable backend. +unit tests. It is not a user-selectable backend. `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 @@ -321,11 +329,12 @@ conformance tests. It does not need changes in `deb/local`, `apt` or ### Construction and selection Each implementation owns its constructor, because each needs different inputs. -`Unshare::create` is async because it downloads and extracts a tarball. -`Host::new` is trivial. `Ecrou::create` will be async. +`Unshare::new_with_base` and `Unshare::new_for_session` are async because they +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 -small `Backend` value to `DebBuildOptions` and a CLI flag, then choosing the +`pkh deb` calls `Unshare::new_with_base` today. Adding the Ecrou backend means +adding a small `Backend` value to `DebBuildOptions` and a CLI flag, then choosing the constructor there. Everything downstream already takes `Arc`. 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>`. That is a new field with a new meaning, not the old config-resolved `ctx`. -`Unshare::create` stays crate-private while it takes a `&mut BuildProfiler`. -Publishing a constructor for downstream callers means making the profiler -optional in the signature first. +The `Unshare` constructors stay crate-private while they take a +`&mut BuildProfiler` and a `Session`. Publishing a constructor for downstream +callers means making both optional in the signature first. `pkh test` maps its modes to implementations: `local` to `Host`, `chroot` to `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 chroot for inspection and removes it on success, as today. - `cleanup` takes `Option` so it works through - `Arc`. `deb` calls `cleanup(Some(Success))` after a good build - and `cleanup(Some(Failure))` before returning an error; `Drop` and the - interrupt hook call `cleanup(None)`. `Unshare` stores the outcome in an - `AtomicBool` and the first call applies the teardown. + `Arc`. `deb` marks success on the `Unshare` before it drops; + `Drop` and the interrupt hook call `cleanup(None)`. `Unshare` stores the + outcome in an `AtomicBool`. - A build record keeps its metadata and log outside the environment. Dropping a sandbox never touches them. Backend-owned state, such as `/chroot`, 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 `context::current()` default goes away. -After the migration the word does not appear in the code. This document -mentions it only to describe what is removed. No setting, global, driver or -command builder keeps the name. +The build and test APIs no longer expose the word. This document mentions it +only to describe what was removed; no setting, global, driver or command +builder keeps the name. ## Public API changes - `pkh::sandbox::{Sandbox, SandboxExt, BuildCommand, Capture, CommandSpec, 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 `LineSink`. - `pkh::deb::DebBuildOptions` loses `ctx` and `mode`. A later `Backend` value is additive. -- `pkh::apt::sources::{load, save}` and - `pkh::apt::keyring::download_trust_ppa_key` take `&dyn Sandbox`. -- `pkh::apt::keyring::download_cache_keyrings` becomes host-only. The bootstrap - always runs on the host now. +- `pkh::apt::sources::{load, save}` and the keyring helpers take + `Option>`; `None` means a `Host` sandbox. `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`. @@ -415,22 +422,19 @@ src/ staging.rs StageOptions, stage_tree, VCS pruning host.rs Host unshare/ - mod.rs Unshare, UnshareSpec, Teardown, Drop - bootstrap.rs tarball cache, download, extraction - finalize.rs device nodes, /proc, apt cache, ccache shim - overlay.rs overlay mounting, resume state - namespace.rs namespace and pivot scripts, MAPPED_BUILD_ID + mod.rs Unshare, bootstrap, finalize, ccache, apt cache, + teardown + namespace.rs UnshareDriver, path mapping, overlay staging, + namespace and pivot scripts, MAPPED_BUILD_ID ecrou.rs future Ecrou - build_profile.rs Phase, BuildProfiler, moved out of deb ``` -`Phase` and `BuildProfiler` move out of `deb` because `Unshare::create` needs -them and `sandbox` must not depend on `deb`. `pkh::deb::Phase` can be -re-exported for compatibility. +`Phase` and `BuildProfiler` still live in `deb`; moving them to +`build_profile.rs` is the remaining separation between `sandbox` and `deb`. -## 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. 1. `exec: move line capture out of context` adds `src/exec.rs` with `Stream`, @@ -446,13 +450,13 @@ last. `Arc`. The SSH and schroot drivers are not moved. 4. `sandbox: move the chroot bootstrap out of deb` moves the tarball, extraction, finalize, ccache, apt cache and teardown helpers from - `deb/ephemeral.rs`, and folds `EphemeralContextGuard` into `Unshare::create` - and `Drop`. + `deb/ephemeral.rs`, and folds `EphemeralContextGuard` into + `Unshare::new_with_base`/`new_for_session` and `Drop`. 5. `deb: drop the ctx and mode options` removes `DebBuildOptions.ctx`, `DebBuildOptions.mode` and `BuildMode`, and passes the `Arc` explicitly through `deb/local`. 6. `test: make local mode use Host` replaces `Bed::Local(Arc)` with - `Bed::Host` and the trait methods. + `Bed::Local(Arc)` backed by `Host`. 7. `apt,build: take the sandbox explicitly` removes the `Option` parameters and the `context::current()` defaults, and passes `Host` in the 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 backend. The `put` and `stage_tree` API must be settled before `Ecrou`, or the Ecrou backend will not support incremental builds. -3. Trait size. The trait has 11 required methods and one provided capability - method (`is_host`), and every backend implement the required ones. One trait keeps `Arc` simple. If it grows, split +3. Trait size. The trait has 10 required methods and two provided methods + (`is_host`, `cleanup`); every backend implements the required ones. One trait keeps `Arc` simple. If it grows, split it into `CommandRunner` and `FileSystem` supertraits rather than adding optional methods. 4. Per-call cost over a microVM channel. A file read is cheap on the host and a @@ -530,24 +534,17 @@ The commit scopes follow `AGENTS.md`: add `sandbox`, `build_profile` and ## Testing -- Add a conformance suite that takes `&dyn Sandbox` and checks the - contract: run a command, capture its output, read and write a file, list a - directory, stage a tree, copy a file out, create a temporary directory, and - clean up. Run it against `Host` always and against `Unshare` when root and - `unshare` are available. -- A future `Ecrou` runs the same suite. That is the main reason to keep the trait - small and behavior explicit. -- Use `Arc` in a test to catch object-safety regressions. -- Port the existing `context` unit tests: staging strips VCS metadata, copies - dangling symlinks, maps unshare paths, prunes nested VCS directories, and - stages over an overlay upperdir. -- Delete the `ContextManager` tests with the manager. -- Add lifecycle tests: create an `Unshare` over a pre-populated fake root, drop - 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. +- `sandbox::tests::conformance` takes `&dyn Sandbox` and checks the contract: + run a command, capture its output, read and write a file, list a directory, + stage a tree, copy a file out, create a temporary directory, and clean up. + It runs against `Host`. +- `sandbox::unshare::namespace::path_tests` runs the path and staging half + against `UnshareDriver` over a temp root, without namespace privileges. +- A bootstrapped `Unshare` needs root, `unshare` and a tarball download, so its + full command conformance is left to the `pkh deb` and `pkh test` e2e runs. +- The existing staging units moved with the code: VCS metadata is skipped, + dangling symlinks round-trip, unshare paths map below the root, and overlay + mounts prune the lower tree. +- `Host` stays fast and unprivileged, so `build/binary.rs`, `deb/local.rs` and + `apt/sources.rs` unit tests run without a chroot. + diff --git a/src/apt/keyring.rs b/src/apt/keyring.rs index e3311bf..73f050a 100644 --- a/src/apt/keyring.rs +++ b/src/apt/keyring.rs @@ -95,10 +95,10 @@ pub async fn download_cache_keyrings( // Upgrade cache directories created by versions that made them // private: mmdebstrap's unshare-mode hooks cannot read them. } else { - // Remote contexts (e.g. ssh) have no stat/metadata access through - // the sandbox API, so the ownership guard cannot be performed; - // keep the previous best-effort behavior of tightening the - // directory permissions instead (no group/others write). + // Non-host sandboxes have no host-side stat access, so the + // ownership guard cannot be performed; keep the previous + // best-effort behavior of tightening the directory permissions + // instead (no group/others write). } ctx.command("chmod").arg("755").arg(&keyring_dir).status()?; } else { @@ -270,7 +270,7 @@ pub async fn download_trust_ppa_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 // shelling out to curl. let api_url = crate::launchpad::archive_url(ppa_owner, ppa_name); diff --git a/src/build/binary.rs b/src/build/binary.rs index f937f51..db3672e 100644 --- a/src/build/binary.rs +++ b/src/build/binary.rs @@ -4,7 +4,7 @@ //! //! All tree/database access goes through a [`Sandbox`] so the generation can //! run against a build tree living in a local directory, an ephemeral -//! chroot or a remote host. Artifact digests are computed inside the context +//! chroot or a remote host. Artifact digests are computed inside the sandbox //! with coreutils (`md5sum`, `sha1sum`, `sha256sum`, `stat`), keeping the //! flow binary-safe regardless of the transport. @@ -39,7 +39,7 @@ pub struct BinaryMetadataOptions { /// precedence over whatever the host process inherited, so the metadata /// describes the environment the build actually ran in. pub exported_env: BTreeMap, - /// Build architecture (the machine inside the build context). + /// Build architecture (the machine inside the build sandbox). pub build_arch: String, /// Host architecture (the packages' target); equals the build /// architecture except for cross builds. @@ -49,7 +49,7 @@ pub struct BinaryMetadataOptions { /// Generate `__.buildinfo` and `.changes` for a finished /// binary build, consuming `debian/files` from `package_dir` and the /// artifacts sitting in `upload_dir`. Returns both paths (inside the -/// context). +/// sandbox). /// /// Mirrors the observable behavior of `dpkg-genbuildinfo -b` and /// `dpkg-genchanges -b`: sorted `Binary` list, encounter-order `Architecture` @@ -63,7 +63,7 @@ pub fn generate_binary_metadata( opts: &BinaryMetadataOptions, ) -> Result<(PathBuf, PathBuf), Box> { // ------------------------------------------------------------------ - // Metadata sources inside the context + // Metadata sources inside the sandbox // ------------------------------------------------------------------ let changelog_content = ctx.read_file(&package_dir.join("debian/changelog"))?; let mut entries = @@ -216,7 +216,7 @@ pub fn generate_binary_metadata( 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 // 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())?; - // Hash the freshly written .buildinfo inside the context. + // Hash the freshly written .buildinfo inside the sandbox. let buildinfo_hashes = hashes_in_context(ctx, upload_dir, std::slice::from_ref(&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 -/// context directory `dir`, using coreutils. +/// sandbox directory `dir`, using coreutils. fn hashes_in_context( ctx: &Arc, dir: &Path, @@ -349,10 +349,10 @@ fn hashes_in_context( .arg("%s %n") .args(names) .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() { return Err(format!( - "'stat' failed inside the build context: {}", + "'stat' failed inside the build sandbox: {}", String::from_utf8_lossy(&output.stderr).trim() ) .into()); @@ -381,10 +381,10 @@ fn hashes_in_context( .current_dir(dir) .args(names) .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() { return Err(format!( - "'{tool}' failed inside the build context: {}", + "'{tool}' failed inside the build sandbox: {}", String::from_utf8_lossy(&output.stderr).trim() ) .into()); diff --git a/src/deb/local.rs b/src/deb/local.rs index 5719f6a..3d40ad7 100644 --- a/src/deb/local.rs +++ b/src/deb/local.rs @@ -3,7 +3,7 @@ use crate::exec::LineSink; use crate::logfmt::QuiltClassifier; use crate::report::BuildView; /// 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 log::warn; use std::collections::{BTreeMap, BTreeSet, HashMap}; @@ -94,7 +94,7 @@ pub(crate) fn apply_ccache_env(env: &mut HashMap, enabled: bool, /// 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 /// 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. pub const BUILD_USER: &str = "pkh-build"; @@ -102,7 +102,7 @@ pub const BUILD_USER: &str = "pkh-build"; enum RulesIdentity { /// A nested user namespace maps the chroot's root ownership onto /// [`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 /// build identity, so nothing is chowned and no data moves. Files the /// build writes come out as the invoking user's own host-side. @@ -113,7 +113,7 @@ enum RulesIdentity { 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 /// (`--map-user`), the pivot wrapper working, and the mapping actually /// taken. The probe runs the real wrapper over a `sh` test, so a failure @@ -141,14 +141,14 @@ fn probe_mapped_namespace(ctx: &Arc) -> 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 /// dh_builddeb drops the .debs), the scratch HOME and the shared ccache /// directory. Returns how the rules drop privileges. /// /// 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 -/// to uid 0, so a namespace nested inside the context's, mapping uid 0 +/// files are the invoking user's host-side and the sandbox maps that user +/// 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 /// owner of everything without moving a byte. The fallback creates an /// ordinary chroot user and hands the tree over with a chown — through @@ -167,7 +167,7 @@ fn ensure_build_user( Err(reason) => { log::info!( "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 } @@ -442,7 +442,7 @@ fn hand_over( 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 /// mmdebstrap ones append the entries directly at a fixed, free id. fn create_build_user(ctx: &Arc) -> Result<(), Box> { @@ -498,7 +498,7 @@ fn shlex_quote(value: &str) -> String { /// drops to the build user without touching the environment (a login /// shell would reset it), so the dpkg architecture variables and /// 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>( ctx: &'a Arc, identity: Option<&RulesIdentity>, @@ -542,7 +542,7 @@ pub async fn build( build_resume: bool, ccache: bool, // 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>, // Accumulator of the measured dependency-installation and build // 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()); // 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 { Some(j) => j, None => ctx @@ -588,7 +588,7 @@ pub async fn build( 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 // the chroot - tools keying user config on it (texi2dvi's TeX live // setup, anything writing dotfiles) then fail mid-build. sbuild points @@ -770,7 +770,7 @@ pub async fn build( .status() .map_err(|e| { 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 \ try executing with sudo.", e @@ -778,7 +778,7 @@ pub async fn build( })?; timings.add_deps(started.elapsed()); 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, \ or re-run with RUST_LOG=debug for more details." .into()); @@ -958,7 +958,7 @@ pub async fn build( // Rootless builds: the rules run as an unprivileged user owning the // staged tree. Everything before this point - dependency installation, // 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 // builds ('libfakeroot internal error: payload not recognized' per // LTO/make -j process flood), and a rules chown that fails for the @@ -1231,7 +1231,7 @@ fn next_install_pass( 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 /// build-architecture and `all` candidates; the host-qualified name is /// what surfaces foreign-arch candidates. Names missing from the indexes @@ -1273,8 +1273,8 @@ fn query_candidates( map } -/// Build architecture inside the build context. -fn context_build_arch(ctx: &Arc) -> String { +/// Build architecture inside the build sandbox. +fn sandbox_build_arch(ctx: &Arc) -> String { ctx.command("dpkg") .arg("--print-architecture") .output() @@ -1306,14 +1306,14 @@ fn build_profiles_for(env: &HashMap, ctx: &Arc) -> } } -/// 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 /// installs. -fn load_context_facts(ctx: &Arc, build_arch: &str, host_arch: &str) -> Facts { +fn load_sandbox_facts(ctx: &Arc, 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) => { - log::debug!("cannot read the context dpkg status: {e}"); + log::debug!("cannot read the sandbox dpkg status: {e}"); Facts::new(host_arch, build_arch) } } @@ -1322,7 +1322,7 @@ fn load_context_facts(ctx: &Arc, build_arch: &str, host_arch: &str) /// Resolve and install the Build-* dependencies with dpkg's cross /// semantics: the clauses of `debian/control` are evaluated natively (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. /// /// Build conflicts abort before anything installs. The loop installs one @@ -1349,7 +1349,7 @@ fn install_build_dependencies( enter_phase(view, Phase::InstallingBuildDeps, profiler); 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 control_content = ctx @@ -1416,7 +1416,7 @@ fn install_build_dependencies( let mut cursors = vec![0usize; clauses.len()]; 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 // 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 -/// `debian/files`, returning their paths inside the build context +/// `debian/files`, returning their paths inside the build sandbox /// (`/`, dh_builddeb's `..`: the package /// directory's parent). `debian/files` is the canonical record of /// 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, -/// inside the build context. +/// inside the build sandbox. fn generate_upload_metadata( package_dir: &str, upload_dir: &str, @@ -1558,7 +1558,7 @@ fn generate_upload_metadata( env: &HashMap, ctx: &Arc, ) -> Result<(PathBuf, PathBuf), Box> { - // Build architecture: the machine inside the build context. + // Build architecture: the machine inside the build sandbox. let build_arch = ctx .command("dpkg") .arg("--print-architecture") @@ -1574,7 +1574,7 @@ fn generate_upload_metadata( 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. let vendor = ctx .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..."); let status = cap( ctx.command("apt-get") @@ -1781,7 +1781,7 @@ fn apply_quilt_patches( } /// 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 /// line whose trimmed content — after stripping a leading `--` long-option /// 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) let pkg_path = Path::new(pkg); 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 chroot_path = 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 - /// 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. #[test] - fn detector_on_a_real_tree_through_the_context() { + fn detector_on_a_real_tree_through_the_sandbox() { let ctx: Arc = Arc::new(Host::new()); let dir = tempfile::tempdir().unwrap(); diff --git a/src/deb/mod.rs b/src/deb/mod.rs index f1183bf..49c943a 100644 --- a/src/deb/mod.rs +++ b/src/deb/mod.rs @@ -217,7 +217,7 @@ pub struct DebBuildOptions<'a> { /// (.deb paths, archive names or PPA packages). pub inject: Vec, /// Parallel build jobs; defaults to the core count available in the - /// build context. + /// build sandbox. pub jobs: Option, /// Incremental request (`pkh deb --incremental []`): which /// 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, }); - // Create an ephemeral unshare context for all Local builds. It is kept in - // this scope so it outlives the guarded section below and is only dropped - // once the live view has been cleared. + // Create the build's unshare sandbox. It stays in this scope so it + // outlives the guarded section below and is only dropped once the live + // view has been cleared. // // Every build runs in its own record under the sessions directory // (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 // raw lines are written by a terminal sink instead, and --verbose // 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, std::io::Error>> = session.as_ref().map(|s| { session::RecordLogSink::new( @@ -547,7 +547,7 @@ async fn build_binary_package_impl( )) } else { Some(Arc::new( - Unshare::new_with_context( + Unshare::new_with_base( series, chroot_arch, mirror_arg, @@ -559,11 +559,9 @@ async fn build_binary_package_impl( )) }; - // Determine the build context explicitly: for Local builds it is the - // ephemeral context the guard just created (taken from the guard itself, - // never from the process-global, which concurrent builds may have - // re-pointed at their own chroot); otherwise the base context is used - // directly. + // The build runs in the unshare sandbox the guard created, taken from + // the guard itself rather than any global that concurrent builds could + // re-point at their own chroot. let build_ctx: Arc = match guard.as_ref() { Some(g) => Arc::clone(g) as Arc, None => base_ctx.clone(), @@ -704,7 +702,7 @@ async fn build_binary_package_impl( session.as_ref(), build_resume, 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. Some(local::BUILD_USER), &mut timings, @@ -1060,9 +1058,9 @@ pub(crate) fn find_package_directory( let entries = ctx.list_files(package_parent)?; let mut found_dirs = Vec::new(); for entry in entries { - // list_files yields context-relative paths (e.g. rooted inside - // the chroot for an unshare context): classify through the - // context, a host-side stat would miss every entry. + // list_files yields sandbox-relative paths (e.g. rooted inside + // the chroot for an unshare sandbox): classify through the + // sandbox, a host-side stat would miss every entry. let is_dir = ctx.is_dir(&entry)?; log::debug!(" - {}", entry.display()); 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_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)? { return Err(format!("Could not find .dsc file at {}", dsc_path.display()).into()); } @@ -1231,24 +1229,23 @@ mod tests { assert!(profiler.finish().is_empty()); } - /// An unshare context mapped over `chroot_root`, parented on a local - /// context like the ephemeral build contexts are: exists/list_files/ - /// is_dir answer through the path mapping, no namespace privileges - /// needed. - fn unshare_test_context(chroot_root: &Path) -> Arc { + /// An unshare sandbox mapped over `chroot_root` on a host base: + /// exists/list_files/is_dir answer through the path mapping, no + /// namespace privileges needed. + fn unshare_test_sandbox(chroot_root: &Path) -> Arc { Arc::new(crate::sandbox::unshare::UnshareDriver::new( chroot_root.to_path_buf(), Arc::new(Host::new()), )) } - /// The staging-area listing must classify entries through the context: - /// an unshare context returns build-root-relative paths that a host-side + /// The staging-area listing must classify entries through the sandbox: + /// 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 /// used to silently empty the 'Found directories' list of the search /// failure message — and with it every hint about the actual layout. #[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(); // Staged tree holding a single nested checkout whose name matches // 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"); 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( Path::new("/tmp/pkh-build-1/j-42"), "bc", @@ -1269,7 +1266,7 @@ mod tests { let message = err.to_string(); assert!( 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"); 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( Path::new("/tmp/pkh-build-1/tree"), "bc", @@ -1307,7 +1304,7 @@ mod tests { // /- 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( Path::new("/tmp/pkh-build-1/checkout"), "bc", @@ -1427,7 +1424,7 @@ mod tests { } // 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] #[test_log::test] async fn test_deb_hello_ubuntu_end_to_end() { diff --git a/src/main.rs b/src/main.rs index 37a077f..348f190 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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)) .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)) - .arg(arg!(-j --jobs "Number of parallel build jobs (default: number of CPUs available in the build context)").required(false)) + .arg(arg!(-j --jobs "Number of parallel build jobs (default: number of CPUs available in the build sandbox)").required(false)) .arg( clap::Arg::new("incremental") .long("incremental") diff --git a/src/prune.rs b/src/prune.rs index d49e7a3..0310357 100644 --- a/src/prune.rs +++ b/src/prune.rs @@ -4,7 +4,7 @@ //! //! - **Residual build/chroot directories** under the system temp directory, //! named `pkh-` (or `pkh--` 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 //! may contain root-owned device nodes (created via `mknod`), a //! bind-mounted `/proc` and overlay filesystems, so they require careful diff --git a/src/put/ssh.rs b/src/put/ssh.rs index 7f62371..74d22ef 100644 --- a/src/put/ssh.rs +++ b/src/put/ssh.rs @@ -11,7 +11,7 @@ //! server fails the upload instead of hanging it forever. //! //! 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::fs; diff --git a/src/sandbox/host.rs b/src/sandbox/host.rs index a12390e..e0efdf4 100644 --- a/src/sandbox/host.rs +++ b/src/sandbox/host.rs @@ -11,7 +11,7 @@ use super::{BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcom /// /// Commands run with [`std::process::Command`], files use [`std::fs`], and /// 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)] pub struct Host; diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index c8dcd7a..d7acf46 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -215,7 +215,7 @@ impl<'a> BuildCommand<'a> { self.sandbox .run(&self.spec, capture) .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. @@ -227,7 +227,7 @@ impl<'a> BuildCommand<'a> { stdout: execution.stdout, 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. -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 { io::Error::new( e.kind(), diff --git a/src/sandbox/unshare/mod.rs b/src/sandbox/unshare/mod.rs index ffc65cf..9470a61 100644 --- a/src/sandbox/unshare/mod.rs +++ b/src/sandbox/unshare/mod.rs @@ -26,7 +26,7 @@ use xz2::read::XzDecoder; // Interrupt-time cleanup // // 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 // freshly bootstrapped chroot under /tmp together with its bind-mounted // /proc and any overlayfs mounts. @@ -51,10 +51,10 @@ fn sigint_cleanup_chroot(chroot_path: &Path) { /// interrupt included. /// /// Unlike [`Unshare::drop`], this deliberately does NOT go -/// through the context manager, the ephemeral context's driver (whose -/// `cleanup()` unmounts the tracked overlays) or the base context's -/// command builder: interrupt-time hooks must be self-contained, and -/// those machineries may be mid-mutation on the interrupted thread. +/// through the sandbox's driver (whose `cleanup()` unmounts the tracked +/// overlays) or the base sandbox's command builder: interrupt-time hooks +/// must be self-contained, and those machineries may be mid-mutation on +/// the interrupted thread. /// 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 @@ -478,8 +478,8 @@ fn unescape_mount_field(field: &str) -> String { String::from_utf8_lossy(&out).into_owned() } -/// An ephemeral unshare context guard that creates and manages a temporary chroot environment -/// for building packages with unshare permissions. +/// An ephemeral unshare sandbox that creates and manages a temporary chroot +/// environment for building packages with unshare permissions. /// /// In session mode ([`Unshare::new_for_session`]) the chroot /// 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 /// for `--incremental` runs (`keep_upper`). pub struct Unshare { - /// The ephemeral build context this guard created (an unshare context - /// bound to the chroot, parented on the base context). Held explicitly so - /// cleanup and the build itself never depend on the process-global - /// "current" context, which concurrent builds swap for their own. + /// The chroot driver this sandbox owns: path mapping, namespace + /// wrappers and overlay staging. driver: UnshareDriver, chroot_path: PathBuf, build_succeeded: AtomicBool, @@ -513,16 +511,16 @@ pub struct 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 /// * `series` - The distribution series (e.g., "noble", "sid") /// * `arch` - Optional target architecture. If provided and different from host, /// 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 /// 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, arch: Option<&str>, mirror: Option<&str>, @@ -536,15 +534,15 @@ impl Unshare { .await } - /// Create the ephemeral build context inside `session`'s chroot. + /// Create the unshare sandbox inside `session`'s chroot. /// /// # Arguments /// * `session` - The build record owning the chroot (locked by the /// caller) /// * `series` - The distribution series (e.g., "noble", "sid") /// * `arch` - Optional target architecture, as for - /// [`Unshare::new_with_context`] - /// * `base_ctx` - The base context to use for chroot work + /// [`Unshare::new_with_base`] + /// * `base_ctx` - The base sandbox used for chroot work /// * `keep_upper` - Retain the record's staged tree after the build /// (`pkh deb --incremental`); a plain run's record keeps metadata /// and log only @@ -613,7 +611,7 @@ impl Unshare { // the user hits Ctrl-C during bootstrap or the build itself, the // interrupt watchdog unmounts the chroot's mounts through this hook // (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`. // For remote or nested bases the chroot lives elsewhere, and // leftovers stay handled by `pkh prune` as before. @@ -635,7 +633,7 @@ impl Unshare { Some(crate::interrupt::register_cleanup_hook(hook)) } else { 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() ); None @@ -1266,9 +1264,9 @@ impl Drop for Unshare { 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 // handle another concurrent build may have swapped. The actual // unmount commands run through the base sandbox. diff --git a/src/sandbox/unshare/namespace.rs b/src/sandbox/unshare/namespace.rs index 3b14bc1..b68470d 100644 --- a/src/sandbox/unshare/namespace.rs +++ b/src/sandbox/unshare/namespace.rs @@ -22,7 +22,7 @@ pub(crate) const MAPPED_BUILD_ID: u32 = 65536; const _: () = assert!( 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`]. diff --git a/src/test/bed.rs b/src/test/bed.rs index b28e368..ca8fd6e 100644 --- a/src/test/bed.rs +++ b/src/test/bed.rs @@ -38,7 +38,7 @@ impl Bed { // foreign-arch chroot, so the native case shares deb's // unsuffixed `-buildd.tar.xz` cache entry. 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, chroot_arch.as_deref(), 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 { match self { Bed::Chroot(guard) => Arc::clone(guard) as Arc, @@ -75,8 +75,8 @@ impl Bed { } /// Whether root-requiring tests can run: always inside a chroot - /// (commands run as mapped root), on the local context only when the - /// context itself runs as root. + /// (commands run as mapped root), on the host only when the sandbox + /// itself runs as root. pub(crate) fn supports_root(&self) -> bool { match self { Bed::Chroot(_) => true, diff --git a/src/test/mod.rs b/src/test/mod.rs index 7112440..d159bda 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -247,7 +247,7 @@ pub async fn run(opts: TestOptions<'_>) -> Result, - local_context: bool, + host_sandbox: bool, view: &dyn BuildView, ) -> Result<(), Box> { let mut sources = crate::apt::sources::load(Some(ctx.clone()))?; @@ -539,7 +539,7 @@ async fn configure_testbed( if !status.success() { return Err(format!( "apt-get update failed inside the testbed{}", - if local_context { + if host_sandbox { " (a local run needs root to install packages: \ use sudo, or the default chroot mode)" } else { @@ -781,8 +781,8 @@ mod tests { return; // not requested: nothing to compare }; - // pkh's native runner, on the host context (autopkgtest's null - // runner equivalent). + // pkh's native runner, on the host (autopkgtest's null runner + // equivalent). let rt = tokio::runtime::Runtime::new().unwrap(); let native = rt.block_on(crate::test::run(TestOptions { tree: Some(tree.clone()), diff --git a/src/test/options.rs b/src/test/options.rs index ec98c10..d7845f8 100644 --- a/src/test/options.rs +++ b/src/test/options.rs @@ -6,7 +6,7 @@ use std::path::PathBuf; /// Testbed mode: where the tests run. /// /// 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 /// running on the host is the explicit choice. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] diff --git a/src/test/runner.rs b/src/test/runner.rs index bd2c3f4..b7304e5 100644 --- a/src/test/runner.rs +++ b/src/test/runner.rs @@ -29,12 +29,12 @@ use crate::test::outcome::{TestOutcome, Verdict}; const KILL_AFTER_SECS: u64 = 15; /// Everything one test run needs from the orchestration. -pub(crate) struct RunContext<'a> { - /// The testbed context. +pub(crate) struct RunEnv<'a> { + /// The testbed sandbox. pub ctx: Arc, - /// Context-side path of the staged source tree. + /// Sandbox-side path of the staged source tree. pub tree: String, - /// Context-side scratch root (temporary directories, artifacts). + /// Sandbox-side scratch root (temporary directories, artifacts). pub staging_root: String, /// The testbed architecture. pub arch: String, @@ -61,7 +61,7 @@ pub(crate) struct RunContext<'a> { /// Run the tests in declaration order, filtered by the caller's /// selection, and return one outcome per selected test. pub(crate) fn run_tests( - run: &RunContext<'_>, + run: &RunEnv<'_>, tests: &[Test], only: &[String], skipped: &[String], @@ -158,7 +158,7 @@ pub(crate) fn restriction_skip( } /// 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(); if let Some(reason) = restriction_skip(test, run.supports_root, run.arch != run.host_arch) { 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. -fn execute(run: &RunContext<'_>, test: &Test) -> (RawRun, Duration) { +fn execute(run: &RunEnv<'_>, test: &Test) -> (RawRun, Duration) { let started = Instant::now(); // 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. -fn install_test_deps(run: &RunContext<'_>, test: &Test) -> Result<(), String> { +fn install_test_deps(run: &RunEnv<'_>, test: &Test) -> Result<(), String> { let specs = expand_depends( test.depends.as_deref(), &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 /// autopkgtest build, with the nocheck profile — the tests need the /// 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(); env.insert("DEB_BUILD_OPTIONS".to_string(), "nocheck".to_string()); 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. -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"); format!("{}/{base}/{script}", run.tree) } /// Retrieve a test's artifacts directory from the testbed into the run's /// 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!( "{}/artifacts/{}", run.staging_root, @@ -369,7 +369,7 @@ fn retrieve_artifacts(run: &RunContext<'_>, test_name: &str) { } /// 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 .join("artifacts") .join(safe_name(test_name))