phoebus_os/installer-rs/crates/phoebus-executor/src/exec.rs
Phoebus b4a6b5df80
Some checks are pending
ci / test (push) Waiting to run
feat(nvidia): hardware-driven driver policy, installed integration and live payload
- resolve the NVIDIA branch and kernel-module flavor from PCI device IDs
  (Turing+ open modules; Maxwell/Pascal/Volta proprietary, masked below 595;
  Fermi/Kepler fall back to nouveau, reported; unknown IDs reported)
- capture pci_id/pci_address in the probe; drive VIDEO_CARDS, package.use,
  package.accept_keywords, package.mask, modprobe.d and dracut from the plan,
  preserving hybrid Intel/AMD
- add the nvidia_drivers install stage (after the kernel, before boot) that
  emerges the driver, regenerates the initramfs, records /etc/phoebus/nvidia and
  fails the install on failure; sys update rebuilds modules and the initramfs
- refuse AI changes to x11-drivers/nvidia-drivers
- live ISO: signed non-free components, stable-kernel pin (testing 7.2 breaks
  the 550 driver), DKMS build for the exact kernel, gated pre-greetd load,
  fail-safe entry, gpu-report, and a --verify-live-nvidia build gate that runs
  on cached rootfs builds and fails on any missing component
- docs: ADR 0012, STATUS/CHANGELOG/HANDOFF, live README
- also carries the pending OpenCode model-variant/streaming changes and fixes
  the GUI bridge install thread join that could hang
2026-09-22 21:53:28 -07:00

248 lines
7.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 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(
&spec.stage,
&spec.operation,
&spec.program,
&spec.args,
output.status,
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 {
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(())
}
}
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());
}
}