phoebus_os/installer-rs/crates/phoebus-executor/src/exec.rs
Phoebus c52840645c
Some checks are pending
ci / test (push) Waiting to run
feat(stability): harden mutation locking, coordinated snapshots, and health inspection
- Introduce SystemLock with safe PID-liveness detection via /proc/<pid> to prevent concurrent mutation collisions and reclaim stale locks
- Coordinate paired @ and @var Btrfs snapshots for all high-risk mutations to prevent Portage VDB database drift during rollbacks
- Persist transaction log via tempfile + sync_all + atomic rename to ensure durability against unexpected power loss
- Add SystemAction::SystemStatus and sys status/health query reporting boot assessment counters, reboot state, storage headroom, and package lane readiness
- Unify natural language verbs (update/updates -> CheckUpdates, upgrade -> ApplyUpdates) and dynamic candidate-aware legacy install guidance
2026-09-30 04:19:14 -07:00

274 lines
8.6 KiB
Rust

//! Execution context: the single place commands are run and logged.
use std::path::{Path, PathBuf};
use phoebus_core::{Redactor, SecretString, TargetRoot};
use crate::command::{CommandOutput, CommandSpec, ProcessRunner};
use crate::error::{ExecError, Result};
use crate::log::Logger;
pub struct Exec {
pub runner: Box<dyn ProcessRunner>,
pub logger: Logger,
pub dry_run: bool,
pub root: PathBuf,
pub state_dir: PathBuf,
}
impl Exec {
pub fn new(
runner: Box<dyn ProcessRunner>,
logger: Logger,
dry_run: bool,
root: impl Into<PathBuf>,
state_dir: impl Into<PathBuf>,
) -> Self {
Self {
runner,
logger,
dry_run,
root: root.into(),
state_dir: state_dir.into(),
}
}
pub fn target(&self) -> TargetRoot {
TargetRoot::new(self.root.clone())
}
pub fn is_real(&self) -> bool {
self.runner.is_real()
}
pub fn register_secret(&self, secret: &SecretString) {
self.logger.register_secret(secret);
}
pub fn redactor(&self) -> &Redactor {
self.logger.redactor()
}
/// Run a command, honouring dry-run, and log it with its exit status.
pub fn run(&self, spec: CommandSpec) -> Result<CommandOutput> {
if self.dry_run {
self.logger
.dry_run(&spec.stage, &spec.operation, &spec.program, &spec.args);
return Ok(CommandOutput::dry_run());
}
let stdin_hidden = spec.stdin.is_some();
self.logger.command_start(
&spec.stage,
&spec.operation,
&spec.program,
&spec.args,
stdin_hidden,
);
let output = self.runner.execute(&spec)?;
self.logger.command(crate::log::CommandRecord {
stage: &spec.stage,
operation: &spec.operation,
program: &spec.program,
args: &spec.args,
status: output.status,
duration: output.duration,
stdin_hidden,
});
if !self.runner.is_streaming() {
if !output.stdout.is_empty() {
self.logger.output(&output.stdout);
}
if !output.stderr.is_empty() {
self.logger.output(&output.stderr);
}
}
if !output.success {
return Err(ExecError::command(crate::error::CommandFailure {
stage: spec.stage.clone(),
operation: spec.operation.clone(),
program: spec.program.clone(),
status: output.status,
stdout: self.redactor().redact(&output.stdout_lossy()),
stderr: self.redactor().redact(&output.stderr_lossy()),
}));
}
Ok(output)
}
/// Run a command and return its captured stdout on success.
pub fn run_capture(&self, spec: CommandSpec) -> Result<CommandOutput> {
self.run(spec)
}
/// Verify that all named commands are available in PATH.
pub fn require_tools(&self, tools: &[&str]) -> Result<()> {
for tool in tools {
if find_in_path(tool).is_none() {
return Err(ExecError::MissingTool((*tool).to_string()));
}
}
Ok(())
}
pub fn log_path(&self) -> &Path {
self.logger.path()
}
/// Mount the pseudo-filesystems required by a target chroot.
pub fn mount_chroot(&self) -> Result<()> {
let root = self.root.to_string_lossy().to_string();
self.run(
CommandSpec::new("chroot", "mount proc", "mount")
.args(["-t", "proc", "proc"])
.arg(format!("{root}/proc")),
)?;
self.run(
CommandSpec::new("chroot", "mount sysfs", "mount")
.args(["--rbind", "/sys"])
.arg(format!("{root}/sys")),
)?;
self.run(
CommandSpec::new("chroot", "mount devtmpfs", "mount")
.args(["--rbind", "/dev"])
.arg(format!("{root}/dev")),
)?;
let _ = self.run(
CommandSpec::new("chroot", "make /dev rslave", "mount")
.args(["--make-rslave"])
.arg(format!("{root}/dev")),
);
if self.root.join("run").is_dir() {
let _ = self.run(
CommandSpec::new("chroot", "mount tmpfs on /run", "mount")
.args(["-t", "tmpfs", "tmpfs"])
.arg(format!("{root}/run")),
);
}
Ok(())
}
pub fn umount_chroot(&self) -> Result<()> {
let root = self.root.to_string_lossy().to_string();
for sub in ["proc", "sys", "dev"] {
let _ = self.run(
CommandSpec::new("chroot", format!("unmount {sub}"), "umount")
.arg("-l")
.arg(format!("{root}/{sub}")),
);
}
Ok(())
}
/// Copy the host resolver configuration into the target so Portage can
/// reach the network. Best effort.
pub fn copy_resolv_conf(&self) -> Result<()> {
let src = Path::new("/etc/resolv.conf");
if !src.exists() {
return Ok(());
}
let dst = self.root.join("etc/resolv.conf");
if let Some(parent) = dst.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::copy(src, &dst);
Ok(())
}
/// Copy the installer log into the target for post-mortem analysis.
pub fn export_log(&self) -> Result<()> {
let dst_dir = self.root.join("var/log/phoebus-installer");
if std::fs::create_dir_all(&dst_dir).is_err() {
return Ok(());
}
let _ = std::fs::copy(self.logger.path(), dst_dir.join("install.log"));
Ok(())
}
}
/// Whether a tool is present in the intended target.
///
/// For the running root this is the host `PATH`. For an alternate root a query
/// runs inside the target chroot, so availability must be resolved from the
/// target's own binary directories rather than the host's, where a host tool
/// would otherwise leak into (or bypass) target operations.
pub fn tool_in_target(root: &Path, program: &str) -> bool {
if program.contains('/') {
let candidate = root.join(program.trim_start_matches('/'));
return is_executable(&candidate);
}
if root == Path::new("/") {
return find_in_path(program).is_some();
}
for dir in ["usr/bin", "usr/sbin", "usr/local/bin", "bin", "sbin"] {
if is_executable(&root.join(dir).join(program)) {
return true;
}
}
false
}
pub fn find_in_path(program: &str) -> Option<PathBuf> {
if program.contains('/') {
let p = PathBuf::from(program);
return if is_executable(&p) { Some(p) } else { None };
}
let path = std::env::var_os("PATH")?;
for dir in std::env::split_paths(&path) {
let candidate = dir.join(program);
if is_executable(&candidate) {
return Some(candidate);
}
}
None
}
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
match std::fs::metadata(path) {
Ok(meta) => meta.is_file() && meta.permissions().mode() & 0o111 != 0,
Err(_) => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::RecordingRunner;
use crate::log::Logger;
fn exec(runner: RecordingRunner) -> Exec {
let dir = tempfile::tempdir().unwrap();
// Leak the tempdir for the duration of the test process.
let path = dir.keep();
let logger = Logger::open(path.join("install.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn dry_run_does_not_execute() {
let runner = RecordingRunner::new();
let mut e = exec(runner.clone());
e.dry_run = true;
e.run(CommandSpec::new("s", "op", "sgdisk")).unwrap();
assert!(runner.recorded().is_empty());
}
#[test]
fn failing_command_returns_error_with_stage() {
let runner = RecordingRunner::new();
runner.fail("mkfs.btrfs", "no space");
let e = exec(runner.clone());
let err = e
.run(CommandSpec::new("storage_prepare", "mkfs", "mkfs.btrfs"))
.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("storage_prepare"));
assert!(msg.contains("mkfs.btrfs"));
}
#[test]
fn find_true_in_path() {
assert!(find_in_path("true").is_some());
assert!(find_in_path("definitely-not-a-real-tool-xyz").is_none());
}
}