Some checks are pending
ci / test (push) Waiting to run
- 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
1029 lines
36 KiB
Rust
1029 lines
36 KiB
Rust
//! Execution of typed system actions after approval.
|
|
//!
|
|
//! These functions are the privileged broker. The model never calls them
|
|
//! directly; a human-approved, validated `SystemAction` does.
|
|
|
|
use std::path::Path;
|
|
|
|
use phoebus_core::action::SystemAction;
|
|
use phoebus_core::effects::{changed_materially, parse_emerge_pretend, ResolvedPlan};
|
|
use phoebus_core::transaction::TransactionOutcome;
|
|
|
|
use crate::auth::DestructiveAuthorization;
|
|
use crate::command::{CommandOutput, CommandSpec};
|
|
use crate::error::{ExecError, Result};
|
|
use crate::exec::Exec;
|
|
use crate::portage;
|
|
use crate::snapshot;
|
|
|
|
#[derive(Debug)]
|
|
pub struct ActionOutcome {
|
|
pub action: SystemAction,
|
|
pub output: String,
|
|
pub snapshot: Option<String>,
|
|
}
|
|
|
|
/// Human-readable preview shown before approval.
|
|
pub fn preview(action: &SystemAction) -> String {
|
|
let mut out = String::new();
|
|
out.push_str("Proposed action:\n");
|
|
out.push_str(&format!(" {}\n", action.describe()));
|
|
out.push_str(&format!(" risk: {:?}\n", action.risk()));
|
|
if action.is_mutating() {
|
|
out.push_str(" this will modify the system.\n");
|
|
}
|
|
out
|
|
}
|
|
|
|
/// Whether the command acts on the running system (`/`) rather than a mounted
|
|
/// alternate target.
|
|
fn is_host_root(root: &Path) -> bool {
|
|
root == Path::new("/")
|
|
}
|
|
|
|
/// Build a command that acts on the intended system: directly for the running
|
|
/// root, or inside the target chroot for an alternate root. This is the single
|
|
/// place package, service and Flatpak commands are rooted, so preview and
|
|
/// execution always target the same system.
|
|
fn target_spec(
|
|
root: &Path,
|
|
stage: &str,
|
|
operation: &str,
|
|
program: &str,
|
|
args: &[String],
|
|
) -> CommandSpec {
|
|
if is_host_root(root) {
|
|
CommandSpec::new(stage, operation, program).args(args.iter().cloned())
|
|
} else {
|
|
portage::chroot_spec(stage, operation, root, program, args)
|
|
}
|
|
}
|
|
|
|
/// Refuse an operation that genuinely needs the running system (e.g. service
|
|
/// status, start, stop, restart) when an alternate root was requested. This
|
|
/// runs before any command is built, so nothing is invoked against the host.
|
|
fn require_host_root(root: &Path, operation: &str) -> Result<()> {
|
|
if is_host_root(root) {
|
|
Ok(())
|
|
} else {
|
|
Err(ExecError::operation(
|
|
"sys",
|
|
operation,
|
|
format!(
|
|
"cannot target the alternate root {}; this operation needs the \
|
|
running system",
|
|
root.display()
|
|
),
|
|
))
|
|
}
|
|
}
|
|
|
|
/// Run a mutating command against the intended system.
|
|
fn run_in_target(
|
|
exec: &Exec,
|
|
root: &Path,
|
|
stage: &str,
|
|
operation: &str,
|
|
program: &str,
|
|
args: &[String],
|
|
) -> Result<CommandOutput> {
|
|
exec.run(target_spec(root, stage, operation, program, args))
|
|
}
|
|
|
|
/// Capture a read-only command against the intended system. Output is returned
|
|
/// regardless of exit status (inspection commands report state, not failure).
|
|
fn capture_in_target(
|
|
exec: &Exec,
|
|
root: &Path,
|
|
stage: &str,
|
|
operation: &str,
|
|
program: &str,
|
|
args: &[String],
|
|
) -> Result<CommandOutput> {
|
|
exec.runner
|
|
.execute(&target_spec(root, stage, operation, program, args))
|
|
}
|
|
|
|
/// `systemctl` for boot enable/disable. On the host it acts on PID 1; on an
|
|
/// alternate root it uses `--root`, which only writes symlinks under the
|
|
/// target, so the host's service state is never touched.
|
|
fn systemctl_spec(root: &Path, operation: &str, verb: &str, name: &str) -> CommandSpec {
|
|
if is_host_root(root) {
|
|
CommandSpec::new("sys", operation, "systemctl").args([verb, name])
|
|
} else {
|
|
CommandSpec::new("sys", operation, "systemctl")
|
|
.arg("--root")
|
|
.arg(root.to_string_lossy().to_string())
|
|
.arg(verb)
|
|
.arg(name)
|
|
}
|
|
}
|
|
|
|
/// The Portage arguments that produce a resolved pretend plan for an action,
|
|
/// or `None` when the action is not a Portage transaction.
|
|
fn pretend_args(action: &SystemAction) -> Option<Vec<String>> {
|
|
match action {
|
|
SystemAction::InstallPackage { atom } => Some(vec![
|
|
"--pretend".into(),
|
|
"--color=n".into(),
|
|
"--".into(),
|
|
atom.clone(),
|
|
]),
|
|
SystemAction::RemovePackage { atom } => Some(vec![
|
|
"--pretend".into(),
|
|
"--unmerge".into(),
|
|
"--color=n".into(),
|
|
"--".into(),
|
|
atom.clone(),
|
|
]),
|
|
SystemAction::UpdateSystem => Some(vec![
|
|
"--pretend".into(),
|
|
"--update".into(),
|
|
"--deep".into(),
|
|
"--newuse".into(),
|
|
"--color=n".into(),
|
|
"--".into(),
|
|
"@world".into(),
|
|
]),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Resolve exactly what a package action will do. Non-Portage actions yield an
|
|
/// empty plan. A plan's digest can be bound to an approval.
|
|
pub fn resolve_effects(exec: &Exec, action: &SystemAction, root: &Path) -> Result<ResolvedPlan> {
|
|
action
|
|
.validate()
|
|
.map_err(|e| ExecError::operation("sys", "validate action", e))?;
|
|
let Some(args) = pretend_args(action) else {
|
|
return Ok(ResolvedPlan::default());
|
|
};
|
|
// Same rooting as execution, so the reviewed plan describes the action that
|
|
// will actually run.
|
|
let spec = target_spec(root, "sys", "resolve effects", "emerge", &args);
|
|
let out = exec.run_capture(spec)?;
|
|
let mut plan = parse_emerge_pretend(&out.stdout_lossy());
|
|
if !plan.established {
|
|
return Err(ExecError::operation(
|
|
"sys",
|
|
"resolve effects",
|
|
"could not establish the package plan from emerge --pretend; \
|
|
refusing to proceed unreviewed",
|
|
));
|
|
}
|
|
if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
|
|
plan.recovery_point = Some("a protective snapshot before the change".into());
|
|
}
|
|
Ok(plan)
|
|
}
|
|
|
|
/// Execute an action after re-resolving it against the approved digest. If the
|
|
/// plan changed materially since review, execution is refused.
|
|
pub fn execute_checked(
|
|
exec: &Exec,
|
|
action: &SystemAction,
|
|
auth: Option<&DestructiveAuthorization>,
|
|
root: &Path,
|
|
approved: Option<&ResolvedPlan>,
|
|
) -> Result<ActionOutcome> {
|
|
if let Some(approved) = approved {
|
|
let current = resolve_effects(exec, action, root)?;
|
|
if changed_materially(approved, ¤t) {
|
|
return Err(ExecError::operation(
|
|
"sys",
|
|
"plan changed",
|
|
format!(
|
|
"the reviewed plan changed before execution (approved {}, now {}); \
|
|
re-run and review again",
|
|
&approved.digest[..approved.digest.len().min(12)],
|
|
¤t.digest[..current.digest.len().min(12)]
|
|
),
|
|
));
|
|
}
|
|
}
|
|
execute(exec, action, auth, root)
|
|
}
|
|
|
|
/// The result of running a reviewed multi-action plan.
|
|
#[derive(Debug, Default)]
|
|
pub struct PlanOutcome {
|
|
/// `(action, output)` for actions that completed, in execution order.
|
|
pub completed: Vec<(String, String)>,
|
|
/// `(action, error)` for the action that failed, if any.
|
|
pub failure: Option<(String, String)>,
|
|
/// Every action's status in order, including the ones never attempted
|
|
/// because an earlier action aborted the plan.
|
|
pub outcomes: Vec<TransactionOutcome>,
|
|
/// The most recent protective snapshot reported by an action.
|
|
pub snapshot: Option<String>,
|
|
}
|
|
|
|
/// Execute a reviewed plan action by action, stopping at the first failure and
|
|
/// recording later actions as unattempted. This is the single execution path
|
|
/// shared by the assistant and any multi-step caller, so partial failure is
|
|
/// reported truthfully rather than as success.
|
|
pub fn execute_plan(
|
|
exec: &Exec,
|
|
steps: &[(SystemAction, ResolvedPlan)],
|
|
auth: Option<&DestructiveAuthorization>,
|
|
root: &Path,
|
|
) -> PlanOutcome {
|
|
let mut outcome = PlanOutcome::default();
|
|
for (action, resolved) in steps {
|
|
let described = action.describe();
|
|
if outcome.failure.is_some() {
|
|
outcome
|
|
.outcomes
|
|
.push(TransactionOutcome::unattempted(described));
|
|
continue;
|
|
}
|
|
match execute_checked(exec, action, auth, root, Some(resolved)) {
|
|
Ok(result) => {
|
|
if result.snapshot.is_some() {
|
|
outcome.snapshot = result.snapshot;
|
|
}
|
|
outcome
|
|
.outcomes
|
|
.push(TransactionOutcome::completed(described.clone()));
|
|
outcome.completed.push((described, result.output));
|
|
}
|
|
Err(e) => {
|
|
let detail = e.to_string();
|
|
outcome.outcomes.push(TransactionOutcome::failed(
|
|
described.clone(),
|
|
detail.clone(),
|
|
));
|
|
outcome.failure = Some((described, detail));
|
|
}
|
|
}
|
|
}
|
|
outcome
|
|
}
|
|
|
|
pub fn execute(
|
|
exec: &Exec,
|
|
action: &SystemAction,
|
|
auth: Option<&DestructiveAuthorization>,
|
|
root: &Path,
|
|
) -> Result<ActionOutcome> {
|
|
// The execution boundary validates every action regardless of its source
|
|
// (manual phrase, JSON, or AI plan), so an invalid value can never reach a
|
|
// command.
|
|
action
|
|
.validate()
|
|
.map_err(|e| ExecError::operation("sys", "validate action", e))?;
|
|
|
|
if action.is_mutating() && auth.is_none() {
|
|
return Err(ExecError::NotAuthorized(action.describe()));
|
|
}
|
|
|
|
// Rollback moves the root, `/var` and the boot selection together and takes
|
|
// its own pre-rollback snapshot, so it must not run through the generic
|
|
// protective-snapshot path below.
|
|
if let SystemAction::Undo { snapshot } = action {
|
|
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
|
|
let outcome = crate::rollback::execute(exec, auth, root, snapshot.as_deref())?;
|
|
let mut output = format!(
|
|
"rollback activated: {} -> {}\nnext boot uses {}\nreboot to complete; \
|
|
a known-good previous entry is kept",
|
|
outcome.state.target_snapshot, outcome.state.root_subvol, outcome.state.root_subvol
|
|
);
|
|
for warning in &outcome.warnings {
|
|
output.push_str(&format!("\nwarning: {warning}"));
|
|
}
|
|
return Ok(ActionOutcome {
|
|
action: action.clone(),
|
|
output,
|
|
snapshot: Some(outcome.state.target_snapshot),
|
|
});
|
|
}
|
|
|
|
let mut snapshot_id = None;
|
|
|
|
// A protective snapshot must exist before a high-risk change. If the
|
|
// snapshots subvolume is present but the snapshot cannot be created, fail
|
|
// closed rather than proceed without a recovery point. A system without a
|
|
// `.snapshots` subvolume (e.g. a non-Btrfs root) is a warning, not a block.
|
|
// The snapshot source is the target root itself, so an alternate root
|
|
// snapshots the target, never the host.
|
|
if action.risk() == phoebus_core::action::Risk::High && !exec.dry_run {
|
|
if root.join(snapshot::SNAPSHOT_DIR).is_dir() {
|
|
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
|
|
let source = root.to_string_lossy().to_string();
|
|
let record =
|
|
snapshot::create_and_record(exec, auth, root, &source, &action.describe())?;
|
|
// Preserve the recovery point so callers can record it.
|
|
snapshot_id = Some(record.id);
|
|
} else {
|
|
exec.logger.warn(format!(
|
|
"no {}/ subvolume; proceeding without a protective snapshot",
|
|
snapshot::SNAPSHOT_DIR
|
|
));
|
|
}
|
|
}
|
|
|
|
let output = match action {
|
|
SystemAction::InspectService { name } => {
|
|
require_host_root(root, "inspect service")?;
|
|
let out = capture_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"inspect service",
|
|
"systemctl",
|
|
&["status".into(), name.clone(), "--no-pager".into()],
|
|
)?;
|
|
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
|
|
}
|
|
SystemAction::EnableService { name } => {
|
|
let spec = systemctl_spec(root, "enable service", "enable", name);
|
|
exec.run(spec)?;
|
|
format!("enabled {name}")
|
|
}
|
|
SystemAction::DisableService { name } => {
|
|
let spec = systemctl_spec(root, "disable service", "disable", name);
|
|
exec.run(spec)?;
|
|
format!("disabled {name}")
|
|
}
|
|
SystemAction::StartService { name } => {
|
|
require_host_root(root, "start service")?;
|
|
let spec = systemctl_spec(root, "start service", "start", name);
|
|
exec.run(spec)?;
|
|
format!("started {name}")
|
|
}
|
|
SystemAction::StopService { name } => {
|
|
require_host_root(root, "stop service")?;
|
|
let spec = systemctl_spec(root, "stop service", "stop", name);
|
|
exec.run(spec)?;
|
|
format!("stopped {name}")
|
|
}
|
|
SystemAction::RestartService { name } => {
|
|
require_host_root(root, "restart service")?;
|
|
let spec = systemctl_spec(root, "restart service", "restart", name);
|
|
exec.run(spec)?;
|
|
format!("restarted {name}")
|
|
}
|
|
SystemAction::InspectPackage { atom } => {
|
|
let out = capture_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"inspect package",
|
|
"emerge",
|
|
&[
|
|
"--pretend".into(),
|
|
"--quiet".into(),
|
|
"--".into(),
|
|
atom.clone(),
|
|
],
|
|
)?;
|
|
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
|
|
}
|
|
SystemAction::InstallPackage { atom } => {
|
|
// Portage resolves a bare name (`vim`) or a full atom.
|
|
run_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"install package",
|
|
"emerge",
|
|
&["--ask=n".into(), "--".into(), atom.clone()],
|
|
)?;
|
|
format!("installed {atom} (Portage)")
|
|
}
|
|
SystemAction::RemovePackage { atom } => {
|
|
run_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"remove package",
|
|
"emerge",
|
|
&[
|
|
"--unmerge".into(),
|
|
"--ask=n".into(),
|
|
"--".into(),
|
|
atom.clone(),
|
|
],
|
|
)?;
|
|
format!("removed {atom} (Portage)")
|
|
}
|
|
SystemAction::SearchPackages { query } => {
|
|
let out = capture_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"search packages",
|
|
"emerge",
|
|
&[
|
|
"--search".into(),
|
|
"--quiet".into(),
|
|
"--".into(),
|
|
query.clone(),
|
|
],
|
|
)?;
|
|
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
|
|
}
|
|
SystemAction::FlatpakInstall { app_id } => {
|
|
run_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"install flatpak",
|
|
"flatpak",
|
|
&[
|
|
"install".into(),
|
|
"-y".into(),
|
|
"--".into(),
|
|
"flathub".into(),
|
|
app_id.clone(),
|
|
],
|
|
)?;
|
|
format!("installed Flatpak app {app_id}")
|
|
}
|
|
SystemAction::FlatpakRemove { app_id } => {
|
|
run_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"remove flatpak",
|
|
"flatpak",
|
|
&["uninstall".into(), "-y".into(), "--".into(), app_id.clone()],
|
|
)?;
|
|
format!("removed Flatpak app {app_id}")
|
|
}
|
|
SystemAction::FlatpakList => {
|
|
let out = capture_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"list flatpaks",
|
|
"flatpak",
|
|
&[
|
|
"list".into(),
|
|
"--app".into(),
|
|
"--columns=application,version,branch".into(),
|
|
],
|
|
)?;
|
|
let text = format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy());
|
|
if text.trim().is_empty() {
|
|
"no Flatpak applications installed".to_string()
|
|
} else {
|
|
text
|
|
}
|
|
}
|
|
SystemAction::NixPrepare { packages } => {
|
|
let prepared = crate::nix::prepare_dev_packages(exec, root, packages)?;
|
|
format!("realised Nix development packages: {}", prepared.join(", "))
|
|
}
|
|
SystemAction::UpdateSystem => {
|
|
run_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"update system",
|
|
"emerge",
|
|
&[
|
|
"--update".into(),
|
|
"--deep".into(),
|
|
"--newuse".into(),
|
|
"--".into(),
|
|
"@world".into(),
|
|
],
|
|
)?;
|
|
// A system with the NVIDIA out-of-tree driver must rebuild its
|
|
// modules against any newly installed kernel and regenerate the
|
|
// initramfs, so modules, userspace libraries and the boot image stay
|
|
// coherent before the next reboot. The record is written by the
|
|
// installer (or by the installed system's driver setup).
|
|
if root.join("etc/phoebus/nvidia").is_file() {
|
|
run_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"rebuild NVIDIA modules",
|
|
"emerge",
|
|
&["@module-rebuild".into()],
|
|
)?;
|
|
run_in_target(
|
|
exec,
|
|
root,
|
|
"sys",
|
|
"regenerate the initramfs",
|
|
"kernel-install",
|
|
&["add-all".into()],
|
|
)?;
|
|
}
|
|
"system update complete".to_string()
|
|
}
|
|
SystemAction::CreateSnapshot { operation } => {
|
|
let auth = auth.ok_or_else(|| ExecError::NotAuthorized(action.describe()))?;
|
|
let source = root.to_string_lossy().to_string();
|
|
let record = snapshot::create_and_record(exec, auth, root, &source, operation)?;
|
|
snapshot_id = Some(record.id.clone());
|
|
format!("snapshot created: {}", record.id)
|
|
}
|
|
// Handled before the match (it has its own snapshot/safety path).
|
|
SystemAction::Undo { .. } => "rollback handled by the dedicated path".to_string(),
|
|
SystemAction::PrepareUpdates => {
|
|
let cores = std::thread::available_parallelism()
|
|
.map(|n| n.get() as u32)
|
|
.unwrap_or(4);
|
|
let outcome = crate::update::prepare(exec, root, cores, true)?;
|
|
outcome.note
|
|
}
|
|
SystemAction::InspectUpdates => {
|
|
let state = crate::update::load_state(root);
|
|
format!(
|
|
"status: {:?}\nnote: {}\nlast prepared: {}",
|
|
state.status, state.note, state.last_prepared_unix
|
|
)
|
|
}
|
|
SystemAction::History => {
|
|
let history = snapshot::read_history(root)?;
|
|
let mut s = String::new();
|
|
if history.records.is_empty() {
|
|
s.push_str("no snapshot history\n");
|
|
} else {
|
|
s.push_str("snapshots:\n");
|
|
for r in &history.records {
|
|
s.push_str(&format!("{:<40} {:<16?} {}\n", r.id, r.status, r.operation));
|
|
}
|
|
}
|
|
let log = crate::transaction::read(root)?;
|
|
s.push_str("transactions:\n");
|
|
s.push_str(&log.render());
|
|
s
|
|
}
|
|
SystemAction::RollbackStatus => {
|
|
// Reading the state may also promote an activated rollback to
|
|
// verified once the restored root is the running root.
|
|
let state = crate::rollback::verify(exec, root)?;
|
|
format!(
|
|
"status: {:?}\nroot subvolume: {}\n/var subvolume: {}\ntarget: {}\nnote: {}",
|
|
state.status,
|
|
state.root_subvol,
|
|
state.var_subvol.as_deref().unwrap_or("(none)"),
|
|
state.target_snapshot,
|
|
state.note
|
|
)
|
|
}
|
|
};
|
|
Ok(ActionOutcome {
|
|
action: action.clone(),
|
|
output,
|
|
snapshot: snapshot_id,
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::command::RecordingRunner;
|
|
use crate::log::Logger;
|
|
use phoebus_core::transaction::ActionStatus;
|
|
use phoebus_core::Redactor;
|
|
use std::time::Duration;
|
|
|
|
const PRETEND_VIM: &str = "\
|
|
These are the packages that would be merged, in order:
|
|
|
|
Calculating dependencies... done!
|
|
[ebuild N ] app-editors/vim-9.1.0
|
|
|
|
Total: 1 package (1 new), Size of downloads: 1,024 KiB
|
|
";
|
|
|
|
const PRETEND_WGET: &str = "\
|
|
These are the packages that would be merged, in order:
|
|
|
|
Calculating dependencies... done!
|
|
[ebuild N ] net-misc/wget-1.24.5
|
|
|
|
Total: 1 package (1 new), Size of downloads: 512 KiB
|
|
";
|
|
|
|
fn make_exec(runner: RecordingRunner) -> Exec {
|
|
let path = tempfile::tempdir().unwrap().keep();
|
|
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
|
|
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
|
|
}
|
|
|
|
fn auth() -> DestructiveAuthorization {
|
|
crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap()
|
|
}
|
|
|
|
fn response(stdout: &str) -> CommandOutput {
|
|
CommandOutput {
|
|
status: 0,
|
|
success: true,
|
|
stdout: stdout.as_bytes().to_vec(),
|
|
stderr: Vec::new(),
|
|
duration: Duration::from_millis(1),
|
|
}
|
|
}
|
|
|
|
fn emerge_calls(specs: &[CommandSpec]) -> Vec<&CommandSpec> {
|
|
specs
|
|
.iter()
|
|
.filter(|s| s.program == "emerge" || s.args.iter().any(|a| a == "emerge"))
|
|
.collect()
|
|
}
|
|
|
|
#[test]
|
|
fn mutating_action_requires_authorization() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::EnableService {
|
|
name: "sshd".into(),
|
|
};
|
|
let err = execute(&exec, &action, None, Path::new("/")).unwrap_err();
|
|
assert!(matches!(err, ExecError::NotAuthorized(_)));
|
|
}
|
|
|
|
#[test]
|
|
fn inspect_does_not_require_authorization() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::InspectService {
|
|
name: "sshd".into(),
|
|
};
|
|
execute(&exec, &action, None, Path::new("/")).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn high_risk_action_snapshots_before_running() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
|
|
let auth = auth();
|
|
execute(
|
|
&exec,
|
|
&SystemAction::UpdateSystem,
|
|
Some(&auth),
|
|
Path::new(&exec.root),
|
|
)
|
|
.unwrap();
|
|
let specs = runner.recorded();
|
|
let btrfs = specs
|
|
.iter()
|
|
.position(|s| s.program == "btrfs")
|
|
.expect("snapshot");
|
|
let emerge = specs
|
|
.iter()
|
|
.position(|s| s.program == "emerge" || s.args.iter().any(|a| a == "emerge"))
|
|
.expect("emerge");
|
|
assert!(
|
|
btrfs < emerge,
|
|
"protective snapshot must precede the mutation: {:?}",
|
|
runner.programs()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn updating_an_nvidia_system_rebuilds_modules_and_the_initramfs() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
std::fs::create_dir_all(exec.root.join("etc/phoebus")).unwrap();
|
|
std::fs::write(exec.root.join("etc/phoebus/nvidia"), "branch=current\n").unwrap();
|
|
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
|
|
let auth = auth();
|
|
execute(
|
|
&exec,
|
|
&SystemAction::UpdateSystem,
|
|
Some(&auth),
|
|
Path::new(&exec.root),
|
|
)
|
|
.unwrap();
|
|
let specs = runner.recorded();
|
|
assert!(
|
|
specs
|
|
.iter()
|
|
.any(|s| s.args.iter().any(|a| a == "@module-rebuild")),
|
|
"the NVIDIA modules must be rebuilt after a kernel update"
|
|
);
|
|
assert!(
|
|
specs
|
|
.iter()
|
|
.any(|s| s.args.iter().any(|a| a == "kernel-install")),
|
|
"the initramfs must be regenerated with the rebuilt modules"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn protective_snapshot_id_is_preserved_in_the_outcome() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
|
|
let auth = auth();
|
|
let outcome = execute(
|
|
&exec,
|
|
&SystemAction::UpdateSystem,
|
|
Some(&auth),
|
|
Path::new(&exec.root),
|
|
)
|
|
.unwrap();
|
|
// The generic protective-snapshot path must report its id, not drop it.
|
|
assert!(outcome.snapshot.is_some(), "protective snapshot id lost");
|
|
}
|
|
|
|
#[test]
|
|
fn high_risk_action_aborts_when_protective_snapshot_fails() {
|
|
let runner = RecordingRunner::new();
|
|
runner.fail("btrfs", "snapshot failed");
|
|
let exec = make_exec(runner.clone());
|
|
std::fs::create_dir_all(exec.root.join(snapshot::SNAPSHOT_DIR)).unwrap();
|
|
let auth = auth();
|
|
let err = execute(
|
|
&exec,
|
|
&SystemAction::UpdateSystem,
|
|
Some(&auth),
|
|
Path::new(&exec.root),
|
|
)
|
|
.unwrap_err();
|
|
assert!(matches!(err, ExecError::Command { .. }), "got {err}");
|
|
// The mutation must not run, and no snapshot may be recorded as
|
|
// committed when creation failed.
|
|
assert!(!runner.programs().iter().any(|p| p == "emerge"));
|
|
let history = snapshot::read_history(Path::new(&exec.root)).unwrap();
|
|
assert!(history.records.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn history_query_reports_corrupt_file() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner);
|
|
let path = crate::snapshot::history_path(Path::new(&exec.root));
|
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
|
std::fs::write(&path, "not = = toml [[[").unwrap();
|
|
let err = execute(&exec, &SystemAction::History, None, Path::new(&exec.root)).unwrap_err();
|
|
assert!(matches!(err, ExecError::Core(_)), "got {err}");
|
|
}
|
|
|
|
#[test]
|
|
fn remove_package_builds_unmerge() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let auth = auth();
|
|
let action = SystemAction::RemovePackage { atom: "vim".into() };
|
|
execute(&exec, &action, Some(&auth), Path::new(&exec.root)).unwrap();
|
|
let recorded = runner.recorded();
|
|
let spec = emerge_calls(&recorded)[0];
|
|
assert!(spec.args.contains(&"--unmerge".to_string()));
|
|
assert!(spec.args.contains(&"vim".to_string()));
|
|
// The operand follows the option terminator.
|
|
assert!(spec.args.windows(2).any(|w| w[0] == "--" && w[1] == "vim"));
|
|
}
|
|
|
|
#[test]
|
|
fn search_packages_builds_emerge_search() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::SearchPackages {
|
|
query: "firefox".into(),
|
|
};
|
|
execute(&exec, &action, None, Path::new(&exec.root)).unwrap();
|
|
let recorded = runner.recorded();
|
|
let spec = emerge_calls(&recorded)[0];
|
|
assert!(spec.args.contains(&"--search".to_string()));
|
|
assert!(spec.args.contains(&"firefox".to_string()));
|
|
assert!(spec
|
|
.args
|
|
.windows(2)
|
|
.any(|w| w[0] == "--" && w[1] == "firefox"));
|
|
}
|
|
|
|
#[test]
|
|
fn enable_builds_separate_arguments() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::EnableService {
|
|
name: "sshd".into(),
|
|
};
|
|
execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap();
|
|
let spec = &runner.recorded()[0];
|
|
assert_eq!(spec.program, "systemctl");
|
|
assert_eq!(spec.args, vec!["enable", "sshd"]);
|
|
}
|
|
|
|
#[test]
|
|
fn service_lifecycle_runs_on_the_host() {
|
|
for (action, verb) in [
|
|
(
|
|
SystemAction::StartService {
|
|
name: "sshd".into(),
|
|
},
|
|
"start",
|
|
),
|
|
(
|
|
SystemAction::StopService {
|
|
name: "sshd".into(),
|
|
},
|
|
"stop",
|
|
),
|
|
(
|
|
SystemAction::RestartService {
|
|
name: "sshd".into(),
|
|
},
|
|
"restart",
|
|
),
|
|
] {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap();
|
|
let spec = &runner.recorded()[0];
|
|
assert_eq!(spec.program, "systemctl");
|
|
assert_eq!(spec.args, vec![verb.to_string(), "sshd".to_string()]);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn service_enable_on_an_alternate_root_uses_root_flag() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let root = Path::new("/tmp/phoebus-alt");
|
|
execute(
|
|
&exec,
|
|
&SystemAction::EnableService {
|
|
name: "sshd".into(),
|
|
},
|
|
Some(&auth()),
|
|
root,
|
|
)
|
|
.unwrap();
|
|
let spec = &runner.recorded()[0];
|
|
assert_eq!(spec.program, "systemctl");
|
|
assert_eq!(
|
|
spec.args,
|
|
vec!["--root", "/tmp/phoebus-alt", "enable", "sshd"]
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn runtime_service_operations_reject_an_alternate_root() {
|
|
let root = Path::new("/tmp/phoebus-alt");
|
|
for action in [
|
|
SystemAction::InspectService {
|
|
name: "sshd".into(),
|
|
},
|
|
SystemAction::StartService {
|
|
name: "sshd".into(),
|
|
},
|
|
SystemAction::StopService {
|
|
name: "sshd".into(),
|
|
},
|
|
SystemAction::RestartService {
|
|
name: "sshd".into(),
|
|
},
|
|
] {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let err = execute(&exec, &action, Some(&auth()), root).unwrap_err();
|
|
assert!(
|
|
err.to_string().contains("cannot target the alternate root"),
|
|
"got {err}"
|
|
);
|
|
// Nothing may be invoked against the host.
|
|
assert!(runner.recorded().is_empty(), "{:?}", runner.programs());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn preview_and_execution_use_the_same_alternate_root() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("chroot", response(PRETEND_VIM));
|
|
let exec = make_exec(runner.clone());
|
|
let root = Path::new("/mnt/phoebus-target");
|
|
let action = SystemAction::InstallPackage {
|
|
atom: "app-editors/vim".into(),
|
|
};
|
|
let plan = resolve_effects(&exec, &action, root).unwrap();
|
|
assert!(!plan.effects.is_empty());
|
|
let outcome = execute_checked(&exec, &action, Some(&auth()), root, Some(&plan)).unwrap();
|
|
assert!(outcome.output.contains("installed"));
|
|
|
|
let recorded = runner.recorded();
|
|
let calls = emerge_calls(&recorded);
|
|
assert!(calls.len() >= 2, "preview + execution: {:?}", calls);
|
|
for spec in calls {
|
|
assert_eq!(spec.program, "chroot", "execution escaped the target");
|
|
assert_eq!(spec.args[0], "/mnt/phoebus-target");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn execution_validates_before_any_command() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::InstallPackage {
|
|
atom: "--color=n".into(),
|
|
};
|
|
// The read path refuses too.
|
|
assert!(resolve_effects(&exec, &action, Path::new("/")).is_err());
|
|
let err = execute(&exec, &action, Some(&auth()), Path::new("/")).unwrap_err();
|
|
assert!(err.to_string().contains("invalid"), "got {err}");
|
|
assert!(runner.recorded().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn resolve_effects_refuses_unparseable_output() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("emerge", response("something went sideways\n"));
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::InstallPackage {
|
|
atom: "app-editors/vim".into(),
|
|
};
|
|
let err = resolve_effects(&exec, &action, Path::new("/")).unwrap_err();
|
|
assert!(err.to_string().contains("could not establish"), "got {err}");
|
|
}
|
|
|
|
#[test]
|
|
fn resolve_effects_accepts_a_genuinely_empty_plan() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response(
|
|
"emerge",
|
|
response("Calculating dependencies... done!\n\nTotal: 0 packages\n"),
|
|
);
|
|
let exec = make_exec(runner.clone());
|
|
let action = SystemAction::InstallPackage {
|
|
atom: "app-editors/vim".into(),
|
|
};
|
|
let plan = resolve_effects(&exec, &action, Path::new("/")).unwrap();
|
|
assert!(plan.effects.is_empty());
|
|
assert!(plan.established);
|
|
}
|
|
|
|
#[test]
|
|
fn a_material_change_invalidates_the_reviewed_plan() {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("emerge", response(PRETEND_WGET));
|
|
let exec = make_exec(runner.clone());
|
|
let approved = phoebus_core::effects::parse_emerge_pretend(PRETEND_VIM);
|
|
let action = SystemAction::InstallPackage {
|
|
atom: "net-misc/wget".into(),
|
|
};
|
|
let err = execute_checked(
|
|
&exec,
|
|
&action,
|
|
Some(&auth()),
|
|
Path::new("/"),
|
|
Some(&approved),
|
|
)
|
|
.unwrap_err();
|
|
assert!(err.to_string().contains("plan changed"), "got {err}");
|
|
// The unapproved mutation must not run.
|
|
assert!(!runner
|
|
.recorded()
|
|
.iter()
|
|
.any(|s| s.args.iter().any(|a| a == "--ask=n")));
|
|
}
|
|
|
|
#[test]
|
|
fn plan_stops_at_the_first_failure_and_marks_the_rest_unattempted() {
|
|
let runner = RecordingRunner::new();
|
|
runner.fail("emerge", "boom");
|
|
let exec = make_exec(runner.clone());
|
|
let steps = vec![
|
|
(SystemAction::History, ResolvedPlan::default()),
|
|
(
|
|
SystemAction::InstallPackage {
|
|
atom: "app-editors/vim".into(),
|
|
},
|
|
ResolvedPlan::default(),
|
|
),
|
|
(
|
|
SystemAction::EnableService {
|
|
name: "sshd".into(),
|
|
},
|
|
ResolvedPlan::default(),
|
|
),
|
|
];
|
|
let run = execute_plan(&exec, &steps, Some(&auth()), Path::new("/"));
|
|
assert_eq!(run.completed.len(), 1);
|
|
assert!(run.failure.is_some());
|
|
assert_eq!(run.outcomes.len(), 3);
|
|
assert_eq!(run.outcomes[0].status, ActionStatus::Completed);
|
|
assert_eq!(run.outcomes[1].status, ActionStatus::Failed);
|
|
assert_eq!(run.outcomes[2].status, ActionStatus::Unattempted);
|
|
// The third action must never reach the system.
|
|
assert!(!runner.programs().iter().any(|p| p == "systemctl"));
|
|
}
|
|
|
|
#[test]
|
|
fn undo_requires_authorization() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner);
|
|
let action = SystemAction::Undo { snapshot: None };
|
|
let err = execute(&exec, &action, None, Path::new(&exec.root)).unwrap_err();
|
|
assert!(matches!(err, ExecError::NotAuthorized(_)));
|
|
}
|
|
|
|
#[test]
|
|
fn rollback_status_reports_default_state() {
|
|
let runner = RecordingRunner::new();
|
|
let exec = make_exec(runner);
|
|
let action = SystemAction::RollbackStatus;
|
|
let outcome = execute(&exec, &action, None, Path::new(&exec.root)).unwrap();
|
|
assert!(outcome.output.contains("Idle"));
|
|
assert!(outcome.snapshot.is_none());
|
|
}
|
|
}
|