sandbox,deb,test: fold the unshare driver into Unshare
Unshare now owns its chroot driver directly: command wrappers, path mapping, overlay staging and teardown no longer go through Context or ContextDriver. Host is the base for every bootstrap, and deb and test pass Arc<dyn Sandbox> end to end. apt, build and the unit tests use Host instead of a local Context. The context module, its manager, drivers and persisted configuration are deleted. test_support::wrap_driver is replaced by the exec test sink.
This commit is contained in:
1 parent
7c689e8c39
commit
d5bf2ceeb3
27 files changed
+507
-3286
No files matched your search
@@ -234,7 +234,7 @@ native runner on a pkh testbed, and reports one verdict per test:
|
||||
|
||||
```
|
||||
pkh test # test this tree: builds it first if needed
|
||||
pkh test --mode local # on the current context, no isolation
|
||||
pkh test --mode local # on the host, no isolation
|
||||
pkh test --mode vm --image img.qcow2 # in a VM, via autopkgtest
|
||||
pkh test --json --fail-on skip # CI-shaped
|
||||
pkh test --list-tests # what does this package test?
|
||||
|
||||
+4
-4
@@ -51,7 +51,7 @@ struct LaunchpadPpaResponse {
|
||||
/// releases since sid needs keys from all recent releases.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `ctx` - Optional context to use
|
||||
/// * `ctx` - Optional sandbox to use
|
||||
/// * `series` - The distribution series (e.g., "noble", "sid")
|
||||
///
|
||||
/// # Returns
|
||||
@@ -96,7 +96,7 @@ pub async fn download_cache_keyrings(
|
||||
// private: mmdebstrap's unshare-mode hooks cannot read them.
|
||||
} else {
|
||||
// Remote contexts (e.g. ssh) have no stat/metadata access through
|
||||
// the context API, so the ownership guard cannot be performed;
|
||||
// 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).
|
||||
}
|
||||
@@ -234,11 +234,11 @@ fn validate_keyring_dir(dir_uid: u32, mode: u32, euid: u32) -> Result<(), String
|
||||
///
|
||||
/// The signing key fingerprint is looked up through the shared HTTP client;
|
||||
/// the key itself is fetched from the keyserver with curl through the
|
||||
/// context, because the key file must land in the context's filesystem
|
||||
/// sandbox, because the key file must land in the sandbox's filesystem
|
||||
/// (which may be remote).
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `ctx` - Optional context to use
|
||||
/// * `ctx` - Optional sandbox to use
|
||||
/// * `ppa_owner` - PPA owner (username)
|
||||
/// * `ppa_name` - PPA name
|
||||
///
|
||||
|
||||
+5
-5
@@ -59,7 +59,7 @@ pub enum SourceFormat {
|
||||
/// File a source entry was loaded from
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SourceOrigin {
|
||||
/// Path of the origin file, inside the context
|
||||
/// Path of the origin file, inside the sandbox
|
||||
pub path: PathBuf,
|
||||
/// Format of the origin file
|
||||
pub format: SourceFormat,
|
||||
@@ -327,7 +327,7 @@ pub fn parse_legacy(data: &str) -> Vec<SourceEntry> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Load sources from context (or current context by default)
|
||||
/// Load sources from a sandbox (or a host sandbox by default)
|
||||
///
|
||||
/// Reads the deb822 distro sources (ubuntu.sources or debian.sources), the
|
||||
/// legacy '/etc/apt/sources.list' and the pkh-owned added-sources file when
|
||||
@@ -372,7 +372,7 @@ pub fn load(ctx: Option<Arc<dyn Sandbox>>) -> Result<Vec<SourceEntry>, Box<dyn E
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
/// Save sources back to the context
|
||||
/// Save sources back to the sandbox
|
||||
///
|
||||
/// Each entry is written back to the file it was loaded from
|
||||
/// ([`SourceEntry::origin`]), in that file's format. Entries without an
|
||||
@@ -491,7 +491,7 @@ fn backup_path(path: &Path) -> PathBuf {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::context::{Context, ContextConfig};
|
||||
use crate::sandbox::Host;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_parse_deb822() {
|
||||
@@ -731,7 +731,7 @@ mod tests {
|
||||
"Types: deb\nURIs: http://a\nSuites: noble\nComponents: main\n",
|
||||
)
|
||||
.unwrap();
|
||||
let ctx = Arc::new(Context::new(ContextConfig::Local).unwrap());
|
||||
let ctx = Arc::new(Host::new());
|
||||
|
||||
let origin = SourceOrigin {
|
||||
path: path.clone(),
|
||||
|
||||
+3
-9
@@ -488,9 +488,7 @@ Description: test package
|
||||
std::fs::write(base.path().join("hello_1.0-1+b1_all.deb"), "deb payload")
|
||||
.expect("write deb");
|
||||
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"),
|
||||
);
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(crate::sandbox::Host::new());
|
||||
let opts = BinaryMetadataOptions {
|
||||
profiles: Vec::new(),
|
||||
vendor: "debian".to_string(),
|
||||
@@ -547,9 +545,7 @@ Description: test package
|
||||
.expect("chmod files");
|
||||
}
|
||||
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"),
|
||||
);
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(crate::sandbox::Host::new());
|
||||
let opts = BinaryMetadataOptions {
|
||||
profiles: Vec::new(),
|
||||
vendor: "debian".to_string(),
|
||||
@@ -622,9 +618,7 @@ Description: test package
|
||||
std::fs::write(base.path().join("hello_1.0.orig.tar.xz"), "tarball bytes")
|
||||
.expect("write previous tarball");
|
||||
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local).expect("context"),
|
||||
);
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(crate::sandbox::Host::new());
|
||||
let opts = BinaryMetadataOptions {
|
||||
profiles: Vec::new(),
|
||||
vendor: "debian".to_string(),
|
||||
|
||||
+2
-3
@@ -2005,9 +2005,8 @@ Provides: virtual-thing (= 2.0), plain-virtual
|
||||
assert!(status.success(), "debian/rules {target} failed");
|
||||
}
|
||||
|
||||
let ctx: std::sync::Arc<dyn crate::sandbox::Sandbox> = std::sync::Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local).unwrap(),
|
||||
);
|
||||
let ctx: std::sync::Arc<dyn crate::sandbox::Sandbox> =
|
||||
std::sync::Arc::new(crate::sandbox::Host::new());
|
||||
let native_arch = crate::debian::arch::native().unwrap_or_else(|_| "amd64".into());
|
||||
let opts = crate::build::binary::BinaryMetadataOptions {
|
||||
profiles,
|
||||
|
||||
+5
-7
@@ -1,12 +1,11 @@
|
||||
//! User settings: the optional `config.yml` in the pkh configuration
|
||||
//! directory (the same `~/.config/pkh/` that holds `contexts.json`),
|
||||
//! and their defaults.
|
||||
//! directory, and their defaults.
|
||||
//!
|
||||
//! A missing file carries the defaults — the file is written only when
|
||||
//! a user creates it, never generated. A file that cannot be read or
|
||||
//! parsed must not take the whole program down: like the context
|
||||
//! configuration, it is backed up to `<path>.bak` (best effort) so a
|
||||
//! later save cannot silently destroy it, and the defaults apply. Every
|
||||
//! parsed must not take the whole program down: it is backed up to
|
||||
//! `<path>.bak` (best effort) so a later save cannot silently destroy it,
|
||||
//! and the defaults apply. Every
|
||||
//! struct level is individually defaulted (`#[serde(default)]`), so any
|
||||
//! hand-written file may carry a subset of the settings:
|
||||
//!
|
||||
@@ -19,8 +18,7 @@
|
||||
use serde::Deserialize;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The pkh configuration directory (the one holding `contexts.json`
|
||||
/// and `config.yml`).
|
||||
/// The pkh configuration directory (holding `config.yml`).
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("com", "pkh", "pkh").map(|dirs| dirs.config_dir().to_path_buf())
|
||||
}
|
||||
|
||||
@@ -1,617 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ffi::OsStr;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::exec::LineSink;
|
||||
use crate::sandbox::contextualize_spawn_error;
|
||||
|
||||
use super::local::LocalDriver;
|
||||
use super::schroot::SchrootDriver;
|
||||
use super::ssh::SshDriver;
|
||||
use super::unshare::UnshareDriver;
|
||||
|
||||
/// Outcome of an overlay-aware staging
|
||||
/// ([`ContextDriver::ensure_available_with_overlay`]).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OverlayStaging {
|
||||
/// The staged path as it appears inside the context.
|
||||
pub path: PathBuf,
|
||||
/// Whether the staging reused the persistent overlay upperdir (build
|
||||
/// artifacts of a previous attempt are visible); `false` means a fresh
|
||||
/// copy was staged instead.
|
||||
pub overlay: bool,
|
||||
}
|
||||
|
||||
/// Marker environment value (set to `1`) flagging a command as a rules
|
||||
/// step of a rootless build: unshare-based contexts then enter the chroot
|
||||
/// by pivoting and drop into a nested user namespace mapping the chroot's
|
||||
/// root ownership onto the build identity ([`MAPPED_BUILD_ID`]), instead
|
||||
/// of chrooting into the namespace's root — so the staged tree is already
|
||||
/// owned and no chown is needed. See `crate::deb::local`, which sets it.
|
||||
pub(crate) const MAPPED_IDENTITY_ENV: &str = "PKH_MAPPED_IDENTITY";
|
||||
|
||||
/// The build identity inside the nested namespace of a rootless build:
|
||||
/// the namespace maps the chroot's root onto this id, and the chroot's
|
||||
/// passwd/group entries carry it, so `getpwuid` resolves the identity for
|
||||
/// the build tools. It must stay outside the context namespace's own
|
||||
/// mapping (which covers 0..=65535), so the two identities never alias.
|
||||
pub(crate) const MAPPED_BUILD_ID: u32 = 65536;
|
||||
|
||||
const _: () = assert!(
|
||||
MAPPED_BUILD_ID > 65535,
|
||||
"the mapped identity must not alias a context-namespace uid"
|
||||
);
|
||||
|
||||
/// A ContextDriver is the interface for the logic happening inside a context
|
||||
pub trait ContextDriver {
|
||||
fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf>;
|
||||
/// Stage `src` at `dest_root` over the given persistent overlay
|
||||
/// upperdir/workdir (host-side paths), for resumable build sessions.
|
||||
///
|
||||
/// The default implementation rejects the request; drivers that cannot
|
||||
/// overlay-mount fall back to a plain copy in their caller.
|
||||
fn ensure_available_with_overlay(
|
||||
&self,
|
||||
_src: &Path,
|
||||
_dest_root: &str,
|
||||
_upper: &Path,
|
||||
_work: &Path,
|
||||
) -> io::Result<OverlayStaging> {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"overlay staging is not supported by this context driver",
|
||||
))
|
||||
}
|
||||
fn retrieve_path(&self, src: &Path, dest: &Path) -> io::Result<()>;
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>>;
|
||||
fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::ExitStatus>;
|
||||
/// Run a command, capturing its output line by line into `sink`
|
||||
///
|
||||
/// Implementations should pipe the subprocess standard streams and forward
|
||||
/// each decoded line to `sink` instead of letting it inherit the terminal.
|
||||
/// The default implementation ignores the sink and behaves like
|
||||
/// [`ContextDriver::run`].
|
||||
fn run_captured(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
sink: Arc<dyn LineSink>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
let _ = sink;
|
||||
self.run(program, args, env, cwd)
|
||||
}
|
||||
fn run_output(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::Output>;
|
||||
fn create_temp_dir(&self) -> io::Result<String>;
|
||||
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()>;
|
||||
fn read_file(&self, path: &Path) -> io::Result<String>;
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()>;
|
||||
fn exists(&self, path: &Path) -> io::Result<bool>;
|
||||
/// Check if a path is a directory inside the context
|
||||
///
|
||||
/// Distinct from [`ContextDriver::exists`] because paths returned by
|
||||
/// [`ContextDriver::list_files`] are context-relative and can only be
|
||||
/// classified through the context, never with a host-side stat.
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool>;
|
||||
|
||||
/// Clean up any resources held by the driver (e.g. unmount overlay filesystems).
|
||||
/// Called before the chroot directory is removed.
|
||||
fn cleanup(&self) -> io::Result<()> {
|
||||
Ok(()) // default no-op
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents an execution environment (Local or via SSH).
|
||||
///
|
||||
/// This is the data model that configuration files store. It defines *where* operations happen.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(tag = "type")]
|
||||
#[derive(Default)]
|
||||
pub enum ContextConfig {
|
||||
/// Local context: actions executed locally
|
||||
#[serde(rename = "local")]
|
||||
#[default]
|
||||
Local,
|
||||
/// SSH context: actions over an SSH connection
|
||||
#[serde(rename = "ssh")]
|
||||
Ssh {
|
||||
/// Host for the SSH connection
|
||||
host: String,
|
||||
/// User for the SSH connection
|
||||
user: Option<String>,
|
||||
/// TCP port for the SSH connection
|
||||
port: Option<u16>,
|
||||
},
|
||||
/// Schroot context: using `schroot`
|
||||
#[serde(rename = "schroot")]
|
||||
Schroot {
|
||||
/// Name of the schroot
|
||||
name: String,
|
||||
/// Optional parent context for the Schroot context
|
||||
parent: Option<String>,
|
||||
},
|
||||
/// Unshare context: chroot with dropped permissions (using `unshare`)
|
||||
#[serde(rename = "unshare")]
|
||||
Unshare {
|
||||
/// Path to use for chrooting
|
||||
path: String,
|
||||
/// Optional parent context for the Unshare context
|
||||
parent: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ContextConfig {
|
||||
/// Build an SSH context configuration from an endpoint of the form
|
||||
/// `[ssh://][user@]host[:port]`.
|
||||
pub fn from_endpoint(endpoint: &str) -> Result<Self, String> {
|
||||
let re = regex::Regex::new(
|
||||
r"^(?:ssh://)?(?:(?P<user>[^@]+)@)?(?P<host>[^:/]+)(?::(?P<port>\d+))?$",
|
||||
)
|
||||
.expect("valid endpoint regex");
|
||||
let cap = re.captures(endpoint).ok_or_else(|| {
|
||||
format!("Invalid endpoint format: '{endpoint}'. Expected [ssh://][user@]host[:port]")
|
||||
})?;
|
||||
let host = cap.name("host").unwrap().as_str().to_string();
|
||||
let user = cap.name("user").map(|m| m.as_str().to_string());
|
||||
let port = cap
|
||||
.name("port")
|
||||
.map(|m| m.as_str().parse::<u16>())
|
||||
.transpose()
|
||||
.map_err(|_| "Invalid port number".to_string())?;
|
||||
Ok(ContextConfig::Ssh { host, user, port })
|
||||
}
|
||||
}
|
||||
|
||||
/// A context, allowing to run commands, read and write files, etc
|
||||
pub struct Context {
|
||||
/// Configuration for the context
|
||||
pub config: ContextConfig,
|
||||
/// Parent context for the context
|
||||
///
|
||||
/// For example, you could have a chroot context over an ssh connection
|
||||
pub parent: Option<Arc<Context>>,
|
||||
/// ContextDriver for the context, implementing the logic for actions
|
||||
driver: Mutex<Option<Box<dyn ContextDriver + Send + Sync>>>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
/// Create a context from configuration
|
||||
///
|
||||
/// Parent contexts named in the configuration are resolved through the
|
||||
/// global context manager; a dangling parent name is reported as an
|
||||
/// error instead of panicking.
|
||||
///
|
||||
/// Note that this takes a read lock on the global manager's
|
||||
/// configuration: never call it while holding that lock for writing.
|
||||
/// [`crate::context::ContextManager`] itself goes through
|
||||
/// [`Context::with_lookup`] instead, which takes no locks.
|
||||
pub fn new(config: ContextConfig) -> io::Result<Self> {
|
||||
Self::with_lookup(config, &|name| {
|
||||
crate::context::manager::MANAGER
|
||||
.get_config()
|
||||
.contexts
|
||||
.get(name)
|
||||
.cloned()
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a context from configuration, resolving `parent` context names
|
||||
/// through `lookup` instead of the global context manager.
|
||||
///
|
||||
/// `lookup` must be lock-free: this is what allows
|
||||
/// [`crate::context::ContextManager`] to build contexts while holding
|
||||
/// (or before the very existence of) its configuration lock. Returns an
|
||||
/// error when a referenced parent does not exist or when the parent
|
||||
/// chain contains a cycle.
|
||||
pub(crate) fn with_lookup(
|
||||
config: ContextConfig,
|
||||
lookup: &dyn Fn(&str) -> Option<ContextConfig>,
|
||||
) -> io::Result<Self> {
|
||||
Self::with_lookup_inner(config, lookup, &mut Vec::new())
|
||||
}
|
||||
|
||||
fn with_lookup_inner(
|
||||
config: ContextConfig,
|
||||
lookup: &dyn Fn(&str) -> Option<ContextConfig>,
|
||||
chain: &mut Vec<String>,
|
||||
) -> io::Result<Self> {
|
||||
let parent_name = match &config {
|
||||
ContextConfig::Schroot {
|
||||
parent: Some(parent_name),
|
||||
..
|
||||
}
|
||||
| ContextConfig::Unshare {
|
||||
parent: Some(parent_name),
|
||||
..
|
||||
} => parent_name.clone(),
|
||||
_ => {
|
||||
return Ok(Self {
|
||||
config,
|
||||
parent: None,
|
||||
driver: Mutex::new(None),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if chain.iter().any(|name| name == &parent_name) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("Parent context cycle: '{parent_name}' appears in its own parent chain"),
|
||||
));
|
||||
}
|
||||
let parent_config = lookup(&parent_name).ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("Parent context '{parent_name}' not found"),
|
||||
)
|
||||
})?;
|
||||
chain.push(parent_name);
|
||||
let parent = Self::with_lookup_inner(parent_config, lookup, chain);
|
||||
chain.pop();
|
||||
|
||||
Ok(Self {
|
||||
config,
|
||||
parent: Some(Arc::new(parent?)),
|
||||
driver: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// Create a context with an explicit parent context
|
||||
pub fn with_parent(config: ContextConfig, parent: Arc<Context>) -> Self {
|
||||
Self {
|
||||
config,
|
||||
parent: Some(parent),
|
||||
driver: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a command inside context
|
||||
///
|
||||
/// Build tooling must not inherit the session's locale: dpkg-family
|
||||
/// tools and perl-based packaging scripts change their output (and
|
||||
/// dpkg-buildpackage treats some of it as data) with the environment,
|
||||
/// and a translated or mixed locale leaks host state into builds. The
|
||||
/// C locale is the default; a caller can still override it by setting
|
||||
/// LANG/LC_ALL through [`ContextCommand::envs`] afterwards.
|
||||
pub fn command<S: AsRef<OsStr>>(&self, program: S) -> ContextCommand<'_> {
|
||||
ContextCommand {
|
||||
context: self,
|
||||
program: program.as_ref().to_string_lossy().to_string(),
|
||||
args: Vec::new(),
|
||||
env: vec![
|
||||
("LANG".to_string(), "C".to_string()),
|
||||
("LC_ALL".to_string(), "C".to_string()),
|
||||
],
|
||||
cwd: None,
|
||||
sink: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensures that the source file/directory exists at the destination context.
|
||||
///
|
||||
/// If Local: Returns the absolute path of `src`.
|
||||
/// If Remote: Copies `src` to `dest_root` on the remote and returns the path to the copied entity.
|
||||
pub fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf> {
|
||||
self.driver()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.ensure_available(src, dest_root)
|
||||
}
|
||||
|
||||
/// Stage `src` at `dest_root` reusing the given overlay upperdir and
|
||||
/// workdir (host-side paths), so build artifacts written inside the
|
||||
/// context during a previous attempt survive into this one. Falls back
|
||||
/// to a fresh copy when the driver does not support overlay staging or
|
||||
/// the mount fails (the returned [`OverlayStaging::overlay`] says
|
||||
/// which happened).
|
||||
pub fn ensure_available_with_overlay(
|
||||
&self,
|
||||
src: &Path,
|
||||
dest_root: &str,
|
||||
upper: &Path,
|
||||
work: &Path,
|
||||
) -> io::Result<OverlayStaging> {
|
||||
self.driver()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.ensure_available_with_overlay(src, dest_root, upper, work)
|
||||
}
|
||||
|
||||
/// Create a temp directory inside context
|
||||
pub fn create_temp_dir(&self) -> io::Result<String> {
|
||||
self.driver().as_ref().unwrap().create_temp_dir()
|
||||
}
|
||||
|
||||
/// Retrieve a file or directory from the context to the local filesystem.
|
||||
///
|
||||
/// The `src` path is on the context, `dest` is on the local machine.
|
||||
/// If `src` is a directory, it is copied recursively.
|
||||
pub fn retrieve_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
self.driver().as_ref().unwrap().retrieve_path(src, dest)
|
||||
}
|
||||
|
||||
/// List files in a directory on the context.
|
||||
pub fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
self.driver().as_ref().unwrap().list_files(path)
|
||||
}
|
||||
|
||||
/// Copy a path inside context
|
||||
pub fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
self.driver().as_ref().unwrap().copy_path(src, dest)
|
||||
}
|
||||
|
||||
/// Read a file inside context
|
||||
pub fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
self.driver().as_ref().unwrap().read_file(path)
|
||||
}
|
||||
|
||||
/// Write a file inside context
|
||||
pub fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
self.driver().as_ref().unwrap().write_file(path, content)
|
||||
}
|
||||
|
||||
/// Check if a file or directory exists inside context
|
||||
pub fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
self.driver().as_ref().unwrap().exists(path)
|
||||
}
|
||||
|
||||
/// Check if a path is a directory inside context
|
||||
///
|
||||
/// Paths returned by [`Context::list_files`] are context-relative
|
||||
/// (e.g. rooted inside the chroot for an unshare context): whether they
|
||||
/// are directories can only be decided through the context.
|
||||
pub fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
self.driver().as_ref().unwrap().is_dir(path)
|
||||
}
|
||||
|
||||
/// Clean up any resources held by the driver (e.g. unmount overlay filesystems).
|
||||
/// Called before the chroot directory is removed.
|
||||
pub fn cleanup(&self) -> io::Result<()> {
|
||||
self.driver().as_ref().unwrap().cleanup()
|
||||
}
|
||||
|
||||
/// Create and obtain a specific driver for the context
|
||||
pub fn driver(
|
||||
&self,
|
||||
) -> std::sync::MutexGuard<'_, Option<Box<dyn ContextDriver + Send + Sync>>> {
|
||||
let mut driver_lock = self.driver.lock().unwrap();
|
||||
if driver_lock.is_none() {
|
||||
let driver: Box<dyn ContextDriver + Send + Sync> = match &self.config {
|
||||
ContextConfig::Local => Box::new(LocalDriver),
|
||||
ContextConfig::Ssh { host, user, port } => Box::new(SshDriver {
|
||||
host: host.clone(),
|
||||
user: user.clone(),
|
||||
port: *port,
|
||||
}),
|
||||
ContextConfig::Schroot { name, .. } => Box::new(SchrootDriver {
|
||||
name: name.clone(),
|
||||
session: std::sync::Mutex::new(None),
|
||||
parent: self.parent.clone(),
|
||||
}),
|
||||
ContextConfig::Unshare { path, .. } => Box::new(UnshareDriver {
|
||||
path: path.clone(),
|
||||
parent: self.parent.clone(),
|
||||
overlay_mounts: std::sync::Mutex::new(Vec::new()),
|
||||
}),
|
||||
};
|
||||
// In test runs, commands whose output would inherit the terminal
|
||||
// are captured into the per-test log file instead
|
||||
*driver_lock = Some(crate::test_support::wrap_driver(driver));
|
||||
}
|
||||
driver_lock
|
||||
}
|
||||
|
||||
/// Clone a context
|
||||
pub fn clone_raw(&self) -> Self {
|
||||
Self {
|
||||
config: self.config.clone(),
|
||||
parent: self.parent.clone(),
|
||||
driver: std::sync::Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A builder and executor for commands within a specific `Context`.
|
||||
///
|
||||
/// This struct acts as a high-level facade (API) for command creation. It hides the implementation
|
||||
/// details of *how* the command is actually executed, allowing the user to simple chain arguments
|
||||
/// and call `status()` or `output()`.
|
||||
///
|
||||
/// It delegates the actual work to a `ContextDriver`.
|
||||
pub struct ContextCommand<'a> {
|
||||
context: &'a Context,
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
env: Vec<(String, String)>,
|
||||
cwd: Option<String>,
|
||||
sink: Option<Arc<dyn LineSink>>,
|
||||
}
|
||||
|
||||
impl<'a> ContextCommand<'a> {
|
||||
/// Add an argument to current command
|
||||
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
|
||||
self.args.push(arg.as_ref().to_string_lossy().to_string());
|
||||
self
|
||||
}
|
||||
|
||||
/// Add multiple command arguments
|
||||
pub fn args<I, S>(&mut self, args: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
for arg in args {
|
||||
self.arg(arg);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set environment variable for command
|
||||
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
|
||||
where
|
||||
K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
{
|
||||
self.env.push((
|
||||
key.as_ref().to_string_lossy().to_string(),
|
||||
val.as_ref().to_string_lossy().to_string(),
|
||||
));
|
||||
self
|
||||
}
|
||||
|
||||
/// Set multiple environment variables for command
|
||||
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
|
||||
where
|
||||
I: IntoIterator<Item = (K, V)>,
|
||||
K: AsRef<OsStr>,
|
||||
V: AsRef<OsStr>,
|
||||
{
|
||||
for (key, val) in vars {
|
||||
self.env(key, val);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set current working directory for command
|
||||
pub fn current_dir<P: AsRef<OsStr>>(&mut self, dir: P) -> &mut Self {
|
||||
self.cwd = Some(dir.as_ref().to_string_lossy().to_string());
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable line-wise capture of the command output into `sink`
|
||||
///
|
||||
/// When a sink is set, [`ContextCommand::status`] pipes the subprocess
|
||||
/// standard streams and forwards each decoded line to the sink instead of
|
||||
/// letting the child inherit the terminal. Without a sink, behavior is
|
||||
/// unchanged.
|
||||
pub fn capture(&mut self, sink: Arc<dyn LineSink>) -> &mut Self {
|
||||
self.sink = Some(sink);
|
||||
self
|
||||
}
|
||||
|
||||
/// Run command and obtain exit status
|
||||
pub fn status(&mut self) -> io::Result<std::process::ExitStatus> {
|
||||
let program = self.program.clone();
|
||||
let driver_guard = self.context.driver();
|
||||
let driver = driver_guard.as_ref().unwrap();
|
||||
let result = match &self.sink {
|
||||
Some(sink) => driver.run_captured(
|
||||
&self.program,
|
||||
&self.args,
|
||||
&self.env,
|
||||
self.cwd.as_deref(),
|
||||
sink.clone(),
|
||||
),
|
||||
None => driver.run(&self.program, &self.args, &self.env, self.cwd.as_deref()),
|
||||
};
|
||||
result.map_err(|e| contextualize_spawn_error(&program, e))
|
||||
}
|
||||
|
||||
/// Run command, capturing output
|
||||
pub fn output(&mut self) -> io::Result<std::process::Output> {
|
||||
let program = self.program.clone();
|
||||
self.context
|
||||
.driver()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.run_output(&self.program, &self.args, &self.env, self.cwd.as_deref())
|
||||
.map_err(|e| contextualize_spawn_error(&program, e))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod endpoint_tests {
|
||||
use super::*;
|
||||
|
||||
/// Every accepted endpoint spelling maps to the expected config.
|
||||
#[test]
|
||||
fn from_endpoint_parses_all_spellings() {
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("myhost"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: None,
|
||||
port: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("admin@myhost"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: Some("admin".into()),
|
||||
port: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("myhost:2222"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: None,
|
||||
port: Some(2222),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
ContextConfig::from_endpoint("ssh://admin@myhost:22"),
|
||||
Ok(ContextConfig::Ssh {
|
||||
host: "myhost".into(),
|
||||
user: Some("admin".into()),
|
||||
port: Some(22),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// Non-numeric ports and extra segments are format errors; a
|
||||
/// non-u16 numeric port is a port error.
|
||||
#[test]
|
||||
fn from_endpoint_rejects_malformed_endpoints() {
|
||||
for bad in ["", "a/b/c", "host:notaport"] {
|
||||
let err = ContextConfig::from_endpoint(bad).unwrap_err();
|
||||
assert!(err.contains("Invalid endpoint format"), "{err}");
|
||||
}
|
||||
let err = ContextConfig::from_endpoint("host:99999").unwrap_err();
|
||||
assert_eq!(err, "Invalid port number");
|
||||
}
|
||||
|
||||
/// Commands run in the C locale whatever the session environment
|
||||
/// carries: host locale variables must not leak into builds. An
|
||||
/// explicit caller override still wins.
|
||||
#[test]
|
||||
fn commands_default_to_the_c_locale() {
|
||||
let ctx = Context::new(ContextConfig::Local).unwrap();
|
||||
|
||||
let locale = ctx
|
||||
.command("sh")
|
||||
.arg("-c")
|
||||
.arg("printf '%s' \"${LC_ALL:-unset}:${LANG:-unset}\"")
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout;
|
||||
assert_eq!(String::from_utf8_lossy(&locale), "C:C");
|
||||
|
||||
let locale = ctx
|
||||
.command("sh")
|
||||
.arg("-c")
|
||||
.arg("printf '%s' \"$LC_ALL\"")
|
||||
.env("LC_ALL", "C.UTF-8")
|
||||
.output()
|
||||
.unwrap()
|
||||
.stdout;
|
||||
assert_eq!(String::from_utf8_lossy(&locale), "C.UTF-8");
|
||||
}
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
/// Local context: execute commands locally
|
||||
/// Context driver: Does nothing
|
||||
use super::api::ContextDriver;
|
||||
use crate::exec::{self, LineSink};
|
||||
use std::io;
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
pub struct LocalDriver;
|
||||
|
||||
impl ContextDriver for LocalDriver {
|
||||
fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf> {
|
||||
let dest_root_path = Path::new(dest_root);
|
||||
let dest = dest_root_path.join(src.file_name().unwrap_or(src.as_os_str()));
|
||||
|
||||
if src != dest {
|
||||
// Copy src inside dest_root
|
||||
self.copy_path(src, &dest)?;
|
||||
}
|
||||
dest.canonicalize()
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
// Sub-second precision and an atomic create: two concurrent
|
||||
// contexts racing on the same name must never share a directory,
|
||||
// so the loser of a create falls through to the next attempt
|
||||
// instead of probing for existence first (a probe-then-create
|
||||
// window loses exactly when two callers arrive together).
|
||||
let base_timestamp = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
let work_dir_name = if attempt == 0 {
|
||||
format!("pkh-{base_timestamp}")
|
||||
} else {
|
||||
format!("pkh-{base_timestamp}-{attempt}")
|
||||
};
|
||||
|
||||
let temp_dir_path = std::env::temp_dir().join(&work_dir_name);
|
||||
|
||||
match std::fs::create_dir(&temp_dir_path) {
|
||||
Ok(()) => return Ok(temp_dir_path.to_string_lossy().to_string()),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => attempt += 1,
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn retrieve_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
self.copy_path(src, dest)
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let mut entries = Vec::new();
|
||||
for entry in std::fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
entries.push(entry.path());
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
exec::run(program, args, env, cwd)
|
||||
}
|
||||
|
||||
fn run_captured(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
sink: Arc<dyn LineSink>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
exec::run_captured(program, args, env, cwd, sink)
|
||||
}
|
||||
|
||||
fn run_output(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::Output> {
|
||||
exec::run_output(program, args, env, cwd)
|
||||
}
|
||||
|
||||
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
copy_dir_recursive(src, dest)
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
std::fs::read_to_string(path)
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
std::fs::write(path, content)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(path.exists())
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(path.is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||
// Reproduce symlinks as symlinks rather than following them, so that
|
||||
// dangling/absolute symlinks do not abort the copy.
|
||||
if std::fs::symlink_metadata(src)?.file_type().is_symlink() {
|
||||
let target = std::fs::read_link(src)?;
|
||||
let _ = std::fs::remove_file(dest);
|
||||
return symlink(&target, dest);
|
||||
}
|
||||
|
||||
if src.is_dir() {
|
||||
std::fs::create_dir_all(dest)?;
|
||||
for entry in std::fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
// Never ship VCS metadata into the build tree: its presence
|
||||
// flips autotools 'building from VCS' detection (see
|
||||
// is_vcs_dir_name) and activates maintainer-only regeneration
|
||||
// rules requiring undeclared tools (e.g. help2man).
|
||||
if path.symlink_metadata().map(|m| m.is_dir()).unwrap_or(false)
|
||||
&& super::is_vcs_dir_name(&entry.file_name())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let dest_path = dest.join(entry.file_name());
|
||||
copy_dir_recursive(&path, &dest_path)?;
|
||||
}
|
||||
} else {
|
||||
std::fs::copy(src, dest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Concurrent callers must never share a temporary directory: the
|
||||
/// create is atomic, so a lost race falls through to the next name
|
||||
/// instead of both callers probing the same free name and unpacking
|
||||
/// into the same directory.
|
||||
#[test]
|
||||
fn create_temp_dir_is_unique_under_concurrency() {
|
||||
const CALLERS: usize = 8;
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let handles: Vec<_> = (0..CALLERS)
|
||||
.map(|_| {
|
||||
let tx = tx.clone();
|
||||
std::thread::spawn(move || {
|
||||
let dir = LocalDriver.create_temp_dir().unwrap();
|
||||
tx.send(dir).unwrap();
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for handle in handles {
|
||||
handle.join().unwrap();
|
||||
}
|
||||
drop(tx);
|
||||
|
||||
let mut names: Vec<String> = rx.iter().collect();
|
||||
names.sort();
|
||||
let unique: std::collections::BTreeSet<&String> = names.iter().collect();
|
||||
assert_eq!(names.len(), unique.len(), "duplicate temp dirs: {names:?}");
|
||||
for name in &unique {
|
||||
std::fs::remove_dir(name).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
use directories::ProjectDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use super::api::{Context, ContextConfig};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct Config {
|
||||
pub context: String,
|
||||
pub contexts: HashMap<String, ContextConfig>,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
let mut contexts = HashMap::new();
|
||||
contexts.insert("local".to_string(), ContextConfig::Local);
|
||||
Self {
|
||||
context: "local".to_string(),
|
||||
contexts,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper managing contexts
|
||||
pub struct ContextManager {
|
||||
context: RwLock<Arc<Context>>,
|
||||
config_path: PathBuf,
|
||||
config: RwLock<Config>,
|
||||
}
|
||||
|
||||
pub static MANAGER: std::sync::LazyLock<ContextManager> =
|
||||
std::sync::LazyLock::new(|| ContextManager::new().expect("Cannot setup context manager"));
|
||||
|
||||
impl ContextManager {
|
||||
fn new() -> io::Result<Self> {
|
||||
let proj_dirs = ProjectDirs::from("com", "pkh", "pkh").ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"Could not determine config directory",
|
||||
)
|
||||
})?;
|
||||
let config_dir = proj_dirs.config_dir();
|
||||
fs::create_dir_all(config_dir)?;
|
||||
let config_path = config_dir.join("contexts.json");
|
||||
|
||||
let mut config = Self::load_config(&config_path);
|
||||
|
||||
// Build the initial Context against the freshly loaded map, before
|
||||
// the manager itself exists: resolution must not go through the
|
||||
// global MANAGER here, since a parented current context would
|
||||
// re-enter its own LazyLock initialization.
|
||||
let initial = match Self::make_context(&config.context, &config.contexts) {
|
||||
Ok(context) => context,
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"Cannot build current context '{}' from {}: {e}; falling back to 'local'",
|
||||
config.context,
|
||||
config_path.display()
|
||||
);
|
||||
config.context = "local".to_string();
|
||||
Self::make_context("local", &config.contexts).unwrap_or_else(|e| {
|
||||
// Only possible in a hand-edited configuration without
|
||||
// any 'local' entry; a plain Local context has no parent
|
||||
// and cannot fail to build.
|
||||
log::error!(
|
||||
"'local' context missing from {}: {e}",
|
||||
config_path.display()
|
||||
);
|
||||
Context::new(ContextConfig::Local).expect("Local context cannot fail")
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
context: RwLock::new(Arc::new(initial)),
|
||||
config_path,
|
||||
config: RwLock::new(config),
|
||||
})
|
||||
}
|
||||
|
||||
/// Load the configuration stored at `path`.
|
||||
///
|
||||
/// A missing file yields [`Config::default`]. A file that cannot be read
|
||||
/// or parsed must not take the whole program down: this falls back to
|
||||
/// the default (local-only) configuration and logs an error. Because a
|
||||
/// later [`ContextManager::save`] would otherwise silently overwrite the
|
||||
/// corrupt file and destroy its content, the corrupt file is first
|
||||
/// backed up to `<path>.bak` (best effort).
|
||||
pub(crate) fn load_config(path: &Path) -> Config {
|
||||
if !path.exists() {
|
||||
return Config::default();
|
||||
}
|
||||
let loaded = fs::read_to_string(path).and_then(|content| {
|
||||
serde_json::from_str(&content)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
|
||||
});
|
||||
match loaded {
|
||||
Ok(config) => config,
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"Context configuration {} is corrupt ({e}); using the default (local-only) configuration",
|
||||
path.display()
|
||||
);
|
||||
Self::backup_corrupt_file(path);
|
||||
Config::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Back up a corrupt configuration file (best effort) so a later save
|
||||
/// cannot silently destroy its content.
|
||||
fn backup_corrupt_file(path: &Path) {
|
||||
let mut os = path.as_os_str().to_os_string();
|
||||
os.push(".bak");
|
||||
let backup_path = PathBuf::from(os);
|
||||
match fs::copy(path, &backup_path) {
|
||||
Ok(_) => log::warn!(
|
||||
"Corrupt context configuration backed up to {}",
|
||||
backup_path.display()
|
||||
),
|
||||
Err(e) => log::warn!(
|
||||
"Could not back up corrupt context configuration to {}: {e}",
|
||||
backup_path.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtain current ContextManager configuration
|
||||
pub fn get_config(&self) -> std::sync::RwLockReadGuard<'_, Config> {
|
||||
self.config.read().unwrap()
|
||||
}
|
||||
|
||||
/// Make a ContextManager using a specific configuration path
|
||||
pub fn with_path(path: PathBuf) -> Self {
|
||||
let config = Config::default();
|
||||
Self {
|
||||
// 'local' is always present in Config::default and has no
|
||||
// parent, so this cannot fail.
|
||||
context: RwLock::new(Arc::new(
|
||||
Self::make_context("local", &config.contexts)
|
||||
.expect("default 'local' context cannot fail"),
|
||||
)),
|
||||
config_path: path,
|
||||
config: RwLock::new(config),
|
||||
}
|
||||
}
|
||||
|
||||
/// Save current context configuration to disk
|
||||
pub fn save(&self) -> io::Result<()> {
|
||||
let config = self.config.read().unwrap();
|
||||
let content = serde_json::to_string_pretty(&*config)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
fs::write(&self.config_path, content)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build a [`Context`] for `name` from `contexts`.
|
||||
///
|
||||
/// Lock-free by construction: parent references are resolved against
|
||||
/// `contexts` itself (see [`Context::with_lookup`]), never against the
|
||||
/// manager's configuration lock. This is what keeps [`ContextManager::new`]
|
||||
/// working before the global [`MANAGER`] exists, and what allows callers
|
||||
/// to build contexts without risking a re-entrant read on a lock they
|
||||
/// already hold for writing.
|
||||
fn make_context(name: &str, contexts: &HashMap<String, ContextConfig>) -> io::Result<Context> {
|
||||
let context_config = contexts.get(name).cloned().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("Context '{name}' not found in configuration"),
|
||||
)
|
||||
})?;
|
||||
Context::with_lookup(context_config, &|parent| contexts.get(parent).cloned())
|
||||
}
|
||||
|
||||
/// List contexts from configuration
|
||||
pub fn list_contexts(&self) -> Vec<String> {
|
||||
self.config
|
||||
.read()
|
||||
.unwrap()
|
||||
.contexts
|
||||
.keys()
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Add a context to configuration
|
||||
pub fn add_context(&self, name: &str, config: ContextConfig) -> io::Result<()> {
|
||||
self.config
|
||||
.write()
|
||||
.unwrap()
|
||||
.contexts
|
||||
.insert(name.to_string(), config);
|
||||
self.save()
|
||||
}
|
||||
|
||||
/// Remove context from configuration
|
||||
pub fn remove_context(&self, name: &str) -> io::Result<()> {
|
||||
if name == "local" {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Cannot remove local context",
|
||||
));
|
||||
}
|
||||
// Mutate under the write lock, snapshotting the remaining map when
|
||||
// the removed context was current; the fallback Context is built
|
||||
// after the lock is released (same discipline as `set_current`).
|
||||
let fallback_contexts = {
|
||||
let mut config = self.config.write().unwrap();
|
||||
if config.contexts.remove(name).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if name == config.context {
|
||||
// If we are removing the current context, fallback to local
|
||||
config.context = "local".to_string();
|
||||
Some(config.contexts.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(contexts) = fallback_contexts {
|
||||
self.set_current_ephemeral(Self::make_context("local", &contexts)?);
|
||||
}
|
||||
self.save()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set current context from name (modifying configuration)
|
||||
pub fn set_current(&self, name: &str) -> io::Result<()> {
|
||||
// Snapshot what `make_context` needs and release the lock before
|
||||
// building the Context. Building resolves parent contexts, and this
|
||||
// code path used to hold the config write guard while re-entering
|
||||
// the same lock for a read — a guaranteed deadlock on a
|
||||
// std::sync::RwLock (same-thread write-then-read).
|
||||
let contexts = self.config.read().unwrap().contexts.clone();
|
||||
if !contexts.contains_key(name) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("Context '{name}' not found"),
|
||||
));
|
||||
}
|
||||
let context = Self::make_context(name, &contexts)?;
|
||||
|
||||
// Re-take the write lock briefly to commit. The name may have been
|
||||
// removed between snapshot and commit; report the same NotFound
|
||||
// error instead of persisting a dangling current-context reference.
|
||||
let mut config = self.config.write().unwrap();
|
||||
if !config.contexts.contains_key(name) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("Context '{name}' not found"),
|
||||
));
|
||||
}
|
||||
config.context = name.to_string();
|
||||
drop(config); // Drop write lock before saving
|
||||
self.set_current_ephemeral(context);
|
||||
self.save()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set current context, without modifying configuration
|
||||
///
|
||||
/// Accepts either an owned [`Context`] or an already-shared
|
||||
/// `Arc<Context>`: callers that keep their own handle to the context
|
||||
/// they install (e.g. [`crate::sandbox::Unshare`])
|
||||
/// pass the Arc so they can restore exactly this context afterwards
|
||||
/// instead of relying on whatever happens to be current at that time.
|
||||
pub fn set_current_ephemeral(&self, context: impl Into<Arc<Context>>) {
|
||||
*self.context.write().unwrap() = context.into();
|
||||
}
|
||||
|
||||
/// Obtain current context handle
|
||||
pub fn current(&self) -> Arc<Context> {
|
||||
self.context.read().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Obtain current context name
|
||||
/// Will not work for ephemeral context (obtained from config)
|
||||
pub fn current_name(&self) -> String {
|
||||
self.config.read().unwrap().context.clone()
|
||||
}
|
||||
}
|
||||
@@ -1,427 +0,0 @@
|
||||
mod api;
|
||||
mod local;
|
||||
mod manager;
|
||||
mod sandbox_impl;
|
||||
mod schroot;
|
||||
pub(crate) mod shell;
|
||||
mod ssh;
|
||||
mod unshare;
|
||||
|
||||
pub use crate::exec::{LineSink, Stream};
|
||||
pub use api::{Context, ContextCommand, ContextConfig, OverlayStaging};
|
||||
pub(crate) use api::{MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV};
|
||||
// The driver trait is implementation detail of the context API; it is only
|
||||
// needed crate-internally (test-run capture wrapper), so keep it out of the
|
||||
// public surface (and its documentation requirement).
|
||||
pub(crate) use api::ContextDriver;
|
||||
pub use manager::ContextManager;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Obtain global context manager
|
||||
pub fn manager() -> &'static ContextManager {
|
||||
&manager::MANAGER
|
||||
}
|
||||
|
||||
/// Obtain current context
|
||||
pub fn current() -> Arc<Context> {
|
||||
manager::MANAGER.current()
|
||||
}
|
||||
|
||||
pub(crate) use crate::sandbox::staging::is_vcs_dir_name;
|
||||
|
||||
/// Recursively remove version-control metadata directories below `root`.
|
||||
///
|
||||
/// Used after an overlay mount, where the source tree is exposed verbatim
|
||||
/// and entries cannot be filtered during the copy.
|
||||
pub(crate) fn prune_vcs_dirs(root: &std::path::Path) -> std::io::Result<()> {
|
||||
let mut pending = vec![root.to_path_buf()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
for entry in std::fs::read_dir(&dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
// symlink_metadata: never follow symlinks while pruning.
|
||||
let Ok(meta) = std::fs::symlink_metadata(&path) else {
|
||||
continue;
|
||||
};
|
||||
if meta.is_dir() {
|
||||
if is_vcs_dir_name(&entry.file_name()) {
|
||||
log::debug!("Removing VCS metadata from build tree: {}", path.display());
|
||||
std::fs::remove_dir_all(&path)?;
|
||||
} else {
|
||||
pending.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn test_ensure_available_local() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let src_file = temp_dir.path().join("src.txt");
|
||||
fs::write(&src_file, "local").unwrap();
|
||||
|
||||
let ctx = Context::new(ContextConfig::Local).unwrap();
|
||||
let dest = ctx.ensure_available(&src_file, "/tmp").unwrap();
|
||||
|
||||
// Should return a path that exists and has the same content
|
||||
assert!(dest.exists());
|
||||
let content = fs::read_to_string(&dest).unwrap();
|
||||
assert_eq!(content, "local");
|
||||
|
||||
// The dest should be in the /tmp directory
|
||||
assert!(dest.starts_with("/tmp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_context_manager_crud() {
|
||||
let temp_file = NamedTempFile::new().unwrap();
|
||||
let path = temp_file.path().to_path_buf();
|
||||
|
||||
let mgr = ContextManager::with_path(path.clone());
|
||||
|
||||
// Add
|
||||
let ssh_cfg = ContextConfig::Ssh {
|
||||
host: "10.0.0.1".into(),
|
||||
user: Some("admin".into()),
|
||||
port: Some(2222),
|
||||
};
|
||||
mgr.add_context("myserver", ssh_cfg.clone()).unwrap();
|
||||
|
||||
assert!(mgr.list_contexts().contains(&"myserver".to_string()));
|
||||
|
||||
// List
|
||||
let list = mgr.list_contexts();
|
||||
assert!(list.contains(&"myserver".to_string()));
|
||||
|
||||
// Set Current
|
||||
mgr.set_current("myserver").unwrap();
|
||||
assert_eq!(mgr.current_name(), "myserver".to_string());
|
||||
|
||||
// Remove
|
||||
mgr.remove_context("myserver").unwrap();
|
||||
assert!(!mgr.list_contexts().contains(&"myserver".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_persistence() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let config_path = temp_dir.path().join("contexts.json");
|
||||
|
||||
{
|
||||
let mgr = ContextManager::with_path(config_path.clone());
|
||||
mgr.add_context("persistent", ContextConfig::Local).unwrap();
|
||||
mgr.set_current("persistent").unwrap();
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(&config_path).unwrap();
|
||||
let loaded_config: super::manager::Config = serde_json::from_str(&content).unwrap();
|
||||
|
||||
assert_eq!(loaded_config.context, "persistent".to_string());
|
||||
assert!(loaded_config.contexts.contains_key("persistent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_context_fallback_on_removal() {
|
||||
let temp_file = NamedTempFile::new().unwrap();
|
||||
let path = temp_file.path().to_path_buf();
|
||||
let mgr = ContextManager::with_path(path);
|
||||
|
||||
// 1. Add and set a context
|
||||
mgr.add_context("temp", ContextConfig::Local).unwrap();
|
||||
mgr.set_current("temp").unwrap();
|
||||
assert_eq!(mgr.current_name(), "temp");
|
||||
|
||||
// 2. Remove it
|
||||
mgr.remove_context("temp").unwrap();
|
||||
|
||||
// 3. Should have fallen back to local
|
||||
assert_eq!(mgr.current_name(), "local");
|
||||
assert!(mgr.list_contexts().contains(&"local".to_string()));
|
||||
}
|
||||
|
||||
/// `set_current` on a context whose configuration carries a `parent`
|
||||
/// must complete without deadlocking: building the Context resolves the
|
||||
/// parent chain, which used to re-enter the config lock while
|
||||
/// `set_current` still held it for writing (a guaranteed deadlock on a
|
||||
/// std::sync::RwLock, same-thread write-then-read).
|
||||
#[test]
|
||||
fn test_set_current_parented_context_no_deadlock() {
|
||||
let temp_file = NamedTempFile::new().unwrap();
|
||||
let mgr = Arc::new(ContextManager::with_path(temp_file.path().to_path_buf()));
|
||||
|
||||
mgr.add_context("base", ContextConfig::Local).unwrap();
|
||||
mgr.add_context(
|
||||
"child",
|
||||
ContextConfig::Schroot {
|
||||
name: "testchroot".to_string(),
|
||||
parent: Some("base".to_string()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Run with a timeout so a regression fails fast instead of hanging
|
||||
// the test binary forever.
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let worker = {
|
||||
let mgr = mgr.clone();
|
||||
std::thread::spawn(move || {
|
||||
let result = mgr.set_current("child");
|
||||
tx.send(()).expect("receiver still waiting");
|
||||
result
|
||||
})
|
||||
};
|
||||
match rx.recv_timeout(std::time::Duration::from_secs(30)) {
|
||||
Ok(()) => {}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
|
||||
panic!("set_current() deadlocked building a parented context");
|
||||
}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
|
||||
panic!("set_current() thread panicked before completing");
|
||||
}
|
||||
}
|
||||
worker.join().unwrap().unwrap();
|
||||
assert_eq!(mgr.current_name(), "child");
|
||||
}
|
||||
|
||||
/// A context referencing a missing parent must produce an error, not a
|
||||
/// panic (the parent lookup used to `.expect()`).
|
||||
#[test]
|
||||
fn test_set_current_dangling_parent_errors() {
|
||||
let temp_file = NamedTempFile::new().unwrap();
|
||||
let mgr = ContextManager::with_path(temp_file.path().to_path_buf());
|
||||
mgr.add_context(
|
||||
"orphan",
|
||||
ContextConfig::Unshare {
|
||||
path: "/some/chroot".to_string(),
|
||||
parent: Some("missing".to_string()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let err = mgr.set_current("orphan").unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
|
||||
// Nothing was committed: the current context is unchanged.
|
||||
assert_eq!(mgr.current_name(), "local");
|
||||
}
|
||||
|
||||
/// A parent cycle in a hand-edited configuration must be rejected with
|
||||
/// an error instead of recursing until the stack overflows.
|
||||
#[test]
|
||||
fn test_set_current_parent_cycle_errors() {
|
||||
let temp_file = NamedTempFile::new().unwrap();
|
||||
let mgr = ContextManager::with_path(temp_file.path().to_path_buf());
|
||||
mgr.add_context(
|
||||
"a",
|
||||
ContextConfig::Schroot {
|
||||
name: "schroot-a".to_string(),
|
||||
parent: Some("b".to_string()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
mgr.add_context(
|
||||
"b",
|
||||
ContextConfig::Unshare {
|
||||
path: "/chroot-b".to_string(),
|
||||
parent: Some("a".to_string()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let err = mgr.set_current("a").unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
}
|
||||
|
||||
/// A corrupt contexts.json must not take the manager down:
|
||||
/// `load_config` falls back to the default (local-only) configuration,
|
||||
/// keeps the corrupt file in place and backs it up to contexts.json.bak
|
||||
/// so a later save cannot silently destroy its content.
|
||||
#[test]
|
||||
fn test_load_config_corrupt_file_falls_back_and_backs_up() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let config_path = temp_dir.path().join("contexts.json");
|
||||
let garbage = "{ this is definitely not valid json";
|
||||
fs::write(&config_path, garbage).unwrap();
|
||||
|
||||
let config = ContextManager::load_config(&config_path);
|
||||
|
||||
// Falls back to the default (local-only) configuration...
|
||||
assert_eq!(config.context, "local");
|
||||
assert!(config.contexts.contains_key("local"));
|
||||
|
||||
// ...preserving the corrupt file via the backup, original untouched.
|
||||
let backup_path = temp_dir.path().join("contexts.json.bak");
|
||||
assert_eq!(fs::read_to_string(&backup_path).unwrap(), garbage);
|
||||
assert_eq!(fs::read_to_string(&config_path).unwrap(), garbage);
|
||||
|
||||
// A subsequent save replaces only the original, never the backup.
|
||||
let mgr = ContextManager::with_path(config_path.clone());
|
||||
mgr.add_context("newctx", ContextConfig::Local).unwrap();
|
||||
let rewritten = fs::read_to_string(&config_path).unwrap();
|
||||
serde_json::from_str::<super::manager::Config>(&rewritten).unwrap();
|
||||
assert_eq!(fs::read_to_string(&backup_path).unwrap(), garbage);
|
||||
}
|
||||
|
||||
/// A missing contexts.json yields the default configuration and writes
|
||||
/// nothing (no file, no backup) until an explicit save.
|
||||
#[test]
|
||||
fn test_load_config_missing_file_defaults() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let config_path = temp_dir.path().join("contexts.json");
|
||||
|
||||
let config = ContextManager::load_config(&config_path);
|
||||
|
||||
assert_eq!(config.context, "local");
|
||||
assert!(config.contexts.contains_key("local"));
|
||||
assert!(!config_path.exists());
|
||||
assert!(!temp_dir.path().join("contexts.json.bak").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_context_file_ops() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = Context::new(ContextConfig::Local).unwrap();
|
||||
|
||||
let file_path = temp_dir.path().join("test.txt");
|
||||
let content = "hello world";
|
||||
|
||||
// 1. Write file
|
||||
ctx.write_file(&file_path, content).unwrap();
|
||||
|
||||
// 2. Read file
|
||||
let read_content = ctx.read_file(&file_path).unwrap();
|
||||
assert_eq!(read_content, content);
|
||||
|
||||
// 3. Copy path
|
||||
let dest_path = temp_dir.path().join("test_copy.txt");
|
||||
ctx.copy_path(&file_path, &dest_path).unwrap();
|
||||
let copied_content = ctx.read_file(&dest_path).unwrap();
|
||||
assert_eq!(copied_content, content);
|
||||
|
||||
// 4. Recursive copy
|
||||
let subdir = temp_dir.path().join("subdir");
|
||||
std::fs::create_dir_all(&subdir).unwrap();
|
||||
let subfile = subdir.join("subfile.txt");
|
||||
ctx.write_file(&subfile, "subcontent").unwrap();
|
||||
|
||||
let subdir_copy = temp_dir.path().join("subdir_copy");
|
||||
ctx.copy_path(&subdir, &subdir_copy).unwrap();
|
||||
|
||||
assert!(subdir_copy.exists());
|
||||
assert!(subdir_copy.join("subfile.txt").exists());
|
||||
assert_eq!(
|
||||
ctx.read_file(&subdir_copy.join("subfile.txt")).unwrap(),
|
||||
"subcontent"
|
||||
);
|
||||
}
|
||||
|
||||
/// Copying a tree containing a dangling symlink must reproduce the link
|
||||
/// itself rather than failing to follow it (which previously surfaced as
|
||||
/// a bare "No such file or directory (os error 2)").
|
||||
#[test]
|
||||
fn test_context_copy_preserves_dangling_symlink() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let ctx = Context::new(ContextConfig::Local).unwrap();
|
||||
|
||||
let src_dir = temp_dir.path().join("src");
|
||||
std::fs::create_dir_all(&src_dir).unwrap();
|
||||
// A regular file alongside the symlink, to ensure normal copies still work.
|
||||
std::fs::write(src_dir.join("real.txt"), "data").unwrap();
|
||||
// A dangling symlink pointing to a non-existent target.
|
||||
symlink("/nonexistent/target", src_dir.join("dangling")).unwrap();
|
||||
|
||||
let dest_dir = temp_dir.path().join("dest");
|
||||
ctx.copy_path(&src_dir, &dest_dir).unwrap();
|
||||
|
||||
// The regular file was copied.
|
||||
assert_eq!(ctx.read_file(&dest_dir.join("real.txt")).unwrap(), "data");
|
||||
// The symlink was reproduced as a symlink (not followed).
|
||||
let meta = std::fs::symlink_metadata(dest_dir.join("dangling")).unwrap();
|
||||
assert!(meta.file_type().is_symlink());
|
||||
assert_eq!(
|
||||
std::fs::read_link(dest_dir.join("dangling")).unwrap(),
|
||||
std::path::Path::new("/nonexistent/target")
|
||||
);
|
||||
}
|
||||
|
||||
/// Copying a source tree into a build context must strip version-control
|
||||
/// metadata directories at any depth: their presence flips autotools
|
||||
/// "building from git" detection and activates maintainer-only rules
|
||||
/// needing undeclared tools (e.g. help2man for GNU hello's man page).
|
||||
#[test]
|
||||
fn test_ensure_available_strips_vcs_metadata() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let src_root = temp_dir.path().join("pkg");
|
||||
fs::create_dir_all(src_root.join(".git/objects")).unwrap();
|
||||
fs::write(src_root.join(".git/HEAD"), "ref: refs/heads/main").unwrap();
|
||||
fs::create_dir_all(src_root.join("src/.svn")).unwrap();
|
||||
fs::write(src_root.join("src/hello.c"), "int main() {}").unwrap();
|
||||
|
||||
let ctx = Context::new(ContextConfig::Local).unwrap();
|
||||
let dest = ctx.ensure_available(&src_root, "/tmp").unwrap();
|
||||
|
||||
assert!(dest.join("src/hello.c").exists());
|
||||
assert!(!dest.join(".git").exists());
|
||||
assert!(!dest.join("src/.svn").exists());
|
||||
}
|
||||
|
||||
/// The unshare driver maps context-relative paths onto the chroot root
|
||||
/// on the host: `is_dir` must answer through that mapping (a host-side
|
||||
/// stat of the unmapped path sees nothing), which is what lets the deb
|
||||
/// package-directory search classify staged entries.
|
||||
#[test]
|
||||
fn test_unshare_is_dir_maps_through_the_chroot_root() {
|
||||
let chroot = tempfile::tempdir().unwrap();
|
||||
fs::create_dir_all(chroot.path().join("tmp/work/tree/debian")).unwrap();
|
||||
fs::write(chroot.path().join("tmp/work/orig.tar.xz"), "tar").unwrap();
|
||||
|
||||
let base = Context::new(ContextConfig::Local).unwrap();
|
||||
let ctx = Context::with_parent(
|
||||
ContextConfig::Unshare {
|
||||
path: chroot.path().to_string_lossy().to_string(),
|
||||
parent: None,
|
||||
},
|
||||
Arc::new(base),
|
||||
);
|
||||
|
||||
assert!(ctx.is_dir(std::path::Path::new("/tmp/work/tree")).unwrap());
|
||||
assert!(
|
||||
ctx.exists(std::path::Path::new("/tmp/work/tree/debian"))
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!ctx.is_dir(std::path::Path::new("/tmp/work/orig.tar.xz"))
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!ctx.exists(std::path::Path::new("/tmp/work/missing"))
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
/// The overlay-mount path exposes the tree verbatim, so pruning happens
|
||||
/// after the fact: nested VCS metadata must be removed recursively.
|
||||
#[test]
|
||||
fn test_prune_vcs_dirs_removes_nested_metadata() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let root = temp_dir.path().join("tree");
|
||||
fs::create_dir_all(root.join("a/.git/objects")).unwrap();
|
||||
fs::create_dir_all(root.join("b/c/CVS")).unwrap();
|
||||
fs::write(root.join("a/.git/HEAD"), "ref").unwrap();
|
||||
fs::write(root.join("b/keep.txt"), "x").unwrap();
|
||||
|
||||
prune_vcs_dirs(&root).unwrap();
|
||||
|
||||
assert!(!root.join("a/.git").exists());
|
||||
assert!(!root.join("b/c/CVS").exists());
|
||||
assert!(root.join("b/keep.txt").exists());
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
//! The `Sandbox` bridge for the old `Context` API.
|
||||
//!
|
||||
//! The build code receives `Arc<dyn Sandbox>` while the unshare driver is
|
||||
//! still a `ContextDriver`. This bridge maps the trait onto the driver until
|
||||
//! the driver moves into `sandbox::unshare`.
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::sandbox::{
|
||||
BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcome, Sandbox,
|
||||
};
|
||||
|
||||
use super::Context;
|
||||
|
||||
impl Sandbox for Context {
|
||||
fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result<Execution> {
|
||||
let driver_guard = self.driver();
|
||||
let driver = driver_guard.as_ref().unwrap();
|
||||
let program = cmd.program.to_string_lossy().into_owned();
|
||||
let args: Vec<String> = cmd
|
||||
.args
|
||||
.iter()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
let env: Vec<(String, String)> = cmd
|
||||
.env
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
(
|
||||
key.to_string_lossy().into_owned(),
|
||||
value.to_string_lossy().into_owned(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let cwd = cmd.cwd.as_deref().map(|path| path.to_string_lossy());
|
||||
|
||||
match capture {
|
||||
Capture::Inherit => {
|
||||
let status = driver.run(&program, &args, &env, cwd.as_deref())?;
|
||||
Ok(Execution {
|
||||
status,
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
})
|
||||
}
|
||||
Capture::Lines(sink) => {
|
||||
let status = driver.run_captured(&program, &args, &env, cwd.as_deref(), sink)?;
|
||||
Ok(Execution {
|
||||
status,
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
})
|
||||
}
|
||||
Capture::Output => {
|
||||
let output = driver.run_output(&program, &args, &env, cwd.as_deref())?;
|
||||
Ok(Execution {
|
||||
status: output.status,
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
Context::read_file(self, path)
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
Context::write_file(self, path, content)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
Context::exists(self, path)
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
Context::is_dir(self, path)
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<std::path::PathBuf>> {
|
||||
Context::list_files(self, path)
|
||||
}
|
||||
|
||||
fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> io::Result<PutOutcome> {
|
||||
let dest_root = dest.parent().ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::InvalidInput, "destination has no parent")
|
||||
})?;
|
||||
let dest_root = dest_root.to_string_lossy();
|
||||
|
||||
if let Some(reuse) = &opts.reuse {
|
||||
let staging = Context::ensure_available_with_overlay(
|
||||
self,
|
||||
host,
|
||||
&dest_root,
|
||||
&reuse.upper,
|
||||
&reuse.work,
|
||||
)?;
|
||||
return Ok(if staging.overlay {
|
||||
PutOutcome::Resumed
|
||||
} else {
|
||||
PutOutcome::Fresh
|
||||
});
|
||||
}
|
||||
|
||||
let staged = Context::ensure_available(self, host, &dest_root)?;
|
||||
if staged != dest {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"put destination '{}' does not match the staged path '{}'",
|
||||
dest.display(),
|
||||
staged.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(PutOutcome::Fresh)
|
||||
}
|
||||
|
||||
fn get(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
Context::retrieve_path(self, src, dest)
|
||||
}
|
||||
|
||||
fn remove(&self, path: &Path) -> io::Result<()> {
|
||||
let status = Context::command(self, "rm").arg("-rf").arg(path).status()?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::other(format!(
|
||||
"failed to remove '{}': rm exited with {status}",
|
||||
path.display()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
Context::create_temp_dir(self)
|
||||
}
|
||||
|
||||
fn is_host(&self) -> bool {
|
||||
matches!(self.config, crate::context::ContextConfig::Local)
|
||||
}
|
||||
|
||||
fn cleanup(&self, _outcome: Option<BuildOutcome>) -> io::Result<()> {
|
||||
Context::cleanup(self)
|
||||
}
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
/// Schroot context: execute commands in a schroot session
|
||||
/// Not tested, will need more work!
|
||||
use super::api::{Context, ContextConfig, ContextDriver};
|
||||
use super::shell::shell_quote;
|
||||
use crate::exec::LineSink;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct SchrootDriver {
|
||||
pub name: String,
|
||||
pub session: std::sync::Mutex<Option<String>>,
|
||||
pub parent: Option<Arc<super::api::Context>>,
|
||||
}
|
||||
|
||||
impl SchrootDriver {
|
||||
fn parent(&self) -> Arc<Context> {
|
||||
self.parent.clone().unwrap_or_else(|| {
|
||||
// ContextConfig::Local has no parent, so this cannot fail.
|
||||
Arc::new(Context::new(ContextConfig::Local).expect("Local context cannot fail"))
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_session(&self) -> io::Result<String> {
|
||||
let mut session_lock = self.session.lock().unwrap();
|
||||
if let Some(id) = session_lock.as_ref() {
|
||||
return Ok(id.clone());
|
||||
}
|
||||
|
||||
// Create new session
|
||||
let output = self
|
||||
.parent()
|
||||
.command("schroot")
|
||||
.arg("-b")
|
||||
.arg("-c")
|
||||
.arg(&self.name)
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"Failed to create schroot session: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
)));
|
||||
}
|
||||
|
||||
let session_id = String::from_utf8(output.stdout)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
|
||||
.trim()
|
||||
.to_string();
|
||||
|
||||
*session_lock = Some(session_id.clone());
|
||||
Ok(session_id)
|
||||
}
|
||||
|
||||
fn get_session_location(&self, session_id: &str) -> io::Result<String> {
|
||||
let output = self
|
||||
.parent()
|
||||
.command("schroot")
|
||||
.arg("--location")
|
||||
.arg("-c")
|
||||
.arg(session_id)
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"Failed to get schroot location: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(String::from_utf8(output.stdout)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
|
||||
.trim()
|
||||
.to_string())
|
||||
}
|
||||
|
||||
/// Build the `schroot` argument list executing `(program, args)` inside
|
||||
/// the given session.
|
||||
///
|
||||
/// When `preserve_env` is set, `-p` is passed so the host environment is
|
||||
/// preserved (historical behavior of `run()`, while `run_output()` does
|
||||
/// not preserve it).
|
||||
fn schroot_args(
|
||||
session_id: &str,
|
||||
preserve_env: bool,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> Vec<String> {
|
||||
let mut command_args = Vec::new();
|
||||
if preserve_env {
|
||||
command_args.push("-p".to_string());
|
||||
}
|
||||
command_args.extend([
|
||||
"-r".to_string(),
|
||||
"-c".to_string(),
|
||||
session_id.to_string(),
|
||||
"--".to_string(),
|
||||
]);
|
||||
|
||||
let (actual_program, actual_args) = Self::wrap_command(program, args, env, cwd);
|
||||
command_args.push(actual_program);
|
||||
command_args.extend(actual_args);
|
||||
command_args
|
||||
}
|
||||
|
||||
/// Wrap `(program, args)` in `sh -c` when a working directory or
|
||||
/// environment variables are needed.
|
||||
///
|
||||
/// Everything interpolated into the resulting shell string — the `cd`
|
||||
/// target, env keys and values, the program and each argument — is
|
||||
/// POSIX-shell-quoted (see [`shell_quote`]), so metacharacters (spaces,
|
||||
/// quotes, `$`, ...) can neither split words nor trigger expansion.
|
||||
fn wrap_command(
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> (String, Vec<String>) {
|
||||
let mut actual_program = program.to_string();
|
||||
let mut actual_args = args.to_vec();
|
||||
|
||||
if cwd.is_some() || !env.is_empty() {
|
||||
let mut shell_cmd = String::new();
|
||||
|
||||
if let Some(dir) = cwd {
|
||||
shell_cmd.push_str(&format!("cd {} && ", shell_quote(dir)));
|
||||
}
|
||||
|
||||
if !env.is_empty() {
|
||||
shell_cmd.push_str("env ");
|
||||
for (k, v) in env {
|
||||
shell_cmd.push_str(&format!("{}={} ", shell_quote(k), shell_quote(v)));
|
||||
}
|
||||
}
|
||||
|
||||
shell_cmd.push_str(&shell_quote(program));
|
||||
for arg in args {
|
||||
shell_cmd.push(' ');
|
||||
shell_cmd.push_str(&shell_quote(arg));
|
||||
}
|
||||
|
||||
actual_program = "sh".to_string();
|
||||
actual_args = vec!["-c".to_string(), shell_cmd];
|
||||
}
|
||||
|
||||
(actual_program, actual_args)
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextDriver for SchrootDriver {
|
||||
fn ensure_available(&self, src: &Path, _dest_root: &str) -> io::Result<PathBuf> {
|
||||
src.canonicalize()
|
||||
}
|
||||
|
||||
fn retrieve_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
let session_id = self.ensure_session()?;
|
||||
let location = self.get_session_location(&session_id)?;
|
||||
|
||||
let path_in_chroot = src.strip_prefix("/").unwrap_or(src);
|
||||
let host_src = Path::new(&location).join(path_in_chroot);
|
||||
|
||||
self.parent().retrieve_path(&host_src, dest)
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let session_id = self.ensure_session()?;
|
||||
let location = self.get_session_location(&session_id)?;
|
||||
|
||||
let path_in_chroot = path.strip_prefix("/").unwrap_or(path);
|
||||
let host_path = Path::new(&location).join(path_in_chroot);
|
||||
|
||||
let files = self.parent().list_files(&host_path)?;
|
||||
let mut chroot_files = Vec::new();
|
||||
|
||||
// TODO: Check if we *need* to strip the prefix.
|
||||
// If we don't, we can just return `files`.
|
||||
for file in files {
|
||||
if let Ok(rel) = file.strip_prefix(&location) {
|
||||
chroot_files.push(Path::new("/").join(rel));
|
||||
} else {
|
||||
chroot_files.push(file);
|
||||
}
|
||||
}
|
||||
Ok(chroot_files)
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
let session_id = self.ensure_session()?;
|
||||
let cmd_args = Self::schroot_args(&session_id, true, program, args, env, cwd);
|
||||
self.parent().command("schroot").args(cmd_args).status()
|
||||
}
|
||||
|
||||
fn run_captured(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
sink: Arc<dyn LineSink>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
let session_id = self.ensure_session()?;
|
||||
let cmd_args = Self::schroot_args(&session_id, true, program, args, env, cwd);
|
||||
// Forward the sink to the wrapping command so capture chains through
|
||||
// the parent context driver (e.g. schroot over ssh).
|
||||
let parent = self.parent();
|
||||
let mut cmd = parent.command("schroot");
|
||||
cmd.args(cmd_args).capture(sink);
|
||||
cmd.status()
|
||||
}
|
||||
|
||||
fn run_output(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::Output> {
|
||||
let session_id = self.ensure_session()?;
|
||||
let cmd_args = Self::schroot_args(&session_id, false, program, args, env, cwd);
|
||||
self.parent().command("schroot").args(cmd_args).output()
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
let output = self.run_output("mktemp", &["-d".to_string()], &[], None)?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other("schroot mktemp failed"));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
let status = self.run(
|
||||
"cp",
|
||||
&[
|
||||
"-a".to_string(),
|
||||
src.to_string_lossy().to_string(),
|
||||
dest.to_string_lossy().to_string(),
|
||||
],
|
||||
&[],
|
||||
None,
|
||||
)?;
|
||||
if !status.success() {
|
||||
return Err(io::Error::other("schroot copy failed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
let output = self.run_output("cat", &[path.to_string_lossy().to_string()], &[], None)?;
|
||||
if !output.status.success() {
|
||||
return Err(io::Error::other(format!(
|
||||
"schroot read failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
)));
|
||||
}
|
||||
String::from_utf8(output.stdout).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
let status = self.run(
|
||||
"sh",
|
||||
&[
|
||||
"-c".to_string(),
|
||||
format!(
|
||||
// `printf '%s'` writes the content verbatim (the previous
|
||||
// `echo -ne` mangled backslashes, and dash's echo prints
|
||||
// "-ne" literally). Content and path are shell-quoted so
|
||||
// metacharacters in either cannot break out.
|
||||
"printf '%s' {} > {}",
|
||||
shell_quote(content),
|
||||
shell_quote(&path.to_string_lossy())
|
||||
),
|
||||
],
|
||||
&[],
|
||||
None,
|
||||
)?;
|
||||
if !status.success() {
|
||||
return Err(io::Error::other("schroot write failed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
let status = self.run(
|
||||
"test",
|
||||
&["-e".to_string(), path.to_string_lossy().to_string()],
|
||||
&[],
|
||||
None,
|
||||
)?;
|
||||
Ok(status.success())
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
let status = self.run(
|
||||
"test",
|
||||
&["-d".to_string(), path.to_string_lossy().to_string()],
|
||||
&[],
|
||||
None,
|
||||
)?;
|
||||
Ok(status.success())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SchrootDriver;
|
||||
|
||||
/// Without cwd/env the program and args go to schroot as direct argv
|
||||
/// (no shell involved), so they must pass through untouched.
|
||||
#[test]
|
||||
fn wrap_command_passthrough_without_env_or_cwd() {
|
||||
let (prog, args) = SchrootDriver::wrap_command(
|
||||
"make",
|
||||
&["install".to_string(), "DEST=x y".to_string()],
|
||||
&[],
|
||||
None,
|
||||
);
|
||||
assert_eq!(prog, "make");
|
||||
assert_eq!(args, vec!["install".to_string(), "DEST=x y".to_string()]);
|
||||
}
|
||||
|
||||
/// A value with a space must stay a single env assignment: previously
|
||||
/// DEB_BUILD_OPTIONS="parallel=4 nocheck" made sh treat `nocheck` as
|
||||
/// the command to run.
|
||||
#[test]
|
||||
fn wrap_command_quotes_env_values_cwd_and_args() {
|
||||
let (prog, args) = SchrootDriver::wrap_command(
|
||||
"dpkg-buildpackage",
|
||||
&["-us".to_string(), "-uc".to_string()],
|
||||
&[(
|
||||
"DEB_BUILD_OPTIONS".to_string(),
|
||||
"parallel=4 nocheck".to_string(),
|
||||
)],
|
||||
Some("/build/pkg 1.0"),
|
||||
);
|
||||
assert_eq!(prog, "sh");
|
||||
assert_eq!(args[0], "-c");
|
||||
assert_eq!(
|
||||
args[1],
|
||||
"cd '/build/pkg 1.0' && env 'DEB_BUILD_OPTIONS'='parallel=4 nocheck' \
|
||||
'dpkg-buildpackage' '-us' '-uc'"
|
||||
);
|
||||
}
|
||||
|
||||
/// The definitive check: a real shell must execute the wrapped command
|
||||
/// exactly as intended — cwd applied, env set verbatim, the inner
|
||||
/// program invoked with its argument — despite quotes in the values.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn wrapped_command_survives_shell_parsing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (prog, args) = SchrootDriver::wrap_command(
|
||||
"printenv",
|
||||
&["SOME_OPT".to_string()],
|
||||
&[(
|
||||
"SOME_OPT".to_string(),
|
||||
"parallel=4 noch'eck \"x\"".to_string(),
|
||||
)],
|
||||
Some(dir.path().to_str().unwrap()),
|
||||
);
|
||||
let output = std::process::Command::new(&prog)
|
||||
.arg(&args[0])
|
||||
.arg(&args[1])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
// printenv's output ends with a newline.
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
"parallel=4 noch'eck \"x\"\n"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
//! POSIX-shell quoting for command strings assembled by the remote/chroot
|
||||
//! execution contexts.
|
||||
//!
|
||||
//! Unlike [`super::local`] — which spawns programs directly through
|
||||
//! `std::process::Command`, with no shell in between — the SSH, schroot and
|
||||
//! unshare drivers ultimately hand a *string* to a shell (`ssh
|
||||
//! channel.exec`, `sh -c`, `bash -c`). Every program name, argument,
|
||||
//! path or environment value interpolated into such a string must be
|
||||
//! quoted, or shell metacharacters (`;`, `|`, `&`, quotes, `$`, backticks,
|
||||
//! globs, whitespace, ...) are reinterpreted by the shell: at best the
|
||||
//! command breaks, at worst it executes injected input.
|
||||
|
||||
/// Quote `s` for safe interpolation into a POSIX shell command line.
|
||||
///
|
||||
/// The result is `s` wrapped in single quotes, with every embedded single
|
||||
/// quote replaced by the standard `'\''` sequence (close the quoting, an
|
||||
/// escaped literal quote, reopen). Whatever the input contains — spaces,
|
||||
/// newlines, `"`, `'`, `$`, backticks, globs, `;` — the shell parses the
|
||||
/// result back into exactly `s` as a single word. The empty string becomes
|
||||
/// `''` (one empty argument, not zero arguments).
|
||||
///
|
||||
/// Use this for *every* value interpolated into a shell command string:
|
||||
/// programs, arguments, `cd` targets, `env` assignments (both key and
|
||||
/// value) and paths. It is safe (though redundant) to quote values that are
|
||||
/// known to need no quoting.
|
||||
pub(crate) fn shell_quote(s: &str) -> String {
|
||||
let mut quoted = String::with_capacity(s.len() + 2);
|
||||
quoted.push('\'');
|
||||
for c in s.chars() {
|
||||
if c == '\'' {
|
||||
quoted.push_str("'\\''");
|
||||
} else {
|
||||
quoted.push(c);
|
||||
}
|
||||
}
|
||||
quoted.push('\'');
|
||||
quoted
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::shell_quote;
|
||||
|
||||
#[test]
|
||||
fn plain_word() {
|
||||
assert_eq!(shell_quote("plain"), "'plain'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spaces_stay_one_word() {
|
||||
assert_eq!(shell_quote("parallel=4 nocheck"), "'parallel=4 nocheck'");
|
||||
assert_eq!(
|
||||
shell_quote(" leading and trailing "),
|
||||
"' leading and trailing '"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedded_single_quotes() {
|
||||
assert_eq!(shell_quote("it's"), "'it'\\''s'");
|
||||
assert_eq!(shell_quote("''"), r"''\'''\'''");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_quotes_and_metacharacters() {
|
||||
assert_eq!(
|
||||
shell_quote("say \"hi\" $HOME `id` ; | & * ?"),
|
||||
"'say \"hi\" $HOME `id` ; | & * ?'"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dollar_and_backtick_do_not_expand() {
|
||||
assert_eq!(shell_quote("$HOME"), "'$HOME'");
|
||||
assert_eq!(shell_quote("$(rm -rf /)"), "'$(rm -rf /)'");
|
||||
assert_eq!(shell_quote("`touch /tmp/pwned`"), "'`touch /tmp/pwned`'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_string() {
|
||||
assert_eq!(shell_quote(""), "''");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_preserved() {
|
||||
assert_eq!(shell_quote("héllo→wörld ✓"), "'héllo→wörld ✓'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newlines_preserved() {
|
||||
assert_eq!(shell_quote("a\nb"), "'a\nb'");
|
||||
}
|
||||
|
||||
/// The definitive check: a real shell must parse the quoted string back
|
||||
/// into the original value as a single argument, without expanding or
|
||||
/// executing anything inside it.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn round_trips_through_sh() {
|
||||
let tricky = "a'b\"c $HOME `echo pwned` ; | & \n x*y";
|
||||
let output = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("printf '%s' {}", shell_quote(tricky)))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout), tricky);
|
||||
}
|
||||
}
|
||||
@@ -1,446 +0,0 @@
|
||||
/// SSH context: execute commands over an SSH connection
|
||||
/// Context driver: Copies over SFTP with ssh2, executes commands over ssh2 channels
|
||||
use super::api::ContextDriver;
|
||||
use super::shell::shell_quote;
|
||||
use crate::exec::{LineSink, Stream, pump};
|
||||
use log::debug;
|
||||
use ssh2;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::io::{self, Read};
|
||||
use std::net::TcpStream;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitStatus;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn connect_ssh(host: &str, user: Option<&str>, port: Option<u16>) -> io::Result<ssh2::Session> {
|
||||
let port = port.unwrap_or(22);
|
||||
let tcp = TcpStream::connect((host, port))?;
|
||||
let mut session = ssh2::Session::new().unwrap();
|
||||
session.set_tcp_stream(tcp);
|
||||
session
|
||||
.handshake()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::ConnectionRefused, e))?;
|
||||
|
||||
// Username: if set, use it; else, use local 'USER', and if unset, use 'root'
|
||||
let local_user_string;
|
||||
let user = match user {
|
||||
Some(u) => u,
|
||||
None => {
|
||||
local_user_string = std::env::var("USER").unwrap_or_else(|_| "root".to_string());
|
||||
&local_user_string
|
||||
}
|
||||
};
|
||||
|
||||
if session.userauth_agent(user).is_ok() {
|
||||
return Ok(session);
|
||||
}
|
||||
|
||||
if !session.authenticated() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"SSH authentication failed (tried agent)",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub struct SshDriver {
|
||||
pub host: String,
|
||||
pub user: Option<String>,
|
||||
pub port: Option<u16>,
|
||||
}
|
||||
|
||||
impl SshDriver {
|
||||
/// Build the remote shell command line: `export` assignments for `env`,
|
||||
/// an optional `cd` to `cwd`, then `program` with its `args`.
|
||||
///
|
||||
/// The line is executed verbatim by the remote login shell through
|
||||
/// `channel.exec`, so every component is POSIX-shell-quoted (see
|
||||
/// [`shell_quote`]): metacharacters in arguments, paths or environment
|
||||
/// values can neither break out of their word nor be expanded by the
|
||||
/// remote shell.
|
||||
fn build_command_line(
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
) -> String {
|
||||
let mut cmd_line = String::new();
|
||||
for (key, value) in env {
|
||||
cmd_line.push_str(&format!(
|
||||
"export {}={}; ",
|
||||
shell_quote(key),
|
||||
shell_quote(value)
|
||||
));
|
||||
}
|
||||
if let Some(dir) = cwd {
|
||||
cmd_line.push_str(&format!("cd {} && ", shell_quote(dir)));
|
||||
}
|
||||
cmd_line.push_str(&shell_quote(program));
|
||||
for arg in args {
|
||||
cmd_line.push(' ');
|
||||
cmd_line.push_str(&shell_quote(arg));
|
||||
}
|
||||
cmd_line
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextDriver for SshDriver {
|
||||
fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
|
||||
let file_name = src
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "src has no filename"))?;
|
||||
let remote_dest = Path::new(dest_root).join(file_name);
|
||||
|
||||
debug!("Uploading {:?} to remote {:?}", src, remote_dest);
|
||||
|
||||
Self::upload_recursive(&sftp, src, &remote_dest)?;
|
||||
|
||||
Ok(remote_dest)
|
||||
}
|
||||
|
||||
fn retrieve_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
|
||||
debug!("Downloading remote {:?} to {:?}", src, dest);
|
||||
Self::download_recursive(&sftp, src, dest)
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
|
||||
let mut files = Vec::new();
|
||||
let entries = sftp.readdir(path).map_err(io::Error::other)?;
|
||||
for (p, _) in entries {
|
||||
let file_name = p.file_name().unwrap();
|
||||
if file_name == "." || file_name == ".." {
|
||||
continue;
|
||||
}
|
||||
files.push(p);
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let mut channel = sess.channel_session().map_err(io::Error::other)?;
|
||||
|
||||
// Construct command line with env vars
|
||||
// TODO: No, use ssh2 channel.set_env
|
||||
let cmd_line = Self::build_command_line(env, cwd, program, args);
|
||||
|
||||
debug!("Executing SSH command: {}", cmd_line);
|
||||
|
||||
channel
|
||||
.request_pty("xterm", None, None)
|
||||
.map_err(|e| io::Error::other(format!("Failed to request PTY: {}", e)))?;
|
||||
|
||||
channel.exec(&cmd_line).map_err(io::Error::other)?;
|
||||
|
||||
let mut stdout_stream = channel.stream(0);
|
||||
let mut stdout = io::stdout();
|
||||
io::copy(&mut stdout_stream, &mut stdout)?;
|
||||
|
||||
channel.wait_close().map_err(io::Error::other)?;
|
||||
|
||||
let code = channel.exit_status().unwrap_or(-1);
|
||||
Ok(ExitStatus::from_raw(code))
|
||||
}
|
||||
|
||||
fn run_captured(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
sink: Arc<dyn LineSink>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let mut channel = sess.channel_session().map_err(io::Error::other)?;
|
||||
|
||||
// Construct command line with env vars (same quoting as `run`)
|
||||
let cmd_line = Self::build_command_line(env, cwd, program, args);
|
||||
|
||||
debug!("Executing SSH command (captured): {}", cmd_line);
|
||||
|
||||
// Keep the PTY: it keeps tool output line-buffered (better for live
|
||||
// display) and merges stdout/stderr into a single ordered stream,
|
||||
// which ssh2 cannot read concurrently anyway.
|
||||
channel
|
||||
.request_pty("xterm", None, None)
|
||||
.map_err(|e| io::Error::other(format!("Failed to request PTY: {}", e)))?;
|
||||
|
||||
channel.exec(&cmd_line).map_err(io::Error::other)?;
|
||||
|
||||
let mut stdout_stream = channel.stream(0);
|
||||
pump(&mut stdout_stream, Stream::Stdout, sink.as_ref());
|
||||
|
||||
channel.wait_close().map_err(io::Error::other)?;
|
||||
|
||||
let code = channel.exit_status().unwrap_or(-1);
|
||||
Ok(ExitStatus::from_raw(code))
|
||||
}
|
||||
|
||||
fn run_output(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::Output> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let mut channel = sess.channel_session().map_err(io::Error::other)?;
|
||||
|
||||
// Construct command line with env vars (same quoting as `run`)
|
||||
let cmd_line = Self::build_command_line(env, cwd, program, args);
|
||||
|
||||
channel.exec(&cmd_line).map_err(io::Error::other)?;
|
||||
|
||||
let mut stdout = Vec::new();
|
||||
channel.read_to_end(&mut stdout)?;
|
||||
|
||||
let mut stderr = Vec::new();
|
||||
channel.stderr().read_to_end(&mut stderr)?;
|
||||
|
||||
channel.wait_close().map_err(io::Error::other)?;
|
||||
|
||||
#[cfg(unix)]
|
||||
let status = std::process::ExitStatus::from_raw(channel.exit_status().unwrap_or(-1));
|
||||
|
||||
#[cfg(not(unix))]
|
||||
let status = {
|
||||
panic!("SSH output capture only supported on Unix");
|
||||
};
|
||||
|
||||
Ok(std::process::Output {
|
||||
status,
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let mut channel = sess.channel_session().map_err(io::Error::other)?;
|
||||
|
||||
channel.exec("mktemp -d").map_err(io::Error::other)?;
|
||||
|
||||
let mut stdout = String::new();
|
||||
channel.read_to_string(&mut stdout)?;
|
||||
channel.wait_close().map_err(io::Error::other)?;
|
||||
|
||||
if channel.exit_status().unwrap_or(-1) != 0 {
|
||||
return Err(io::Error::other(
|
||||
"Failed to create remote temporary directory",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(stdout.trim().to_string())
|
||||
}
|
||||
|
||||
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let mut channel = sess.channel_session().map_err(io::Error::other)?;
|
||||
// TODO: use sftp
|
||||
let cmd = format!(
|
||||
"cp -a {} {}",
|
||||
shell_quote(&src.to_string_lossy()),
|
||||
shell_quote(&dest.to_string_lossy())
|
||||
);
|
||||
debug!("Executing remote copy: {}", cmd);
|
||||
channel.exec(&cmd).map_err(io::Error::other)?;
|
||||
channel.wait_close().map_err(io::Error::other)?;
|
||||
if channel.exit_status().unwrap_or(-1) != 0 {
|
||||
return Err(io::Error::other(format!("Remote copy failed: {}", cmd)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
let mut remote_file = sftp.open(path).map_err(io::Error::other)?;
|
||||
let mut content = String::new();
|
||||
remote_file.read_to_string(&mut content)?;
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
if let Some(parent) = path.parent() {
|
||||
let _ = sftp.mkdir(parent, 0o755);
|
||||
}
|
||||
let mut remote_file = sftp.create(path).map_err(io::Error::other)?;
|
||||
remote_file.write_all(content.as_bytes())?;
|
||||
// Close explicitly: the `Drop` impl of `ssh2::File` discards a
|
||||
// close-time error ("too late to recover"), silently truncating the
|
||||
// remote file. Writes are unbuffered (`Write::flush` is a no-op), so
|
||||
// no flush is needed before closing.
|
||||
remote_file.close().map_err(|e| {
|
||||
io::Error::other(format!("Failed to close remote file {:?}: {}", path, e))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
match sftp.stat(path) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
let sess = connect_ssh(&self.host, self.user.as_deref(), self.port)?;
|
||||
let sftp = sess.sftp().map_err(io::Error::other)?;
|
||||
// Same error tolerance as `exists`: an unreachable path is not a
|
||||
// directory, and the caller decides what absence means.
|
||||
Ok(sftp.stat(path).map(|stat| stat.is_dir()).unwrap_or(false))
|
||||
}
|
||||
}
|
||||
|
||||
impl SshDriver {
|
||||
fn upload_recursive(sftp: &ssh2::Sftp, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
if src.is_dir() {
|
||||
// Create dir
|
||||
let _ = sftp.mkdir(dest, 0o755);
|
||||
for entry in fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let name = entry.file_name();
|
||||
// Skip VCS metadata (see is_vcs_dir_name): shipping it into
|
||||
// the remote build tree would flip autotools 'building from
|
||||
// VCS' detection and activate maintainer-only rules.
|
||||
if path.symlink_metadata().map(|m| m.is_dir()).unwrap_or(false)
|
||||
&& super::is_vcs_dir_name(&name)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let dest_path = dest.join(name);
|
||||
Self::upload_recursive(sftp, &path, &dest_path)?;
|
||||
}
|
||||
} else {
|
||||
let mut file = fs::File::open(src)?;
|
||||
let mut remote_file = sftp.create(dest).map_err(|e| {
|
||||
io::Error::other(format!("Failed to create remote file {:?}: {}", dest, e))
|
||||
})?;
|
||||
io::copy(&mut file, &mut remote_file)?;
|
||||
// Close explicitly: quota-exceeded and similar failures only
|
||||
// surface in the final ACKs and the close handshake, and the
|
||||
// `Drop` impl of `ssh2::File` discards that error ("too late to
|
||||
// recover"), leaving a truncated remote file behind. Writes are
|
||||
// unbuffered (`ssh2::File`'s `Write::flush` is a no-op), so no
|
||||
// flush is needed before closing.
|
||||
remote_file.close().map_err(|e| {
|
||||
io::Error::other(format!(
|
||||
"Failed to close remote file {:?} after upload: {}",
|
||||
dest, e
|
||||
))
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn download_recursive(sftp: &ssh2::Sftp, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
let stat = sftp
|
||||
.stat(src)
|
||||
.map_err(|e| io::Error::other(format!("Remote stat failed for {:?}: {}", src, e)))?;
|
||||
|
||||
if stat.is_dir() {
|
||||
fs::create_dir_all(dest)?;
|
||||
let entries = sftp.readdir(src).map_err(io::Error::other)?;
|
||||
for (path, _) in entries {
|
||||
let file_name = path.file_name().unwrap();
|
||||
if file_name == "." || file_name == ".." {
|
||||
continue;
|
||||
}
|
||||
let new_dest = dest.join(file_name);
|
||||
Self::download_recursive(sftp, &path, &new_dest)?;
|
||||
}
|
||||
} else {
|
||||
let mut remote_file = sftp.open(src).map_err(io::Error::other)?;
|
||||
let mut local_file = fs::File::create(dest)?;
|
||||
io::copy(&mut remote_file, &mut local_file)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::SshDriver;
|
||||
|
||||
/// Program, arguments and the `cd` target must each be a single,
|
||||
/// quoted word; `$` in the cwd must not be expanded.
|
||||
#[test]
|
||||
fn command_line_quotes_program_args_and_cwd() {
|
||||
let line = SshDriver::build_command_line(
|
||||
&[],
|
||||
Some("/tmp/some dir/$HOST"),
|
||||
"make",
|
||||
&["install".to_string(), "PREFIX=/opt/my app".to_string()],
|
||||
);
|
||||
assert_eq!(
|
||||
line,
|
||||
"cd '/tmp/some dir/$HOST' && 'make' 'install' 'PREFIX=/opt/my app'"
|
||||
);
|
||||
}
|
||||
|
||||
/// Env keys and values are quoted too (values used to be escaped by
|
||||
/// hand, keys and everything else not at all).
|
||||
#[test]
|
||||
fn command_line_quotes_env_keys_and_values() {
|
||||
let line = SshDriver::build_command_line(
|
||||
&[(
|
||||
"DEB_BUILD_OPTIONS".to_string(),
|
||||
"parallel=4 nocheck".to_string(),
|
||||
)],
|
||||
None,
|
||||
"dpkg-buildpackage",
|
||||
&["-us".to_string(), "-uc".to_string()],
|
||||
);
|
||||
assert_eq!(
|
||||
line,
|
||||
"export 'DEB_BUILD_OPTIONS'='parallel=4 nocheck'; 'dpkg-buildpackage' '-us' '-uc'"
|
||||
);
|
||||
}
|
||||
|
||||
/// The definitive check: a real shell must execute the assembled line
|
||||
/// exactly as intended — one argument through, one env value verbatim —
|
||||
/// even when both contain quotes, spaces and `$`.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn command_line_survives_shell_parsing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let line = SshDriver::build_command_line(
|
||||
&[("OPT".to_string(), "a b'c \"$d\"".to_string())],
|
||||
Some(dir.path().to_str().unwrap()),
|
||||
"printenv",
|
||||
&["OPT".to_string()],
|
||||
);
|
||||
let output = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(&line)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout), "a b'c \"$d\"\n");
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -227,7 +227,7 @@ pub fn ensure_repositories(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::context::Context;
|
||||
use crate::sandbox::Host;
|
||||
|
||||
#[test]
|
||||
fn test_parse_dpkg_architecture_output() {
|
||||
@@ -316,7 +316,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_setup_environment_exports_dpkg_cross_variables_only() {
|
||||
let mut env = HashMap::new();
|
||||
let ctx = Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap());
|
||||
let ctx = Arc::new(Host::new());
|
||||
setup_environment(&mut env, "riscv64", ctx).unwrap();
|
||||
|
||||
assert!(!env.contains_key("PKG_CONFIG_LIBDIR"));
|
||||
|
||||
+10
-10
@@ -101,7 +101,7 @@ pub const BUILD_USER: &str = "pkh-build";
|
||||
/// How the rules steps run as an unprivileged build identity.
|
||||
enum RulesIdentity {
|
||||
/// A nested user namespace maps the chroot's root ownership onto
|
||||
/// [`crate::context::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
|
||||
/// 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
|
||||
@@ -120,12 +120,12 @@ enum RulesIdentity {
|
||||
/// here means the fallback would fail the same way.
|
||||
fn probe_mapped_namespace(ctx: &Arc<dyn Sandbox>) -> Result<(), String> {
|
||||
let mut cmd = ctx.command("sh");
|
||||
cmd.env(crate::context::MAPPED_IDENTITY_ENV, "1")
|
||||
cmd.env(crate::sandbox::unshare::MAPPED_IDENTITY_ENV, "1")
|
||||
.arg("-c")
|
||||
.arg(format!(
|
||||
"test \"$(id -u)\" = {} && test \"$(id -g)\" = {}",
|
||||
crate::context::MAPPED_BUILD_ID,
|
||||
crate::context::MAPPED_BUILD_ID
|
||||
crate::sandbox::unshare::MAPPED_BUILD_ID,
|
||||
crate::sandbox::unshare::MAPPED_BUILD_ID
|
||||
));
|
||||
match cmd.output() {
|
||||
Ok(out) if out.status.success() => Ok(()),
|
||||
@@ -149,7 +149,7 @@ fn probe_mapped_namespace(ctx: &Arc<dyn Sandbox>) -> Result<(), String> {
|
||||
/// 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
|
||||
/// onto [`crate::context::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
|
||||
/// ordinary chroot user and hands the tree over with a chown — through
|
||||
/// the overlay staging every chowned lower-layer file copy-ups, which on
|
||||
@@ -193,7 +193,7 @@ fn ensure_build_user(
|
||||
if let Some(dir) = ccache_host_dir.filter(|dir| dir.is_dir()) {
|
||||
migrate_ccache_ownership(dir);
|
||||
}
|
||||
write_build_user_entries(ctx, crate::context::MAPPED_BUILD_ID)?;
|
||||
write_build_user_entries(ctx, crate::sandbox::unshare::MAPPED_BUILD_ID)?;
|
||||
return Ok(RulesIdentity::MappedNamespace);
|
||||
}
|
||||
|
||||
@@ -507,7 +507,7 @@ fn rules_command<'a>(
|
||||
match identity {
|
||||
Some(RulesIdentity::MappedNamespace) => {
|
||||
let mut cmd = ctx.command(program);
|
||||
cmd.env(crate::context::MAPPED_IDENTITY_ENV, "1");
|
||||
cmd.env(crate::sandbox::unshare::MAPPED_IDENTITY_ENV, "1");
|
||||
cmd
|
||||
}
|
||||
Some(RulesIdentity::Setpriv(uid, gid)) => {
|
||||
@@ -1961,7 +1961,7 @@ fn dose3_explain_dependencies(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::context::{Context, ContextConfig};
|
||||
use crate::sandbox::Host;
|
||||
|
||||
fn cand(arch: &str, ma: &str) -> Candidate {
|
||||
Candidate {
|
||||
@@ -2279,7 +2279,7 @@ mod tests {
|
||||
/// declaration is not.
|
||||
#[test]
|
||||
fn detector_on_a_real_tree_through_the_context() {
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(Context::new(ContextConfig::Local).unwrap());
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(Host::new());
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let tree = dir.path().join("pkg");
|
||||
@@ -2306,7 +2306,7 @@ mod tests {
|
||||
/// application entirely and succeed.
|
||||
#[test]
|
||||
fn apply_phase_skips_single_debian_patch_trees() {
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(Context::new(ContextConfig::Local).unwrap());
|
||||
let ctx: Arc<dyn Sandbox> = Arc::new(Host::new());
|
||||
|
||||
// Dashed spelling through debian/source/options this time.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
+6
-12
@@ -4,13 +4,12 @@ pub(crate) mod local;
|
||||
/// host-tree snapshot/sync that keeps build artifacts alive across attempts
|
||||
pub mod session;
|
||||
|
||||
use crate::context::{Context, ContextConfig};
|
||||
use crate::logfmt::{
|
||||
AptInstallClassifier, AptUpdateClassifier, Classifier, GenericClassifier, MakeClassifier,
|
||||
MmdebstrapClassifier, QuiltClassifier,
|
||||
};
|
||||
use crate::report::{BuildTarget, BuildView, TargetKind};
|
||||
use crate::sandbox::{PutOutcome, ReuseState, Sandbox, SandboxExt, StageOptions, Unshare};
|
||||
use crate::sandbox::{Host, PutOutcome, ReuseState, Sandbox, SandboxExt, StageOptions, Unshare};
|
||||
use std::error::Error;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
@@ -447,7 +446,7 @@ async fn build_binary_package_impl(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let base_ctx = Arc::new(Context::new(ContextConfig::Local)?);
|
||||
let base_ctx = Arc::new(Host::new());
|
||||
|
||||
// Identify the target in the live view once the changelog is parsed, so
|
||||
// even the chroot download output is attributed and tee'd
|
||||
@@ -1237,13 +1236,9 @@ mod tests {
|
||||
/// is_dir answer through the path mapping, no namespace privileges
|
||||
/// needed.
|
||||
fn unshare_test_context(chroot_root: &Path) -> Arc<dyn Sandbox> {
|
||||
let base = Context::new(crate::context::ContextConfig::Local).unwrap();
|
||||
Arc::new(Context::with_parent(
|
||||
crate::context::ContextConfig::Unshare {
|
||||
path: chroot_root.to_string_lossy().to_string(),
|
||||
parent: None,
|
||||
},
|
||||
Arc::new(base),
|
||||
Arc::new(crate::sandbox::unshare::UnshareDriver::new(
|
||||
chroot_root.to_path_buf(),
|
||||
Arc::new(Host::new()),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -1366,8 +1361,7 @@ mod tests {
|
||||
log::info!("Successfully pulled package {}", package);
|
||||
|
||||
// Resolve the package directory through a local sandbox.
|
||||
let ctx_sandbox: Arc<dyn Sandbox> =
|
||||
Arc::new(Context::new(crate::context::ContextConfig::Local).unwrap());
|
||||
let ctx_sandbox: Arc<dyn Sandbox> = Arc::new(Host::new());
|
||||
|
||||
// Change directory to the package directory
|
||||
let cwd = crate::deb::find_package_directory(
|
||||
|
||||
+29
-1
@@ -117,6 +117,22 @@ pub(crate) fn sanitize_fds(cmd: &mut Command) {
|
||||
}
|
||||
}
|
||||
|
||||
/// In test binaries, a sink that tees output into the per-test log.
|
||||
///
|
||||
/// This replaces the old context-driver wrapper: every host command goes
|
||||
/// through these helpers, so the test log stays complete without a backend
|
||||
/// wrapping layer.
|
||||
fn test_sink() -> Option<Arc<dyn LineSink>> {
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::test_support::subprocess_sink()
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a host command with inherited standard streams
|
||||
pub(crate) fn run(
|
||||
program: &str,
|
||||
@@ -124,6 +140,9 @@ pub(crate) fn run(
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<ExitStatus> {
|
||||
if let Some(sink) = test_sink() {
|
||||
return run_captured(program, args, env, cwd, sink);
|
||||
}
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.args(args).envs(env.iter().map(|(k, v)| (k, v)));
|
||||
if let Some(dir) = cwd {
|
||||
@@ -192,7 +211,16 @@ pub(crate) fn run_output(
|
||||
cmd.current_dir(dir);
|
||||
}
|
||||
sanitize_fds(&mut cmd);
|
||||
cmd.output()
|
||||
let output = cmd.output()?;
|
||||
if let Some(sink) = test_sink() {
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
sink.line(Stream::Stdout, line);
|
||||
}
|
||||
for line in String::from_utf8_lossy(&output.stderr).lines() {
|
||||
sink.line(Stream::Stderr, line);
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -63,9 +63,6 @@ pub mod report;
|
||||
/// Terminal UI helpers (progress bars, live build views, prompts)
|
||||
pub mod ui;
|
||||
|
||||
/// Handle context for .deb building: locally, over ssh, in a chroot...
|
||||
pub mod context;
|
||||
|
||||
/// Quiet test runs: per-test log files, subprocess capture and failure
|
||||
/// matrix (inert passthrough outside test binaries)
|
||||
pub(crate) mod test_support;
|
||||
|
||||
+1
-1
@@ -442,7 +442,7 @@ fn main() {
|
||||
.arg(arg!(-p --pocket <pocket> "Resolve test dependencies from a specific distribution pocket (updates, security, proposed)").required(false))
|
||||
.arg(arg!(--ppa <ppa> "Add a PPA as test dependency source (can be specified multiple times)").required(false).action(clap::ArgAction::Append))
|
||||
.arg(arg!(--inject <package> "Inject a package into the testbed before the tests (.deb path or package name, can be specified multiple times)").required(false).action(clap::ArgAction::Append))
|
||||
.arg(arg!(--mode <mode> "Testbed mode: chroot (default, an ephemeral unshare chroot), local (the current context, no isolation) or vm (a qemu VM through autopkgtest)").required(false))
|
||||
.arg(arg!(--mode <mode> "Testbed mode: chroot (default, an ephemeral unshare chroot), local (the host, no isolation) or vm (a qemu VM through autopkgtest)").required(false))
|
||||
.arg(arg!(--image <file> "VM image for --mode vm (required there)").required(false))
|
||||
.arg(arg!(--cpus <n> "VM virtual CPUs (vm mode)").required(false).value_parser(clap::value_parser!(u32)))
|
||||
.arg(arg!(--"ram-size" <mib> "VM memory size in MiB (vm mode)").required(false).value_parser(clap::value_parser!(u32)))
|
||||
|
||||
+1
-1
@@ -623,7 +623,7 @@ fn upload_log_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
///
|
||||
/// The log only backs the advisory duplicate-upload guard (Launchpad
|
||||
/// re-verifies every upload), so a corrupt log must not abort the upload:
|
||||
/// like the context configuration in [`crate::context::manager`], the corrupt
|
||||
/// like the persisted configuration, the corrupt
|
||||
/// file is first backed up to `<path>.bak` (best effort) so a later
|
||||
/// [`record_upload`] cannot destroy it, then an empty log is used.
|
||||
fn load_upload_log(path: &Path) -> Vec<UploadRecord> {
|
||||
|
||||
+36
-51
@@ -1,8 +1,12 @@
|
||||
use crate::context::{self, Context, ContextConfig};
|
||||
mod namespace;
|
||||
|
||||
pub(crate) use namespace::{MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV, UnshareDriver};
|
||||
|
||||
use crate::deb::session::{self, Session};
|
||||
use crate::deb::{BuildProfiler, Phase, enter_phase};
|
||||
use crate::interrupt::CleanupHookGuard;
|
||||
use crate::report::BuildView;
|
||||
use crate::sandbox::SandboxExt;
|
||||
use crate::sandbox::{
|
||||
BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcome, Sandbox,
|
||||
};
|
||||
@@ -351,7 +355,7 @@ pub(crate) const CCACHE_SHIM_DIR: &str = "/usr/lib/pkh-ccache-shim";
|
||||
/// Failures are warnings, never errors: an unshared cache dir makes
|
||||
/// ccache per-run (still correct, just slower), and a missing shim
|
||||
/// leaves the build on the real compilers.
|
||||
fn share_ccache(chroot_path: &Path, cache: &Path, ctx: Arc<context::Context>) {
|
||||
fn share_ccache(chroot_path: &Path, cache: &Path, ctx: Arc<dyn Sandbox>) {
|
||||
if let Err(e) = fs::create_dir_all(cache).and_then(|()| install_ccache_shim(chroot_path)) {
|
||||
log::warn!("Cannot share the ccache {}: {e}", cache.display());
|
||||
return;
|
||||
@@ -488,10 +492,10 @@ pub struct Unshare {
|
||||
/// 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.
|
||||
ephemeral_ctx: Arc<Context>,
|
||||
driver: UnshareDriver,
|
||||
chroot_path: PathBuf,
|
||||
build_succeeded: AtomicBool,
|
||||
base_ctx: Arc<Context>,
|
||||
base_ctx: Arc<dyn Sandbox>,
|
||||
/// Registration of the interrupt-time cleanup hook; deregistered when
|
||||
/// this guard drops, so the hook can never fire after the normal cleanup
|
||||
cleanup_hook: Option<CleanupHookGuard>,
|
||||
@@ -522,7 +526,7 @@ impl Unshare {
|
||||
series: &str,
|
||||
arch: Option<&str>,
|
||||
mirror: Option<&str>,
|
||||
base_ctx: Arc<Context>,
|
||||
base_ctx: Arc<dyn Sandbox>,
|
||||
view: &dyn BuildView,
|
||||
profiler: &mut BuildProfiler,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
@@ -555,7 +559,7 @@ impl Unshare {
|
||||
series: &str,
|
||||
arch: Option<&str>,
|
||||
mirror: Option<&str>,
|
||||
base_ctx: Arc<Context>,
|
||||
base_ctx: Arc<dyn Sandbox>,
|
||||
view: &dyn BuildView,
|
||||
keep_upper: bool,
|
||||
ccache_dir: Option<&Path>,
|
||||
@@ -581,7 +585,7 @@ impl Unshare {
|
||||
series: &str,
|
||||
arch: Option<&str>,
|
||||
mirror: Option<&str>,
|
||||
base_ctx: Arc<Context>,
|
||||
base_ctx: Arc<dyn Sandbox>,
|
||||
view: &dyn BuildView,
|
||||
keep_upper: bool,
|
||||
ccache_dir: Option<&Path>,
|
||||
@@ -617,7 +621,7 @@ impl Unshare {
|
||||
// Session mode tears the record's per-run state down (chroot and
|
||||
// overlay workdir) and keeps its staged tree exactly for
|
||||
// `--incremental`; a plain temp chroot is removed entirely.
|
||||
let cleanup_hook = if matches!(base_ctx.config, ContextConfig::Local) {
|
||||
let cleanup_hook = if base_ctx.is_host() {
|
||||
let hook: Box<dyn Fn() + Send> = match session.as_ref().map(|s| s.root().to_path_buf())
|
||||
{
|
||||
Some(record_root) => {
|
||||
@@ -681,24 +685,9 @@ impl Unshare {
|
||||
s.set_tarball_sha256(&sha);
|
||||
}
|
||||
|
||||
// Switch to an ephemeral context to build the package in the chroot.
|
||||
// The parent is the base context itself (the one that bootstrapped
|
||||
// the chroot), wired through `with_parent` instead of a config-name
|
||||
// lookup, so an explicit non-current base (e.g. ssh) is used for
|
||||
// everything that runs inside the chroot. The Arc stays in the
|
||||
// guard: the build and the cleanup use it directly.
|
||||
let ephemeral_ctx = Arc::new(Context::with_parent(
|
||||
ContextConfig::Unshare {
|
||||
path: chroot_path.to_string_lossy().to_string(),
|
||||
// The real parent is bound below via `with_parent`; the
|
||||
// config field is only used for contexts read from the
|
||||
// persisted configuration.
|
||||
parent: None,
|
||||
},
|
||||
base_ctx.clone(),
|
||||
));
|
||||
let driver = UnshareDriver::new(chroot_path.clone(), base_ctx.clone());
|
||||
Ok(Self {
|
||||
ephemeral_ctx,
|
||||
driver,
|
||||
chroot_path,
|
||||
build_succeeded: AtomicBool::new(false),
|
||||
base_ctx,
|
||||
@@ -715,7 +704,7 @@ impl Unshare {
|
||||
arch: Option<&str>,
|
||||
mirror: Option<&str>,
|
||||
chroot_path: &PathBuf,
|
||||
ctx: Arc<context::Context>,
|
||||
ctx: Arc<dyn Sandbox>,
|
||||
view: &dyn BuildView,
|
||||
ccache_dir: Option<&Path>,
|
||||
profiler: &mut BuildProfiler,
|
||||
@@ -818,7 +807,7 @@ impl Unshare {
|
||||
series: &str,
|
||||
arch: Option<&str>,
|
||||
chroot_path: &Path,
|
||||
ctx: Arc<context::Context>,
|
||||
ctx: Arc<dyn Sandbox>,
|
||||
view: &dyn BuildView,
|
||||
ccache_dir: Option<&Path>,
|
||||
profiler: &mut BuildProfiler,
|
||||
@@ -870,7 +859,7 @@ impl Unshare {
|
||||
series: &str,
|
||||
arch: Option<&str>,
|
||||
chroot_path: &Path,
|
||||
ctx: Arc<context::Context>,
|
||||
ctx: Arc<dyn Sandbox>,
|
||||
) -> Option<fs::File> {
|
||||
let cache = apt_cache_dir(series, arch);
|
||||
if let Err(e) = fs::create_dir_all(cache.join("partial")) {
|
||||
@@ -956,7 +945,7 @@ impl Unshare {
|
||||
arch: Option<&str>,
|
||||
mirror: Option<&str>,
|
||||
tarball_path: &Path,
|
||||
ctx: Arc<context::Context>,
|
||||
ctx: Arc<dyn Sandbox>,
|
||||
view: &dyn BuildView,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Create a lock file to make sure that noone tries to use the file while it's not fully downloaded
|
||||
@@ -1106,7 +1095,7 @@ impl Unshare {
|
||||
|
||||
fn create_device_nodes(
|
||||
chroot_path: &Path,
|
||||
ctx: Arc<context::Context>,
|
||||
ctx: Arc<dyn Sandbox>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Ensure /dev directory exists
|
||||
fs::create_dir_all(chroot_path.join("dev"))?;
|
||||
@@ -1148,10 +1137,7 @@ impl Unshare {
|
||||
|
||||
/// Bind mount /proc from host into the chroot
|
||||
/// This is done before entering the unshare namespace, so it works in containers
|
||||
fn bind_mount_proc(
|
||||
chroot_path: &Path,
|
||||
ctx: Arc<context::Context>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
fn bind_mount_proc(chroot_path: &Path, ctx: Arc<dyn Sandbox>) -> Result<(), Box<dyn Error>> {
|
||||
let proc_path = chroot_path.join("proc");
|
||||
|
||||
// Ensure /proc directory exists in chroot
|
||||
@@ -1199,54 +1185,54 @@ impl Unshare {
|
||||
std::fs::create_dir_all(s.chroot_path().join("tmp/pkh-build"))?;
|
||||
Ok(s.build_root())
|
||||
}
|
||||
None => Ok(self.ephemeral_ctx.create_temp_dir()?),
|
||||
None => Ok(self.driver.create_temp_dir()?),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sandbox for Unshare {
|
||||
fn run(&self, cmd: &CommandSpec, capture: Capture) -> std::io::Result<Execution> {
|
||||
Sandbox::run(self.ephemeral_ctx.as_ref(), cmd, capture)
|
||||
Sandbox::run(&self.driver, cmd, capture)
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> std::io::Result<String> {
|
||||
Sandbox::read_file(self.ephemeral_ctx.as_ref(), path)
|
||||
Sandbox::read_file(&self.driver, path)
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> std::io::Result<()> {
|
||||
Sandbox::write_file(self.ephemeral_ctx.as_ref(), path, content)
|
||||
Sandbox::write_file(&self.driver, path, content)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> std::io::Result<bool> {
|
||||
Sandbox::exists(self.ephemeral_ctx.as_ref(), path)
|
||||
Sandbox::exists(&self.driver, path)
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> std::io::Result<bool> {
|
||||
Sandbox::is_dir(self.ephemeral_ctx.as_ref(), path)
|
||||
Sandbox::is_dir(&self.driver, path)
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> std::io::Result<Vec<PathBuf>> {
|
||||
Sandbox::list_files(self.ephemeral_ctx.as_ref(), path)
|
||||
Sandbox::list_files(&self.driver, path)
|
||||
}
|
||||
|
||||
fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> std::io::Result<PutOutcome> {
|
||||
Sandbox::put(self.ephemeral_ctx.as_ref(), host, dest, opts)
|
||||
Sandbox::put(&self.driver, host, dest, opts)
|
||||
}
|
||||
|
||||
fn get(&self, src: &Path, dest: &Path) -> std::io::Result<()> {
|
||||
Sandbox::get(self.ephemeral_ctx.as_ref(), src, dest)
|
||||
Sandbox::get(&self.driver, src, dest)
|
||||
}
|
||||
|
||||
fn remove(&self, path: &Path) -> std::io::Result<()> {
|
||||
Sandbox::remove(self.ephemeral_ctx.as_ref(), path)
|
||||
Sandbox::remove(&self.driver, path)
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> std::io::Result<String> {
|
||||
Sandbox::create_temp_dir(self.ephemeral_ctx.as_ref())
|
||||
Sandbox::create_temp_dir(&self.driver)
|
||||
}
|
||||
|
||||
fn cleanup(&self, outcome: Option<BuildOutcome>) -> std::io::Result<()> {
|
||||
Sandbox::cleanup(self.ephemeral_ctx.as_ref(), outcome)
|
||||
Sandbox::cleanup(&self.driver, outcome)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1283,11 +1269,10 @@ impl Drop for Unshare {
|
||||
log::debug!("Cleaning up ephemeral context ({:?})...", self.chroot_path);
|
||||
|
||||
// Clean up any overlay mounts before resetting the context. This
|
||||
// explicitly targets the context this guard created — never
|
||||
// `context::current()`, which a concurrent build may have re-pointed
|
||||
// at its own chroot. The actual unmount commands run via the parent
|
||||
// (base) context, so they work regardless.
|
||||
if let Err(e) = self.ephemeral_ctx.cleanup() {
|
||||
// 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.
|
||||
if let Err(e) = self.driver.cleanup(None) {
|
||||
log::warn!("Failed to clean up overlay mounts: {}", e);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,25 +1,354 @@
|
||||
use super::api::{Context, ContextCommand, ContextDriver, MAPPED_BUILD_ID, MAPPED_IDENTITY_ENV};
|
||||
use super::shell::shell_quote;
|
||||
use crate::exec::LineSink;
|
||||
use log::debug;
|
||||
//! The unshare backend: path mapping, overlay staging and namespace wrappers.
|
||||
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub struct UnshareDriver {
|
||||
pub path: String,
|
||||
pub parent: Option<Arc<super::api::Context>>,
|
||||
/// Host-side paths where overlay filesystems are mounted, tracked for cleanup.
|
||||
pub overlay_mounts: Mutex<Vec<PathBuf>>,
|
||||
use crate::sandbox::{
|
||||
BuildOutcome, Capture, CommandSpec, Execution, PutOptions, PutOutcome, Sandbox, SandboxExt,
|
||||
};
|
||||
|
||||
/// Marker environment value (set to `1`) flagging a rules step of a rootless
|
||||
/// build: unshare then enters the chroot by pivoting and drops into a nested
|
||||
/// user namespace mapping the chroot's root ownership onto the build identity
|
||||
/// ([`MAPPED_BUILD_ID`]), instead of chrooting into the namespace's root.
|
||||
pub(crate) const MAPPED_IDENTITY_ENV: &str = "PKH_MAPPED_IDENTITY";
|
||||
|
||||
/// The build identity inside the nested namespace of a rootless build.
|
||||
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 unshare implementation of [`Sandbox`].
|
||||
pub(crate) struct UnshareDriver {
|
||||
path: PathBuf,
|
||||
base: Arc<dyn Sandbox>,
|
||||
overlay_mounts: Mutex<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
impl UnshareDriver {
|
||||
/// Create a driver rooted at `path`, running wrapper commands through
|
||||
/// `base`.
|
||||
pub(crate) fn new(path: PathBuf, base: Arc<dyn Sandbox>) -> Self {
|
||||
UnshareDriver {
|
||||
path,
|
||||
base,
|
||||
overlay_mounts: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Map a sandbox path to its host path below the chroot root.
|
||||
fn map(&self, path: &Path) -> PathBuf {
|
||||
self.path
|
||||
.join(path.to_string_lossy().trim_start_matches('/'))
|
||||
}
|
||||
}
|
||||
|
||||
impl Sandbox for UnshareDriver {
|
||||
fn run(&self, cmd: &CommandSpec, capture: Capture) -> io::Result<Execution> {
|
||||
let mapped = cmd.env.iter().any(|(key, value)| {
|
||||
key.as_os_str() == OsStr::new(MAPPED_IDENTITY_ENV)
|
||||
&& value.as_os_str() == OsStr::new("1")
|
||||
});
|
||||
let cwd = cmd
|
||||
.cwd
|
||||
.as_ref()
|
||||
.map(|path| path.to_string_lossy().into_owned());
|
||||
let program = cmd.program.to_string_lossy().into_owned();
|
||||
let args: Vec<String> = cmd
|
||||
.args
|
||||
.iter()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect();
|
||||
|
||||
let mut command = self.base.command("unshare");
|
||||
command.envs(cmd.env.iter().map(|(key, value)| (key, value)));
|
||||
command
|
||||
.arg("--map-user=65536")
|
||||
.arg("--map-group=65536")
|
||||
.arg("--pid")
|
||||
.arg("--ipc")
|
||||
.arg("--uts")
|
||||
.arg("--user")
|
||||
.arg("--cgroup")
|
||||
.arg("--map-auto")
|
||||
.arg("-r")
|
||||
.arg("--mount")
|
||||
.arg("--fork");
|
||||
|
||||
if mapped {
|
||||
command
|
||||
.arg("--")
|
||||
.arg("bash")
|
||||
.arg("-c")
|
||||
.arg(build_pivot_script(
|
||||
&self.path.to_string_lossy(),
|
||||
cwd.as_deref(),
|
||||
&program,
|
||||
&args,
|
||||
MAPPED_BUILD_ID,
|
||||
));
|
||||
} else {
|
||||
command.arg("-R").arg(self.path.as_os_str());
|
||||
if let Some(dir) = cwd.as_deref() {
|
||||
command.arg("-w").arg(dir);
|
||||
}
|
||||
command
|
||||
.arg("--")
|
||||
.arg("bash")
|
||||
.arg("-c")
|
||||
.arg(build_namespace_script(&program, &args));
|
||||
}
|
||||
|
||||
match capture {
|
||||
Capture::Inherit => {
|
||||
let status = command.status()?;
|
||||
Ok(Execution {
|
||||
status,
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
})
|
||||
}
|
||||
Capture::Lines(sink) => {
|
||||
command.capture(sink);
|
||||
let status = command.status()?;
|
||||
Ok(Execution {
|
||||
status,
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
})
|
||||
}
|
||||
Capture::Output => {
|
||||
let output = command.output()?;
|
||||
Ok(Execution {
|
||||
status: output.status,
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
fs::read_to_string(self.map(path))
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
fs::write(self.map(path), content)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(self.map(path).exists())
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
Ok(self.map(path).is_dir())
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let mut entries = Vec::new();
|
||||
for entry in fs::read_dir(self.map(path))? {
|
||||
let entry = entry?;
|
||||
let relative = entry
|
||||
.path()
|
||||
.strip_prefix(&self.path)
|
||||
.map(|path| path.to_path_buf())
|
||||
.unwrap_or_else(|_| entry.path());
|
||||
entries.push(Path::new("/").join(relative));
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn put(&self, host: &Path, dest: &Path, opts: &PutOptions) -> io::Result<PutOutcome> {
|
||||
let host_dest = self.map(dest);
|
||||
if let Some(reuse) = &opts.reuse {
|
||||
if !host.is_dir() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"overlay staging only applies to directories",
|
||||
));
|
||||
}
|
||||
if !is_overlayfs_available() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"overlayfs is not available on this system",
|
||||
));
|
||||
}
|
||||
self.mount_overlay(host, &host_dest, Some(&reuse.upper), Some(&reuse.work))?;
|
||||
return Ok(PutOutcome::Resumed);
|
||||
}
|
||||
|
||||
copy_tree(host, &host_dest, &opts.skip_dirs)?;
|
||||
Ok(PutOutcome::Fresh)
|
||||
}
|
||||
|
||||
fn get(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
copy_tree(&self.map(src), dest, &[])
|
||||
}
|
||||
|
||||
fn remove(&self, path: &Path) -> io::Result<()> {
|
||||
let host_path = self.map(path);
|
||||
match fs::symlink_metadata(&host_path) {
|
||||
Ok(meta) if meta.is_dir() => fs::remove_dir_all(&host_path),
|
||||
Ok(_) => fs::remove_file(&host_path),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
let tmp = self.path.join("tmp");
|
||||
fs::create_dir_all(&tmp)?;
|
||||
let path = crate::sandbox::unique_dir(&tmp, "pkh-build-")?;
|
||||
Ok(format!(
|
||||
"/tmp/{}",
|
||||
path.file_name().unwrap().to_string_lossy()
|
||||
))
|
||||
}
|
||||
|
||||
fn cleanup(&self, _outcome: Option<BuildOutcome>) -> io::Result<()> {
|
||||
let mounts: Vec<PathBuf> = self.overlay_mounts.lock().unwrap().drain(..).collect();
|
||||
for mount_path in mounts {
|
||||
log::debug!("Unmounting overlay at {}", mount_path.display());
|
||||
let is_root = crate::utils::root::is_root().unwrap_or(false);
|
||||
let mut command = self.base.command(if is_root { "umount" } else { "sudo" });
|
||||
if !is_root {
|
||||
command.arg("umount");
|
||||
}
|
||||
let status = command.arg(mount_path.as_os_str()).status()?;
|
||||
if !status.success() {
|
||||
log::warn!("Failed to unmount overlay at {}", mount_path.display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl UnshareDriver {
|
||||
/// Mount `src` as an overlay at `dest_path` inside the chroot.
|
||||
fn mount_overlay(
|
||||
&self,
|
||||
src: &Path,
|
||||
dest_path: &Path,
|
||||
upper: Option<&Path>,
|
||||
work: Option<&Path>,
|
||||
) -> io::Result<()> {
|
||||
let overlay_base = self.path.join("pkh-overlay");
|
||||
let id = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let upper_dir = upper
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| overlay_base.join(format!("upper-{}", id)));
|
||||
let work_dir = work
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| overlay_base.join(format!("work-{}", id)));
|
||||
|
||||
fs::create_dir_all(&upper_dir)?;
|
||||
fs::create_dir_all(&work_dir)?;
|
||||
fs::create_dir_all(dest_path)?;
|
||||
|
||||
let src_canonical = src.canonicalize().map_err(|e| {
|
||||
io::Error::new(
|
||||
e.kind(),
|
||||
format!("Failed to canonicalize '{}': {}", src.display(), e),
|
||||
)
|
||||
})?;
|
||||
|
||||
let is_root = crate::utils::root::is_root().unwrap_or(false);
|
||||
let mut command = self.base.command(if is_root { "mount" } else { "sudo" });
|
||||
if !is_root {
|
||||
command.arg("mount");
|
||||
}
|
||||
let output = command
|
||||
.arg("-t")
|
||||
.arg("overlay")
|
||||
.arg("overlay")
|
||||
.arg("-o")
|
||||
.arg(format!(
|
||||
"lowerdir={},upperdir={},workdir={}",
|
||||
src_canonical.display(),
|
||||
upper_dir.display(),
|
||||
work_dir.display()
|
||||
))
|
||||
.arg(dest_path.as_os_str())
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
if upper.is_none() {
|
||||
let _ = fs::remove_dir_all(&upper_dir);
|
||||
let _ = fs::remove_dir_all(&work_dir);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(io::Error::other(format!(
|
||||
"Overlay mount of '{}' at '{}' failed: {}",
|
||||
src.display(),
|
||||
dest_path.display(),
|
||||
stderr.trim()
|
||||
)));
|
||||
}
|
||||
|
||||
self.overlay_mounts
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(dest_path.to_path_buf());
|
||||
|
||||
if let Err(e) = crate::sandbox::staging::prune_vcs_dirs(self, dest_path) {
|
||||
log::warn!(
|
||||
"Failed to prune VCS metadata from '{}': {}",
|
||||
dest_path.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn shell_quote(s: &str) -> String {
|
||||
let mut quoted = String::with_capacity(s.len() + 2);
|
||||
quoted.push('\'');
|
||||
for c in s.chars() {
|
||||
if c == '\'' {
|
||||
quoted.push_str("'\\''");
|
||||
} else {
|
||||
quoted.push(c);
|
||||
}
|
||||
}
|
||||
quoted.push('\'');
|
||||
quoted
|
||||
}
|
||||
|
||||
/// Copy a file, symlink or directory tree to `dest`, skipping `skip_dirs`
|
||||
/// by name at any depth.
|
||||
fn copy_tree(src: &Path, dest: &Path, skip_dirs: &[OsString]) -> io::Result<()> {
|
||||
let meta = fs::symlink_metadata(src)?;
|
||||
if meta.file_type().is_symlink() {
|
||||
let target = fs::read_link(src)?;
|
||||
let _ = fs::remove_file(dest);
|
||||
return symlink(target, dest);
|
||||
}
|
||||
if meta.is_dir() {
|
||||
return copy_dir_recursive(src, dest, skip_dirs);
|
||||
}
|
||||
if let Some(parent) = dest.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
copy_file_with_times(src, dest)
|
||||
}
|
||||
|
||||
/// Recursively copy a directory and all its contents.
|
||||
///
|
||||
/// Symlinks are copied as symlinks (preserving the link target rather than
|
||||
/// following it), so that dangling links do not abort the copy.
|
||||
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||
fn copy_dir_recursive(src: &Path, dest: &Path, skip_dirs: &[OsString]) -> io::Result<()> {
|
||||
// Create the destination directory
|
||||
std::fs::create_dir_all(dest).map_err(|e| {
|
||||
io::Error::new(
|
||||
@@ -57,11 +386,7 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||
}
|
||||
};
|
||||
|
||||
// Never ship VCS metadata into the build tree: its presence flips
|
||||
// autotools 'building from VCS' detection (see is_vcs_dir_name) and
|
||||
// activates maintainer-only regeneration rules requiring tools that
|
||||
// are not declared build-dependencies (e.g. help2man).
|
||||
if metadata.is_dir() && super::is_vcs_dir_name(&entry.file_name()) {
|
||||
if metadata.is_dir() && skip_dirs.iter().any(|skip| skip == &entry.file_name()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -87,7 +412,7 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||
})?;
|
||||
} else if src_path.is_dir() {
|
||||
// Recursively copy subdirectories
|
||||
copy_dir_recursive(&src_path, &dest_path)?;
|
||||
copy_dir_recursive(&src_path, &dest_path, skip_dirs)?;
|
||||
} else {
|
||||
// Copy regular files, preserving the source modification and
|
||||
// access times. This is important for autotools/gnulib-based
|
||||
@@ -159,435 +484,6 @@ fn is_overlayfs_available() -> bool {
|
||||
content.contains("overlay\n") || content.contains("overlay\t")
|
||||
}
|
||||
|
||||
impl ContextDriver for UnshareDriver {
|
||||
fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf> {
|
||||
// Construct the destination path inside the chroot
|
||||
let dest_dir = Path::new(&self.path).join(dest_root.trim_start_matches('/'));
|
||||
|
||||
// Ensure the destination directory exists
|
||||
std::fs::create_dir_all(&dest_dir)?;
|
||||
|
||||
// Get the filename from the source path
|
||||
let filename = src
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid source path"))?;
|
||||
|
||||
// Construct the full destination path
|
||||
let dest_path = dest_dir.join(filename);
|
||||
|
||||
// Try overlayfs for directories first — avoids a potentially expensive full copy
|
||||
if src.is_dir() && is_overlayfs_available() {
|
||||
match self.mount_overlay(src, &dest_path, None, None) {
|
||||
Ok(()) => {
|
||||
debug!(
|
||||
"Mounted overlay for {} at {}",
|
||||
src.display(),
|
||||
dest_path.display()
|
||||
);
|
||||
return Ok(Path::new(dest_root).join(filename));
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(
|
||||
"Overlay mount failed for '{}', falling back to copy: {}",
|
||||
src.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: copy the file or directory into the chroot
|
||||
debug!(
|
||||
"unshare/ensure_available: copy '{}' to '{}'",
|
||||
src.display(),
|
||||
dest_dir.display()
|
||||
);
|
||||
|
||||
if src.is_dir() {
|
||||
copy_dir_recursive(src, &dest_path)?;
|
||||
debug!(
|
||||
"Copied directory {} to {}",
|
||||
src.display(),
|
||||
dest_path.display()
|
||||
);
|
||||
} else {
|
||||
copy_file_with_times(src, &dest_path)?;
|
||||
debug!("Copied file {} to {}", src.display(), dest_path.display());
|
||||
}
|
||||
|
||||
// Return the path as it appears inside the chroot (without the chroot prefix)
|
||||
Ok(Path::new(dest_root).join(filename))
|
||||
}
|
||||
|
||||
fn ensure_available_with_overlay(
|
||||
&self,
|
||||
src: &Path,
|
||||
dest_root: &str,
|
||||
upper: &Path,
|
||||
work: &Path,
|
||||
) -> io::Result<super::api::OverlayStaging> {
|
||||
let dest_dir = Path::new(&self.path).join(dest_root.trim_start_matches('/'));
|
||||
std::fs::create_dir_all(&dest_dir)?;
|
||||
let filename = src
|
||||
.file_name()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "Invalid source path"))?;
|
||||
let dest_path = dest_dir.join(filename);
|
||||
|
||||
// The upper/work dirs are the persistent ones of a build session:
|
||||
// mounting them again exposes the previous attempt's build
|
||||
// artifacts over the (live) host tree. Mount failure is an ERROR,
|
||||
// never a silent copy fallback: a copy would merge the host tree
|
||||
// into the stale staged tree of the previous attempt (old build
|
||||
// stamps, dropped host deletions) — the caller decides to wipe and
|
||||
// re-stage instead.
|
||||
if !src.is_dir() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"overlay staging only applies to directories",
|
||||
));
|
||||
}
|
||||
if !is_overlayfs_available() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"overlayfs is not available on this system",
|
||||
));
|
||||
}
|
||||
self.mount_overlay(src, &dest_path, Some(upper), Some(work))?;
|
||||
debug!(
|
||||
"Mounted overlay for {} at {} (reused upper {})",
|
||||
src.display(),
|
||||
dest_path.display(),
|
||||
upper.display()
|
||||
);
|
||||
Ok(super::api::OverlayStaging {
|
||||
path: Path::new(dest_root).join(filename),
|
||||
overlay: true,
|
||||
})
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> io::Result<()> {
|
||||
let mounts = self.overlay_mounts.lock().unwrap();
|
||||
for mount_path in mounts.iter() {
|
||||
debug!("Unmounting overlay at {}", mount_path.display());
|
||||
let is_root = crate::utils::root::is_root().unwrap_or(false);
|
||||
let mut cmd = self
|
||||
.parent()
|
||||
.command(if is_root { "umount" } else { "sudo" });
|
||||
if !is_root {
|
||||
cmd.arg("umount");
|
||||
}
|
||||
let status = cmd.arg(mount_path.to_string_lossy().to_string()).status()?;
|
||||
if !status.success() {
|
||||
log::warn!("Failed to unmount overlay at {}", mount_path.display());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn retrieve_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
let host_src = Path::new(&self.path).join(src.to_string_lossy().trim_start_matches('/'));
|
||||
self.parent().retrieve_path(&host_src, dest)
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
let host_path = Path::new(&self.path).join(path.to_string_lossy().trim_start_matches('/'));
|
||||
let host_entries = self.parent().list_files(&host_path)?;
|
||||
|
||||
let mut entries = Vec::new();
|
||||
let prefix = Path::new(&self.path);
|
||||
for entry in host_entries {
|
||||
if let Ok(rel_path) = entry.strip_prefix(prefix) {
|
||||
entries.push(Path::new("/").join(rel_path));
|
||||
} else {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
self.command(program, args, env, cwd).status()
|
||||
}
|
||||
|
||||
fn run_captured(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
sink: Arc<dyn LineSink>,
|
||||
) -> io::Result<std::process::ExitStatus> {
|
||||
// Forward the sink to the wrapping command: the parent context driver
|
||||
// is responsible for the actual capture (and may chain further, e.g.
|
||||
// unshare over ssh).
|
||||
let mut cmd = self.command(program, args, env, cwd);
|
||||
cmd.capture(sink);
|
||||
cmd.status()
|
||||
}
|
||||
|
||||
fn run_output(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::Output> {
|
||||
self.command(program, args, env, cwd).output()
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
// Create a temporary directory inside the chroot with unique naming
|
||||
// Sub-second precision and an atomic create, like the local
|
||||
// driver: concurrent callers racing on the same name must not
|
||||
// share a directory, so an existing target falls through to the
|
||||
// next attempt instead of a probe-then-create window.
|
||||
let base_timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
let work_dir_name = if attempt == 0 {
|
||||
format!("pkh-build-{base_timestamp}")
|
||||
} else {
|
||||
format!("pkh-build-{base_timestamp}-{attempt}")
|
||||
};
|
||||
|
||||
let work_dir_inside_chroot = format!("/tmp/{work_dir_name}");
|
||||
let host_path = Path::new(&self.path).join("tmp").join(&work_dir_name);
|
||||
|
||||
match std::fs::create_dir(&host_path) {
|
||||
Ok(()) => {
|
||||
debug!(
|
||||
"Created work directory: {} (host: {})",
|
||||
work_dir_inside_chroot,
|
||||
host_path.display()
|
||||
);
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
|
||||
attempt += 1;
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
// Return the path as it appears inside the chroot
|
||||
return Ok(work_dir_inside_chroot);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
let host_src = Path::new(&self.path).join(src.to_string_lossy().trim_start_matches('/'));
|
||||
let host_dest = Path::new(&self.path).join(dest.to_string_lossy().trim_start_matches('/'));
|
||||
self.parent().copy_path(&host_src, &host_dest)
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
let host_path = Path::new(&self.path).join(path.to_string_lossy().trim_start_matches('/'));
|
||||
self.parent().read_file(&host_path)
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
let host_path = Path::new(&self.path).join(path.to_string_lossy().trim_start_matches('/'));
|
||||
self.parent().write_file(&host_path, content)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
let host_path = Path::new(&self.path).join(path.to_string_lossy().trim_start_matches('/'));
|
||||
self.parent().exists(&host_path)
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
let host_path = Path::new(&self.path).join(path.to_string_lossy().trim_start_matches('/'));
|
||||
Ok(host_path.is_dir())
|
||||
}
|
||||
}
|
||||
|
||||
impl UnshareDriver {
|
||||
fn parent(&self) -> &Context {
|
||||
self.parent
|
||||
.as_ref()
|
||||
.expect("UnshareDriver requires a parent context")
|
||||
}
|
||||
|
||||
/// Mount `src` as an overlay at `dest_path` inside the chroot.
|
||||
///
|
||||
/// `upper`/`work` override the per-mount random directories: the
|
||||
/// resumable-session staging passes its persistent upperdir so build
|
||||
/// artifacts survive across attempts. On success, the overlay is
|
||||
/// tracked in `overlay_mounts` for later cleanup. On failure, the
|
||||
/// caller should fall back to the copy-based approach.
|
||||
fn mount_overlay(
|
||||
&self,
|
||||
src: &Path,
|
||||
dest_path: &Path,
|
||||
upper: Option<&Path>,
|
||||
work: Option<&Path>,
|
||||
) -> io::Result<()> {
|
||||
// Create unique upper/work dirs inside the chroot unless the caller
|
||||
// pinned them (session reuse).
|
||||
let overlay_base = Path::new(&self.path).join("pkh-overlay");
|
||||
let id = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let upper_dir = upper
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| overlay_base.join(format!("upper-{}", id)));
|
||||
let work_dir = work
|
||||
.map(Path::to_path_buf)
|
||||
.unwrap_or_else(|| overlay_base.join(format!("work-{}", id)));
|
||||
|
||||
fs::create_dir_all(&upper_dir)?;
|
||||
fs::create_dir_all(&work_dir)?;
|
||||
fs::create_dir_all(dest_path)?;
|
||||
|
||||
// Canonicalize the source path so overlayfs can find it reliably
|
||||
let src_canonical = src.canonicalize().map_err(|e| {
|
||||
io::Error::new(
|
||||
e.kind(),
|
||||
format!("Failed to canonicalize '{}': {}", src.display(), e),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Mount overlay from host (requires CAP_SYS_ADMIN, same as bind_mount_proc).
|
||||
// Use .output() instead of .status() so that mount errors are captured
|
||||
// rather than printed to stderr — the caller will fall back to a copy.
|
||||
let is_root = crate::utils::root::is_root().unwrap_or(false);
|
||||
let mut cmd = self
|
||||
.parent()
|
||||
.command(if is_root { "mount" } else { "sudo" });
|
||||
if !is_root {
|
||||
cmd.arg("mount");
|
||||
}
|
||||
let output = cmd
|
||||
.arg("-t")
|
||||
.arg("overlay")
|
||||
.arg("overlay")
|
||||
.arg("-o")
|
||||
.arg(format!(
|
||||
"lowerdir={},upperdir={},workdir={}",
|
||||
src_canonical.display(),
|
||||
upper_dir.display(),
|
||||
work_dir.display()
|
||||
))
|
||||
.arg(dest_path.to_string_lossy().to_string())
|
||||
.output()?;
|
||||
|
||||
if !output.status.success() {
|
||||
// Clean up dirs we created (never the caller-pinned persistent
|
||||
// upper/work of a session: they hold the previous attempt's
|
||||
// build artifacts)
|
||||
if upper.is_none() {
|
||||
let _ = fs::remove_dir_all(&upper_dir);
|
||||
let _ = fs::remove_dir_all(&work_dir);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(io::Error::other(format!(
|
||||
"Overlay mount of '{}' at '{}' failed: {}",
|
||||
src.display(),
|
||||
dest_path.display(),
|
||||
stderr.trim()
|
||||
)));
|
||||
}
|
||||
|
||||
debug!(
|
||||
"Overlay-mounted {} at {} (upper: {}, work: {})",
|
||||
src.display(),
|
||||
dest_path.display(),
|
||||
upper_dir.display(),
|
||||
work_dir.display()
|
||||
);
|
||||
|
||||
// Track for cleanup
|
||||
self.overlay_mounts
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(dest_path.to_path_buf());
|
||||
|
||||
// The overlay exposes the source tree verbatim: strip VCS metadata
|
||||
// (e.g. '.git') whose presence would flip autotools 'building from
|
||||
// git' detection and activate maintainer-only regeneration rules
|
||||
// (see is_vcs_dir_name). Removals land as whiteouts in the upper
|
||||
// layer, leaving the lowerdir untouched.
|
||||
if let Err(e) = super::prune_vcs_dirs(dest_path) {
|
||||
log::warn!(
|
||||
"Failed to prune VCS metadata from '{}': {}",
|
||||
dest_path.display(),
|
||||
e
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn command(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> ContextCommand<'_> {
|
||||
let mapped = env
|
||||
.iter()
|
||||
.any(|(key, value)| key == MAPPED_IDENTITY_ENV && value == "1");
|
||||
let mut cmd = self.parent().command("unshare");
|
||||
|
||||
cmd.envs(env.iter().cloned());
|
||||
|
||||
cmd.arg("--map-user=65536")
|
||||
.arg("--map-group=65536")
|
||||
.arg("--pid")
|
||||
.arg("--ipc")
|
||||
.arg("--uts")
|
||||
.arg("--user")
|
||||
.arg("--cgroup")
|
||||
.arg("--map-auto")
|
||||
.arg("-r")
|
||||
.arg("--mount")
|
||||
.arg("--fork");
|
||||
|
||||
if mapped {
|
||||
// The rules steps of a rootless build (see the marker in
|
||||
// `crate::deb::local`): no chroot(2) — the wrapper pivots into
|
||||
// the chroot and only then creates the nested build-identity
|
||||
// namespace, because a user namespace cannot be created from a
|
||||
// chrooted process (the kernel refuses with EPERM) and
|
||||
// chroot(2) cannot run inside one. The cwd is taken inside the
|
||||
// script, after the pivot.
|
||||
cmd.arg("--").arg("bash").arg("-c").arg(build_pivot_script(
|
||||
&self.path,
|
||||
cwd,
|
||||
program,
|
||||
args,
|
||||
MAPPED_BUILD_ID,
|
||||
));
|
||||
} else {
|
||||
cmd.arg("-R").arg(&self.path);
|
||||
|
||||
if let Some(dir) = cwd {
|
||||
cmd.arg("-w").arg(dir);
|
||||
}
|
||||
|
||||
// Build the bash command: set up /dev/pts and run the program
|
||||
// /proc should already be bind-mounted from the host before entering the namespace
|
||||
cmd.arg("--")
|
||||
.arg("bash")
|
||||
.arg("-c")
|
||||
.arg(build_namespace_script(program, args));
|
||||
}
|
||||
|
||||
cmd
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the rules-mode wrapper script: pivot into the chroot, bring up
|
||||
/// `/proc` and `/dev/pts` inside it, then drop into the nested
|
||||
/// build-identity namespace (mapping the namespace's root onto
|
||||
@@ -813,3 +709,49 @@ mod tests {
|
||||
.expect("the pivot script must parse: {script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod path_tests {
|
||||
use super::*;
|
||||
use crate::sandbox::Host;
|
||||
|
||||
#[test]
|
||||
fn paths_preserve_the_chroot_boundary() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let driver = UnshareDriver::new(root.path().to_path_buf(), Arc::new(Host::new()));
|
||||
|
||||
let dir = driver.create_temp_dir().unwrap();
|
||||
assert!(dir.starts_with("/tmp/pkh-build-"));
|
||||
|
||||
let file = Path::new(&dir).join("hello.txt");
|
||||
driver.write_file(&file, "hello").unwrap();
|
||||
assert_eq!(driver.read_file(&file).unwrap(), "hello");
|
||||
assert!(driver.exists(&file).unwrap());
|
||||
assert!(!driver.is_dir(&file).unwrap());
|
||||
assert_eq!(
|
||||
driver.list_files(Path::new(&dir)).unwrap(),
|
||||
vec![file.clone()]
|
||||
);
|
||||
|
||||
let host = tempfile::tempdir().unwrap();
|
||||
let src = host.path().join("src");
|
||||
fs::create_dir_all(src.join(".git")).unwrap();
|
||||
fs::write(src.join("keep"), "keep").unwrap();
|
||||
fs::write(src.join(".git/HEAD"), "ref").unwrap();
|
||||
let dest = Path::new(&dir).join("src");
|
||||
let opts = PutOptions {
|
||||
reuse: None,
|
||||
skip_dirs: vec![".git".into()],
|
||||
};
|
||||
assert_eq!(driver.put(&src, &dest, &opts).unwrap(), PutOutcome::Fresh);
|
||||
assert!(driver.exists(&dest.join("keep")).unwrap());
|
||||
assert!(!driver.exists(&dest.join(".git")).unwrap());
|
||||
|
||||
let out = host.path().join("out");
|
||||
driver.get(&dest, &out).unwrap();
|
||||
assert_eq!(fs::read_to_string(out.join("keep")).unwrap(), "keep");
|
||||
|
||||
driver.remove(Path::new(&dir)).unwrap();
|
||||
assert!(!driver.exists(Path::new(&dir)).unwrap());
|
||||
}
|
||||
}
|
||||
+8
-9
@@ -1,16 +1,15 @@
|
||||
//! Testbed lifecycle: where and how the tests run.
|
||||
//!
|
||||
//! A testbed is a [`Context`] plus its teardown. chroot mode reuses the
|
||||
//! `pkh deb` machinery wholesale (an ephemeral unshare context guarded by
|
||||
//! [`crate::sandbox::Unshare`], bootstrapped from the
|
||||
//! same cached mmdebstrap tarballs); local mode is the current context
|
||||
//! used directly. The testbed itself is disposable per run: autopkgtests
|
||||
//! may break it, and the next run starts from a clean bootstrap.
|
||||
//! A testbed is a [`Sandbox`] plus its teardown. chroot mode reuses the
|
||||
//! `pkh deb` machinery wholesale (a [`crate::sandbox::Unshare`] sandbox,
|
||||
//! bootstrapped from the same cached mmdebstrap tarballs); local mode is
|
||||
//! the host used directly. The testbed itself is disposable per run:
|
||||
//! autopkgtests may break it, and the next run starts from a clean
|
||||
//! bootstrap.
|
||||
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::context::Context;
|
||||
use crate::deb::BuildProfiler;
|
||||
use crate::report::BuildView;
|
||||
use crate::sandbox::{Host, Sandbox, SandboxExt, Unshare};
|
||||
@@ -20,7 +19,7 @@ use crate::test::options::TestMode;
|
||||
pub(crate) enum Bed {
|
||||
/// An ephemeral unshare chroot.
|
||||
Chroot(Arc<Unshare>),
|
||||
/// The current context, used directly.
|
||||
/// The host, used directly.
|
||||
Local(Arc<dyn Sandbox>),
|
||||
}
|
||||
|
||||
@@ -30,7 +29,7 @@ impl Bed {
|
||||
mode: TestMode,
|
||||
series: &str,
|
||||
arch: &str,
|
||||
base_ctx: Arc<Context>,
|
||||
base_ctx: Arc<dyn Sandbox>,
|
||||
view: &dyn BuildView,
|
||||
) -> Result<Bed, Box<dyn Error>> {
|
||||
match mode {
|
||||
|
||||
+5
-8
@@ -1,8 +1,8 @@
|
||||
//! Run a source package's DEP-8 as-installed tests (`pkh test`).
|
||||
//!
|
||||
//! The runner is native for the chroot and local testbeds: the testbed
|
||||
//! is a pkh context (an ephemeral unshare chroot bootstrapped exactly
|
||||
//! like a `pkh deb` build chroot, or the current context directly), and
|
||||
//! is a sandbox (an ephemeral unshare chroot bootstrapped exactly like a
|
||||
//! `pkh deb` build chroot, or the host directly), and
|
||||
//! the DEP-8 per-test contract lives in [`runner`]. `--mode vm` execs
|
||||
//! the installed autopkgtest with its qemu runner instead — the one
|
||||
//! backend pkh does not reimplement (serial-console protocol, image
|
||||
@@ -153,8 +153,8 @@ pub async fn run(opts: TestOptions<'_>) -> Result<TestRunReport, Box<dyn std::er
|
||||
|
||||
if mode == TestMode::Local {
|
||||
log::warn!(
|
||||
"Tests run directly on the current context: they install packages \
|
||||
and can rewrite it. Use the default chroot mode for isolation."
|
||||
"Tests run directly on the host: they install packages and can \
|
||||
rewrite it. Use the default chroot mode for isolation."
|
||||
);
|
||||
}
|
||||
let run_dir = create_run_dir(&package, &series, &arch)?;
|
||||
@@ -164,10 +164,7 @@ pub async fn run(opts: TestOptions<'_>) -> Result<TestRunReport, Box<dyn std::er
|
||||
.then(|| Arc::new(TerminalLines) as Arc<dyn LineSink>)
|
||||
});
|
||||
|
||||
let base_ctx = Arc::new(
|
||||
crate::context::Context::new(crate::context::ContextConfig::Local)
|
||||
.map_err(|e| format!("cannot create a local testbed context: {e}"))?,
|
||||
);
|
||||
let base_ctx: Arc<dyn crate::sandbox::Sandbox> = Arc::new(crate::sandbox::Host::new());
|
||||
let bed = Bed::prepare(mode, &series, &arch, base_ctx, view).await?;
|
||||
let ctx = bed.ctx();
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ pub enum TestMode {
|
||||
/// chroot (shared tarball cache).
|
||||
#[default]
|
||||
Chroot,
|
||||
/// The current context directly: no isolation, tests can rewrite it.
|
||||
/// The host directly: no isolation, tests can rewrite it.
|
||||
Local,
|
||||
/// A qemu virtual machine, through the installed autopkgtest's qemu
|
||||
/// runner — the one backend pkh does not reimplement.
|
||||
|
||||
+1
-113
@@ -8,7 +8,7 @@
|
||||
//! - all `log` output is written to a per-test file under
|
||||
//! `target/pkh-test-logs/` instead of the terminal, so concurrent tests
|
||||
//! never interleave their logs;
|
||||
//! - subprocesses launched through a [`crate::context::Context`] (the whole
|
||||
//! - subprocesses launched through a [`crate::sandbox::Sandbox`] (the whole
|
||||
//! build pipeline: apt, dpkg, make, compilers, ...) are captured line by
|
||||
//! line into the same per-test file instead of inheriting the terminal,
|
||||
//! which used to garble the `cargo test` output beyond readability;
|
||||
@@ -44,12 +44,6 @@ mod imp {
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn wrap_driver(
|
||||
driver: Box<dyn crate::context::ContextDriver + Send + Sync>,
|
||||
) -> Box<dyn crate::context::ContextDriver + Send + Sync> {
|
||||
driver
|
||||
}
|
||||
|
||||
pub(crate) fn run_logged(
|
||||
cmd: &mut std::process::Command,
|
||||
) -> std::io::Result<std::process::ExitStatus> {
|
||||
@@ -78,7 +72,6 @@ mod imp {
|
||||
use std::process::{Command, ExitStatus};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use crate::context::ContextDriver;
|
||||
use crate::exec::{LineSink, Stream};
|
||||
|
||||
/// Directory receiving one log file per test
|
||||
@@ -350,111 +343,6 @@ mod imp {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Wrap a context driver so that plain (uncaptured) `run`/`run_output`
|
||||
/// commands still have their output logged in test runs instead of
|
||||
/// inheriting the terminal
|
||||
pub(crate) fn wrap_driver(
|
||||
driver: Box<dyn ContextDriver + Send + Sync>,
|
||||
) -> Box<dyn ContextDriver + Send + Sync> {
|
||||
if !active() {
|
||||
return driver;
|
||||
}
|
||||
Box::new(CapturingDriver { inner: driver })
|
||||
}
|
||||
|
||||
struct CapturingDriver {
|
||||
inner: Box<dyn ContextDriver + Send + Sync>,
|
||||
}
|
||||
|
||||
impl ContextDriver for CapturingDriver {
|
||||
fn run(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<ExitStatus> {
|
||||
match subprocess_sink() {
|
||||
Some(sink) => self.inner.run_captured(program, args, env, cwd, sink),
|
||||
None => self.inner.run(program, args, env, cwd),
|
||||
}
|
||||
}
|
||||
|
||||
fn run_captured(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
sink: Arc<dyn LineSink>,
|
||||
) -> io::Result<ExitStatus> {
|
||||
self.inner.run_captured(program, args, env, cwd, sink)
|
||||
}
|
||||
|
||||
fn run_output(
|
||||
&self,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
env: &[(String, String)],
|
||||
cwd: Option<&str>,
|
||||
) -> io::Result<std::process::Output> {
|
||||
let sink = subprocess_sink();
|
||||
// Commands whose stdout is parsed still need the real output, so
|
||||
// delegate to run_output and additionally forward the lines to
|
||||
// the per-test log
|
||||
let output = self.inner.run_output(program, args, env, cwd)?;
|
||||
if let Some(sink) = sink {
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
sink.line(Stream::Stdout, line);
|
||||
}
|
||||
for line in String::from_utf8_lossy(&output.stderr).lines() {
|
||||
sink.line(Stream::Stderr, line);
|
||||
}
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn ensure_available(&self, src: &Path, dest_root: &str) -> io::Result<PathBuf> {
|
||||
self.inner.ensure_available(src, dest_root)
|
||||
}
|
||||
|
||||
fn retrieve_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
self.inner.retrieve_path(src, dest)
|
||||
}
|
||||
|
||||
fn list_files(&self, path: &Path) -> io::Result<Vec<PathBuf>> {
|
||||
self.inner.list_files(path)
|
||||
}
|
||||
|
||||
fn create_temp_dir(&self) -> io::Result<String> {
|
||||
self.inner.create_temp_dir()
|
||||
}
|
||||
|
||||
fn copy_path(&self, src: &Path, dest: &Path) -> io::Result<()> {
|
||||
self.inner.copy_path(src, dest)
|
||||
}
|
||||
|
||||
fn read_file(&self, path: &Path) -> io::Result<String> {
|
||||
self.inner.read_file(path)
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &Path, content: &str) -> io::Result<()> {
|
||||
self.inner.write_file(path, content)
|
||||
}
|
||||
|
||||
fn exists(&self, path: &Path) -> io::Result<bool> {
|
||||
self.inner.exists(path)
|
||||
}
|
||||
|
||||
fn is_dir(&self, path: &Path) -> io::Result<bool> {
|
||||
self.inner.is_dir(path)
|
||||
}
|
||||
|
||||
fn cleanup(&self) -> io::Result<()> {
|
||||
self.inner.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a command from test code with its output captured into the
|
||||
/// per-test log file (the console stays quiet; the output is available
|
||||
/// on failure)
|
||||
|
||||
Reference in new issue
Block a user