//! 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, pub logger: Logger, pub dry_run: bool, pub root: PathBuf, pub state_dir: PathBuf, } impl Exec { pub fn new( runner: Box, logger: Logger, dry_run: bool, root: impl Into, state_dir: impl Into, ) -> 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 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 { 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(); let output = self.runner.execute(&spec)?; self.logger.command( &spec.stage, &spec.operation, &spec.program, &spec.args, output.status, output.duration, stdin_hidden, ); 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 { 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 { 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(()) } } pub fn find_in_path(program: &str) -> Option { 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()); } }