Implement the shared installation workflow (ADR 0013). sys install, sys ask install and the explicit backend flags all use one path: identify -> evidence -> AI investigation -> deterministic validation/effects -> review -> approval -> execute -> verify -> history. - phoebus-ai::install: bounded, multi-turn investigation. The model may request typed read-only evidence (discover_candidates, inspect_candidate, check_backend, inspect_installation), ask one bounded question about intent, and must return a structured InstallProposal. Turn/request/size limits and repeated-request detection bound it; a rejected proposal is revised. - phoebus-core: add the four read-only investigation actions and strict validators; add a transaction id; backend/kind wire names now match as_str. - phoebus-executor::install: resolve_explicit (no model, no fallback), resolve_deterministic and resolve_with_ai; validate_proposal re-resolves the candidate against real metadata, rejects fabrication/ambiguity/staleness/ duplicates, maps it to the existing broker action, and binds approval to a digest; revalidate + verify_installed. chooser gains per-lane friendly-name resolution and structured evidence. - transaction::begin/finish record an in-progress transaction before mutation. - sys: --portage/--flatpak/--nix/--snap/--appimage/--ebuild (mutually exclusive) bypass the model; an unqualified install consults the model and, with none, prints the deterministic selection and installs nothing. - The installer persists /etc/phoebus/install.toml; sys loads it and adds free space, Wayland, usable lanes, saved preferences and recovery capability to the bounded facts. - Docs: ADR 0013, docs/SYS.md install sections and cases 23-31, CHANGELOG, STATUS, HANDOFF, ROADMAP. New live-VM workflow check script. Host gates pass: fmt, clippy (no new warnings), workspace tests, make test. VM: verified the workflow CLI and read-only investigation on the reference LiveGUI ISO; a full target install journey is running (see HANDOFF).
1117 lines
42 KiB
Rust
1117 lines
42 KiB
Rust
//! Installation orchestration.
|
|
//!
|
|
//! The only place destructive authorization is required, and only after the
|
|
//! plan has been shown and confirmed. Stages run in the proven order and stop
|
|
//! on the first failure.
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use phoebus_core::policy::{load_history, PackagePolicyEngine, PolicyContext};
|
|
use phoebus_core::validate::ValidationIssue;
|
|
use phoebus_core::{
|
|
validate, DesktopProfile, Filesystem, HardwareReport, InstallConfig, InstallPlan, SecretString,
|
|
};
|
|
use phoebus_executor::storage::StorageState;
|
|
use phoebus_executor::{
|
|
boot, desktop, encryption, kernel, nix, portage, probe, services, snapshot, stage3, storage,
|
|
users, Exec, Result,
|
|
};
|
|
|
|
pub struct Installer {
|
|
pub config: InstallConfig,
|
|
pub hardware: HardwareReport,
|
|
pub disks: Vec<phoebus_core::Disk>,
|
|
pub exec: Exec,
|
|
pub engine: PackagePolicyEngine,
|
|
pub policy_ctx: PolicyContext,
|
|
pub state: StorageState,
|
|
}
|
|
|
|
/// Receives stage transitions during [`Installer::install_observed`]. The GUI
|
|
/// bridge uses this to show real backend stages; it is deliberately a narrow
|
|
/// trait so no frontend can influence execution.
|
|
pub trait InstallObserver {
|
|
fn stage_started(&mut self, step: phoebus_core::InstallStep);
|
|
/// `error` is `None` on success, otherwise a redactable message.
|
|
fn stage_finished(&mut self, step: phoebus_core::InstallStep, error: Option<&str>);
|
|
}
|
|
|
|
/// Does nothing; the default for callers that do not report progress.
|
|
pub struct NoopObserver;
|
|
|
|
impl InstallObserver for NoopObserver {
|
|
fn stage_started(&mut self, _step: phoebus_core::InstallStep) {}
|
|
fn stage_finished(&mut self, _step: phoebus_core::InstallStep, _error: Option<&str>) {}
|
|
}
|
|
|
|
impl Installer {
|
|
pub fn new(config: InstallConfig, exec: Exec) -> Self {
|
|
let hardware = probe::probe_hardware(exec.runner.as_ref());
|
|
let disks = probe::probe_disks(exec.runner.as_ref());
|
|
// Prefer measured history installed on the target, then the installer's
|
|
// ephemeral state directory.
|
|
let persistent = exec.root.join("var/lib/phoebus/compile-times.tsv");
|
|
let volatile = exec.state_dir.join("compile-times.tsv");
|
|
let history = if persistent.exists() {
|
|
load_history(&persistent)
|
|
} else {
|
|
load_history(&volatile)
|
|
};
|
|
let engine = PackagePolicyEngine::new().with_history(history);
|
|
let binhost_available = config.packages.binary_packages
|
|
&& !phoebus_core::system::resolved_binhost_uri(&config).is_empty();
|
|
let policy_ctx = PolicyContext {
|
|
policy: config.packages.policy,
|
|
binhost_available,
|
|
memory_mib: hardware.memory_mib,
|
|
cores: hardware.cpu.cores,
|
|
};
|
|
Self {
|
|
config,
|
|
hardware,
|
|
disks,
|
|
exec,
|
|
engine,
|
|
policy_ctx,
|
|
state: StorageState::default(),
|
|
}
|
|
}
|
|
|
|
pub fn plan(&self) -> InstallPlan {
|
|
InstallPlan::for_config(&self.config)
|
|
}
|
|
|
|
/// Replace the configuration after a frontend edit, recomputing the derived
|
|
/// policy context so package decisions reflect the new selection. Hardware
|
|
/// and disks are unchanged by a configuration edit.
|
|
pub fn reconfigure(&mut self, config: InstallConfig) {
|
|
let binhost_available = config.packages.binary_packages
|
|
&& !phoebus_core::system::resolved_binhost_uri(&config).is_empty();
|
|
self.policy_ctx = PolicyContext {
|
|
policy: config.packages.policy,
|
|
binhost_available,
|
|
memory_mib: self.hardware.memory_mib,
|
|
cores: self.hardware.cpu.cores,
|
|
};
|
|
self.config = config;
|
|
}
|
|
|
|
pub fn render_plan(&self) -> String {
|
|
self.plan().render_human(&self.config, Some(&self.hardware))
|
|
}
|
|
|
|
pub fn destructive_preview(&self) -> String {
|
|
let disk = &self.config.storage.disk;
|
|
let layout = probe::probe_disk_layout(self.exec.runner.as_ref(), disk);
|
|
self.plan().destructive_preview(&self.config, &layout)
|
|
}
|
|
|
|
pub fn disk_layout(&self) -> String {
|
|
probe::probe_disk_layout(self.exec.runner.as_ref(), &self.config.storage.disk)
|
|
}
|
|
|
|
/// Bounded system facts for AI assistance: hardware, selected profile,
|
|
/// signed-binhost availability and measured compile times. No personal
|
|
/// data, credentials or file contents.
|
|
pub fn system_facts(&self) -> phoebus_ai::provider::SystemFacts {
|
|
let persistent = self.exec.root.join("var/lib/phoebus/compile-times.tsv");
|
|
let volatile = self.exec.state_dir.join("compile-times.tsv");
|
|
let history = if persistent.exists() {
|
|
load_history(&persistent)
|
|
} else {
|
|
load_history(&volatile)
|
|
};
|
|
let binhost_available = self.config.packages.binary_packages
|
|
&& !phoebus_core::system::resolved_binhost_uri(&self.config).is_empty();
|
|
let disk = self
|
|
.disks
|
|
.iter()
|
|
.find(|d| d.path == self.config.storage.disk)
|
|
.map(|d| phoebus_ai::provider::DiskSummary {
|
|
path: d.path.clone(),
|
|
size_gib: d.size_bytes / (1024 * 1024 * 1024),
|
|
ssd: d
|
|
.transport
|
|
.as_deref()
|
|
.map(|t| t.contains("nvme"))
|
|
.unwrap_or(false),
|
|
});
|
|
phoebus_ai::provider::SystemFacts::from_system(
|
|
&self.config,
|
|
&self.hardware,
|
|
&history,
|
|
binhost_available,
|
|
disk,
|
|
)
|
|
}
|
|
|
|
/// Configuration plus target-disk validation.
|
|
pub fn validate(&self) -> Vec<ValidationIssue> {
|
|
let mut issues = validate::validate_config(&self.config);
|
|
let disk = &self.config.storage.disk;
|
|
if !disk.is_empty() {
|
|
match self.disks.iter().find(|d| &d.path == disk) {
|
|
Some(d) => {
|
|
if let Some(reason) = d.protection() {
|
|
issues.push(ValidationIssue::new(
|
|
"target_disk",
|
|
format!("refusing target {disk}: {}", reason.describe()),
|
|
));
|
|
}
|
|
}
|
|
None => issues.push(ValidationIssue::new(
|
|
"target_disk",
|
|
format!("target disk {disk} was not detected on this system"),
|
|
)),
|
|
}
|
|
}
|
|
issues
|
|
}
|
|
|
|
/// Run the staged installation. `auth` must have been produced only after
|
|
/// the destructive preview and final confirmation.
|
|
pub fn install(
|
|
&mut self,
|
|
auth: &phoebus_executor::DestructiveAuthorization,
|
|
luks_passphrase: Option<&SecretString>,
|
|
user_password: Option<&SecretString>,
|
|
root_password: Option<&SecretString>,
|
|
) -> Result<()> {
|
|
self.install_observed(
|
|
auth,
|
|
luks_passphrase,
|
|
user_password,
|
|
root_password,
|
|
&mut NoopObserver,
|
|
)
|
|
}
|
|
|
|
/// As [`Installer::install`], reporting each stage to `observer`. This is
|
|
/// the real executor loop, not a re-implementation: the observer only sees
|
|
/// transitions the backend actually performs.
|
|
pub fn install_observed(
|
|
&mut self,
|
|
auth: &phoebus_executor::DestructiveAuthorization,
|
|
luks_passphrase: Option<&SecretString>,
|
|
user_password: Option<&SecretString>,
|
|
root_password: Option<&SecretString>,
|
|
observer: &mut dyn InstallObserver,
|
|
) -> Result<()> {
|
|
let steps = self.plan().steps.clone();
|
|
for step in steps {
|
|
let name = step.name();
|
|
self.exec.logger.section(name);
|
|
observer.stage_started(step);
|
|
let result = self.run_step(step, auth, luks_passphrase, user_password, root_password);
|
|
if let Err(e) = result {
|
|
self.exec.logger.error(format!("stage failed: {name}: {e}"));
|
|
observer.stage_finished(step, Some(&self.exec.redactor().redact(&e.to_string())));
|
|
if !self.exec.dry_run {
|
|
let _ = self.exec.export_log();
|
|
let _ = self.exec.umount_chroot();
|
|
}
|
|
return Err(e);
|
|
}
|
|
self.exec.logger.info(format!("stage complete: {name}"));
|
|
observer.stage_finished(step, None);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn run_step(
|
|
&mut self,
|
|
step: phoebus_core::InstallStep,
|
|
auth: &phoebus_executor::DestructiveAuthorization,
|
|
luks_passphrase: Option<&SecretString>,
|
|
user_password: Option<&SecretString>,
|
|
root_password: Option<&SecretString>,
|
|
) -> Result<()> {
|
|
use phoebus_core::InstallStep::*;
|
|
match step {
|
|
StoragePrepare => self.storage_prepare(auth, luks_passphrase),
|
|
StageInstall => self.stage_install(),
|
|
FstabGenerate => self.fstab_generate(),
|
|
PortageConfigure => self.portage_configure(),
|
|
PackagesBase => self.packages_base(),
|
|
KernelInstall => self.kernel_install(),
|
|
NvidiaDrivers => self.nvidia_drivers(),
|
|
BootInstall => self.boot_install(),
|
|
UsersConfigure => self.users_configure(user_password, root_password),
|
|
ServicesConfigure => self.services_configure(),
|
|
DesktopInstall => self.desktop_install(),
|
|
Finalize => self.finalize(auth),
|
|
}
|
|
}
|
|
|
|
/// Re-check the selected target disk immediately before the destructive
|
|
/// stage. An approval binds to a verified plan, not to a device name: the
|
|
/// device may have disappeared, been mounted, become the live medium, or
|
|
/// been replaced under the same name since it was chosen. Refuse to
|
|
/// partition unless the disk is present, unprotected and the same device.
|
|
pub fn revalidate_target_disk(&self) -> Result<()> {
|
|
let disk_path = &self.config.storage.disk;
|
|
if disk_path.trim().is_empty() {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"storage_prepare",
|
|
"revalidate target disk",
|
|
"no target disk is selected",
|
|
));
|
|
}
|
|
let fresh = probe::probe_disks(self.exec.runner.as_ref());
|
|
let observed = match fresh.iter().find(|d| &d.path == disk_path) {
|
|
Some(d) => d,
|
|
None => {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"storage_prepare",
|
|
"revalidate target disk",
|
|
format!(
|
|
"target disk {disk_path} disappeared since it was selected; \
|
|
refusing to partition"
|
|
),
|
|
))
|
|
}
|
|
};
|
|
if let Some(reason) = observed.protection() {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"storage_prepare",
|
|
"revalidate target disk",
|
|
format!("refusing target {disk_path}: {}", reason.describe()),
|
|
));
|
|
}
|
|
// Device-name reuse: if the same path now describes a different device
|
|
// (size or model changed), the earlier review no longer applies.
|
|
if let Some(expected) = self.disks.iter().find(|d| &d.path == disk_path) {
|
|
if expected.size_bytes != 0
|
|
&& observed.size_bytes != 0
|
|
&& expected.size_bytes != observed.size_bytes
|
|
{
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"storage_prepare",
|
|
"revalidate target disk",
|
|
format!(
|
|
"target disk {disk_path} changed size since it was selected \
|
|
({} -> {} bytes); refusing to partition",
|
|
expected.size_bytes, observed.size_bytes
|
|
),
|
|
));
|
|
}
|
|
if let (Some(before), Some(now)) = (&expected.model, &observed.model) {
|
|
if before != now {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"storage_prepare",
|
|
"revalidate target disk",
|
|
format!(
|
|
"target disk {disk_path} changed identity since it was \
|
|
selected ({before} -> {now}); refusing to partition"
|
|
),
|
|
));
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn storage_prepare(
|
|
&mut self,
|
|
auth: &phoebus_executor::DestructiveAuthorization,
|
|
luks_passphrase: Option<&SecretString>,
|
|
) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec.logger.info(format!(
|
|
"[dry-run] would partition and format {}",
|
|
self.config.storage.disk
|
|
));
|
|
self.state.root_source = format!("/dev/mapper/{}", self.config.encryption.name);
|
|
self.state.luks_uuid = Some("<luks-uuid>".into());
|
|
return Ok(());
|
|
}
|
|
self.revalidate_target_disk()?;
|
|
storage::require_tools(&self.exec)?;
|
|
if self.config.is_encrypted() {
|
|
self.exec.require_tools(&["cryptsetup"])?;
|
|
if luks_passphrase.is_none()
|
|
|| luks_passphrase
|
|
.map(|p| p.expose().is_empty())
|
|
.unwrap_or(true)
|
|
{
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"storage_prepare",
|
|
"validate secrets",
|
|
"encryption is enabled but no LUKS passphrase was supplied",
|
|
));
|
|
}
|
|
}
|
|
if let Err(e) = phoebus_executor::sys_runtime::find_trusted_sys_binary() {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"storage_prepare",
|
|
"check sys runtime",
|
|
format!("required sys runtime is missing or unusable: {e}"),
|
|
));
|
|
}
|
|
|
|
storage::prepare(
|
|
&self.exec,
|
|
&self.config,
|
|
auth,
|
|
luks_passphrase,
|
|
&mut self.state,
|
|
)
|
|
}
|
|
|
|
fn stage_install(&self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would fetch and extract the stage3");
|
|
return Ok(());
|
|
}
|
|
stage3::fetch(&self.exec, &self.config, &self.exec.state_dir)?;
|
|
let tarball = self.exec.state_dir.join("stage3-systemd.tar.xz");
|
|
stage3::extract(&self.exec, std::path::Path::new(&self.exec.root), &tarball)
|
|
}
|
|
|
|
fn fstab_generate(&mut self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would write fstab and crypttab");
|
|
return Ok(());
|
|
}
|
|
storage::write_fstab(&self.exec, &self.config, &mut self.state)?;
|
|
storage::write_crypttab(&self.exec, &self.config, &self.state)?;
|
|
let target = self.exec.target();
|
|
for dir in ["var/tmp", "tmp", "root", "home"] {
|
|
target.ensure_dir(dir)?;
|
|
}
|
|
use std::os::unix::fs::PermissionsExt;
|
|
for dir in ["var/tmp", "tmp"] {
|
|
if let Ok(p) = target.resolve(dir) {
|
|
let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o1777));
|
|
}
|
|
}
|
|
if let Ok(p) = target.resolve("root") {
|
|
let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o700));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn portage_configure(&self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would write Portage config and sync");
|
|
return Ok(());
|
|
}
|
|
portage::write_config(&self.exec, &self.config, &self.hardware)?;
|
|
self.exec.copy_resolv_conf()?;
|
|
self.exec.mount_chroot()?;
|
|
let root = PathBuf::from(&self.exec.root);
|
|
if let Err(e) = portage::init_machine_id(&self.exec, &root) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("could not initialise machine-id: {e}"));
|
|
}
|
|
let result: Result<()> = (|| {
|
|
portage::sync(&self.exec, &root)?;
|
|
if let Err(e) = portage::verification_setup(&self.exec, &root) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("getuto failed; binary verification may fail: {e}"));
|
|
}
|
|
// The Mango desktop needs the git-only GURU overlay, so install git
|
|
// from the main tree first, then sync GURU. Signature verification
|
|
// stays on and the keyword set stays scoped.
|
|
if phoebus_core::system::uses_guru(&self.config) {
|
|
let bootstrap: Vec<String> = portage::guru_bootstrap_packages()
|
|
.into_iter()
|
|
.map(str::to_string)
|
|
.collect();
|
|
portage::emerge(
|
|
&self.exec,
|
|
&root,
|
|
&bootstrap,
|
|
&self.engine,
|
|
&self.policy_ctx,
|
|
)?;
|
|
portage::sync_guru(&self.exec, &root, &self.config)?;
|
|
}
|
|
Ok(())
|
|
})();
|
|
self.exec.umount_chroot()?;
|
|
result?;
|
|
portage::select_profile(&self.exec, &self.config)
|
|
}
|
|
|
|
fn packages_base(&self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would install base packages");
|
|
return Ok(());
|
|
}
|
|
self.exec.mount_chroot()?;
|
|
let packages: Vec<String> = portage::base_packages()
|
|
.into_iter()
|
|
.map(str::to_string)
|
|
.collect();
|
|
let result = portage::emerge(
|
|
&self.exec,
|
|
std::path::Path::new(&self.exec.root),
|
|
&packages,
|
|
&self.engine,
|
|
&self.policy_ctx,
|
|
);
|
|
self.exec.umount_chroot()?;
|
|
if result.is_ok() {
|
|
self.harvest_compile_times();
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Record measured compile times from the target's emerge.log into the
|
|
/// installed system so the data survives reboot.
|
|
fn harvest_compile_times(&self) {
|
|
let history = match self.exec.target().var("lib/phoebus/compile-times.tsv") {
|
|
Ok(p) => p,
|
|
Err(_) => self.exec.state_dir.join("compile-times.tsv"),
|
|
};
|
|
if let Err(e) = portage::harvest_emerge_log(&self.exec, &history) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("compile-time instrumentation failed: {e}"));
|
|
}
|
|
}
|
|
|
|
fn kernel_install(&self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would configure and install the kernel");
|
|
return Ok(());
|
|
}
|
|
kernel::write_profile(&self.exec, &self.config)?;
|
|
boot::write_install_conf(&self.exec)?;
|
|
boot::write_dracut_conf(&self.exec, &self.config, &self.hardware)?;
|
|
let root_source = storage::root_source_ref(&self.exec, &self.config, &self.state);
|
|
kernel::write_cmdline(
|
|
&self.exec,
|
|
&self.config,
|
|
self.state.luks_uuid.as_deref(),
|
|
&root_source,
|
|
)?;
|
|
self.exec.mount_chroot()?;
|
|
let result = kernel::install(
|
|
&self.exec,
|
|
&self.config,
|
|
&self.hardware,
|
|
&self.engine,
|
|
&self.policy_ctx,
|
|
);
|
|
self.exec.umount_chroot()?;
|
|
if result.is_ok() {
|
|
self.harvest_compile_times();
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Install the NVIDIA accelerated driver selected from the PCI device IDs.
|
|
///
|
|
/// A no-op on machines with no supported NVIDIA GPU (nouveau fallback). The
|
|
/// initramfs generated during `KernelInstall` predates the module build, so
|
|
/// it is regenerated here to embed the modules and their firmware. A failure
|
|
/// fails the install: it must never be reported as successful NVIDIA
|
|
/// support.
|
|
fn nvidia_drivers(&self) -> Result<()> {
|
|
let plan = phoebus_core::nvidia::NvidiaPlan::for_hardware(&self.hardware);
|
|
if !plan.supported {
|
|
self.exec
|
|
.logger
|
|
.info(format!("NVIDIA: no driver installed; {}", plan.reason));
|
|
return Ok(());
|
|
}
|
|
if self.exec.dry_run {
|
|
self.exec.logger.info(format!(
|
|
"[dry-run] would install {} ({}) and regenerate the initramfs",
|
|
phoebus_core::nvidia::GENTOO_ATOM,
|
|
plan.branch
|
|
));
|
|
return Ok(());
|
|
}
|
|
self.exec.mount_chroot()?;
|
|
let result: Result<()> = (|| {
|
|
let packages = vec![phoebus_core::nvidia::GENTOO_ATOM.to_string()];
|
|
portage::emerge(
|
|
&self.exec,
|
|
std::path::Path::new(&self.exec.root),
|
|
&packages,
|
|
&self.engine,
|
|
&self.policy_ctx,
|
|
)?;
|
|
// The modules exist now: force them into the initramfs, prove they
|
|
// were actually built for the selected kernel, then regenerate the
|
|
// boot image. A driver that produced no modules fails the install.
|
|
boot::write_nvidia_dracut_conf(&self.exec, &self.hardware)?;
|
|
let installed = boot::verify_nvidia_modules(&self.exec.root)?;
|
|
boot::generate_entries(&self.exec)?;
|
|
self.record_nvidia(&plan, &installed)?;
|
|
Ok(())
|
|
})();
|
|
self.exec.umount_chroot()?;
|
|
if result.is_ok() {
|
|
self.harvest_compile_times();
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Persist the resolved driver decision and the *actual* installed version
|
|
/// in the target, so post-install inspection and recovery know exactly what
|
|
/// was selected rather than only a "current" label.
|
|
fn record_nvidia(
|
|
&self,
|
|
plan: &phoebus_core::nvidia::NvidiaPlan,
|
|
installed: &boot::InstalledNvidia,
|
|
) -> Result<()> {
|
|
let mut text = String::new();
|
|
text.push_str("# Resolved NVIDIA accelerated driver (generated by the installer).\n");
|
|
text.push_str(&format!(
|
|
"version={}\n",
|
|
if installed.version.is_empty() {
|
|
"unknown"
|
|
} else {
|
|
&installed.version
|
|
}
|
|
));
|
|
text.push_str(&format!("kernel={}\n", installed.kernel));
|
|
text.push_str(&format!("branch={}\n", plan.branch));
|
|
text.push_str(&format!(
|
|
"flavor={}\n",
|
|
plan.flavor.map(|f| f.as_str()).unwrap_or("none")
|
|
));
|
|
text.push_str(&format!(
|
|
"generation={}\n",
|
|
plan.generation.map(|g| g.as_str()).unwrap_or("none")
|
|
));
|
|
text.push_str("package=x11-drivers/nvidia-drivers\n");
|
|
for module in &installed.modules {
|
|
text.push_str(&format!("module={module}\n"));
|
|
}
|
|
for device in &plan.devices {
|
|
text.push_str(&format!(
|
|
"device={} {}\n",
|
|
device.pci_id,
|
|
device.generation.map(|g| g.as_str()).unwrap_or("unknown")
|
|
));
|
|
}
|
|
text.push_str(&format!("reason={}\n", plan.reason));
|
|
self.exec.target().write("etc/phoebus/nvidia", text)?;
|
|
self.exec.logger.info(format!(
|
|
"recorded the NVIDIA driver selection in /etc/phoebus/nvidia (version {}, kernel {}, modules: {})",
|
|
if installed.version.is_empty() { "unknown" } else { &installed.version },
|
|
installed.kernel,
|
|
installed.modules.join(", ")
|
|
));
|
|
Ok(())
|
|
}
|
|
|
|
fn boot_install(&self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would install systemd-boot");
|
|
return Ok(());
|
|
}
|
|
self.exec.mount_chroot()?;
|
|
if let Err(e) = boot::install_systemd_boot(&self.exec, &self.config) {
|
|
self.exec.logger.warn(format!(
|
|
"bootctl install failed; relying on EFI fallback: {e}"
|
|
));
|
|
}
|
|
if let Err(e) = boot::generate_entries(&self.exec) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("kernel-install reported an issue: {e}"));
|
|
}
|
|
self.exec.umount_chroot()?;
|
|
boot::write_loader_conf(&self.exec, &self.config)?;
|
|
if let Err(e) = boot::write_recovery_entry(&self.exec, &self.config) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("could not write recovery entry: {e}"));
|
|
}
|
|
if let Err(e) = boot::install_fallback(&self.exec, &self.config) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("EFI fallback not installed: {e}"));
|
|
}
|
|
let _ = boot::random_seed(&self.exec, &self.config);
|
|
boot::verify(&self.exec, &self.config)
|
|
}
|
|
|
|
fn users_configure(
|
|
&self,
|
|
user_password: Option<&SecretString>,
|
|
root_password: Option<&SecretString>,
|
|
) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would create the user account");
|
|
return Ok(());
|
|
}
|
|
self.exec.mount_chroot()?;
|
|
let result: Result<()> = (|| {
|
|
users::create(&self.exec, &self.config, user_password, root_password)?;
|
|
users::configure_sudo(&self.exec)?;
|
|
Ok(())
|
|
})();
|
|
self.exec.umount_chroot()?;
|
|
result
|
|
}
|
|
|
|
fn services_configure(&self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would configure locale/timezone/services");
|
|
return Ok(());
|
|
}
|
|
self.exec.mount_chroot()?;
|
|
let result: Result<()> = (|| {
|
|
services::configure(&self.exec, &self.config)?;
|
|
if self.config.packages.nix {
|
|
nix::install(&self.exec, std::path::Path::new(&self.exec.root))?;
|
|
}
|
|
Ok(())
|
|
})();
|
|
self.exec.umount_chroot()?;
|
|
result
|
|
}
|
|
|
|
fn desktop_install(&self) -> Result<()> {
|
|
if self.config.desktop.profile == phoebus_core::DesktopProfile::None {
|
|
self.exec.logger.info("no desktop profile selected");
|
|
return Ok(());
|
|
}
|
|
if self.exec.dry_run {
|
|
self.exec
|
|
.logger
|
|
.info("[dry-run] would install the desktop profile");
|
|
return Ok(());
|
|
}
|
|
self.exec.mount_chroot()?;
|
|
let result: Result<()> = (|| {
|
|
desktop::install(&self.exec, &self.config, &self.engine, &self.policy_ctx)?;
|
|
desktop::write_session_script(&self.exec, &self.config)?;
|
|
desktop::configure_login(&self.exec, &self.config)?;
|
|
desktop::configure_flatpak(&self.exec, &self.config)?;
|
|
Ok(())
|
|
})();
|
|
self.exec.umount_chroot()?;
|
|
if result.is_ok() {
|
|
self.harvest_compile_times();
|
|
}
|
|
result
|
|
}
|
|
|
|
fn finalize(&self, auth: &phoebus_executor::DestructiveAuthorization) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec.logger.info("[dry-run] finalize");
|
|
return Ok(());
|
|
}
|
|
let _ = self.exec.export_log();
|
|
|
|
// 1. Install matching sys runtime into target before recovery snapshot.
|
|
phoebus_executor::sys_runtime::install_sys_to_target(&self.exec)?;
|
|
|
|
// 2. Persist non-secret assistant configuration so `sudo sys ask` keeps its settings.
|
|
if self.config.ai.enabled
|
|
|| !self.config.ai.provider.is_empty()
|
|
|| !self.config.ai.opencode_server.is_empty()
|
|
{
|
|
if let Ok(toml_str) = toml::to_string(&self.config.ai) {
|
|
let _ = self
|
|
.exec
|
|
.target()
|
|
.write("etc/phoebus/assistant.conf", toml_str);
|
|
}
|
|
}
|
|
|
|
// 2b. Persist the non-secret installation configuration so the
|
|
// installed `sys` loads the real settings (desktop, filesystem,
|
|
// package policy, groups) instead of assuming defaults. There are no
|
|
// secrets in `InstallConfig`; passphrases are handled separately.
|
|
if let Ok(toml_str) = self.config.to_toml_string() {
|
|
self.exec
|
|
.target()
|
|
.write("etc/phoebus/install.toml", toml_str)?;
|
|
}
|
|
|
|
// 3. Rewrite the desktop entry point last so it cannot be shadowed by an
|
|
// earlier stage; a no-op for non-desktop profiles.
|
|
desktop::write_session_script(&self.exec, &self.config)?;
|
|
|
|
// 4. Verify target integrity before snapshotting and unmounting.
|
|
self.verify_installed_system()?;
|
|
|
|
// 5. Initial known-good recovery point snapshot and boot entry.
|
|
self.create_initial_recovery_point(auth);
|
|
|
|
// 6. Durability flush before unmounting.
|
|
self.exec.run(phoebus_executor::command::CommandSpec::new(
|
|
"finalize",
|
|
"flush target",
|
|
"sync",
|
|
))?;
|
|
|
|
// 7. Unmount chroot and filesystems.
|
|
let umount_chroot_res = self.exec.umount_chroot();
|
|
let unmount_res = storage::unmount_all(
|
|
&self.exec,
|
|
&self.config,
|
|
std::path::Path::new(&self.exec.root),
|
|
);
|
|
if self.config.is_encrypted() {
|
|
if let Err(e) = encryption::luks_close(&self.exec, auth, &self.config) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("could not close LUKS device: {e}"));
|
|
}
|
|
}
|
|
umount_chroot_res?;
|
|
unmount_res?;
|
|
|
|
self.exec.logger.info("installation finished");
|
|
Ok(())
|
|
}
|
|
|
|
/// Check that required installed components and configuration for the selected profile exist.
|
|
pub fn verify_installed_system(&self) -> Result<()> {
|
|
if self.exec.dry_run {
|
|
self.exec.logger.info("[dry-run] verify_installed_system");
|
|
return Ok(());
|
|
}
|
|
self.exec
|
|
.logger
|
|
.info("verifying installed target integrity");
|
|
let target = self.exec.target();
|
|
|
|
// 1. sys CLI binary must be present in target root and executable
|
|
if !target.exists("usr/local/bin/sys") {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"required runtime /usr/local/bin/sys is missing in target root",
|
|
));
|
|
}
|
|
|
|
// 2. Boot loader and kernel
|
|
let has_loader = target.exists("boot/loader/loader.conf")
|
|
|| target.exists("efi/loader/loader.conf")
|
|
|| target.exists("boot/grub/grub.cfg");
|
|
if !has_loader {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"boot loader configuration (systemd-boot/grub) missing in target",
|
|
));
|
|
}
|
|
|
|
let root_p = std::path::Path::new(&self.exec.root);
|
|
if !target_has_kernel(root_p) {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"no kernel image found in the target boot/efi tree",
|
|
));
|
|
}
|
|
|
|
// 3. Desktop profile artifacts
|
|
if self.config.desktop.profile.is_desktop() {
|
|
match self.config.desktop.profile {
|
|
DesktopProfile::Mango => {
|
|
if !target.exists("usr/local/bin/phoebus-session-mango") {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"session script /usr/local/bin/phoebus-session-mango missing",
|
|
));
|
|
}
|
|
if !target.exists("etc/xdg/mango/config.conf") {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"Mango configuration /etc/xdg/mango/config.conf missing",
|
|
));
|
|
}
|
|
}
|
|
DesktopProfile::Dwl | DesktopProfile::Full => {
|
|
if !target.exists("usr/local/bin/phoebus-session") {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"session script /usr/local/bin/phoebus-session missing",
|
|
));
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
|
|
if !target.exists("etc/greetd/config.toml") {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"login configuration /etc/greetd/config.toml missing",
|
|
));
|
|
}
|
|
|
|
let passwd = target.read_to_string("etc/passwd").unwrap_or_default();
|
|
if !passwd.lines().any(|l| l.starts_with("greeter:")) {
|
|
return Err(phoebus_executor::ExecError::operation(
|
|
"finalize",
|
|
"verify target",
|
|
"greeter user account missing from target /etc/passwd",
|
|
));
|
|
}
|
|
}
|
|
|
|
self.exec
|
|
.logger
|
|
.info("target integrity verification passed");
|
|
Ok(())
|
|
}
|
|
|
|
/// A controlled, reversible re-check used by tests and by callers that want
|
|
/// to gate a destructive action on the current disk identity.
|
|
pub fn current_disks(&self) -> Vec<phoebus_core::Disk> {
|
|
probe::probe_disks(self.exec.runner.as_ref())
|
|
}
|
|
|
|
/// Capture an initial known-good snapshot and point a boot entry at it, so
|
|
/// recovery does not depend on the (possibly later broken) live root.
|
|
fn create_initial_recovery_point(&self, auth: &phoebus_executor::DestructiveAuthorization) {
|
|
if self.config.storage.filesystem != Filesystem::Btrfs
|
|
|| !self
|
|
.config
|
|
.storage
|
|
.subvols
|
|
.iter()
|
|
.any(|s| s == "@snapshots")
|
|
{
|
|
return;
|
|
}
|
|
let root = std::path::PathBuf::from(&self.exec.root);
|
|
let root_str = root.to_string_lossy().to_string();
|
|
let var_source = if self.config.storage.subvols.iter().any(|s| s == "@var") {
|
|
Some(root.join("var").to_string_lossy().to_string())
|
|
} else {
|
|
None
|
|
};
|
|
match snapshot::create_set_and_record_at(
|
|
&self.exec,
|
|
auth,
|
|
&root,
|
|
&root_str,
|
|
var_source.as_deref(),
|
|
"initial known-good",
|
|
) {
|
|
Ok(record) => {
|
|
if let Err(e) = boot::write_snapshot_recovery_entry(
|
|
&self.exec,
|
|
&self.config,
|
|
&record.snapshot_subvol,
|
|
) {
|
|
self.exec
|
|
.logger
|
|
.warn(format!("could not write snapshot recovery entry: {e}"));
|
|
}
|
|
}
|
|
Err(e) => self
|
|
.exec
|
|
.logger
|
|
.warn(format!("could not create initial recovery snapshot: {e}")),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether the target has an installed kernel image.
|
|
///
|
|
/// With `layout=bls`, systemd's `kernel-install` places the kernel as
|
|
/// `<boot>/<machine-id>/<version>/linux` (not a top-level `vmlinuz`), so a
|
|
/// shallow scan is not enough. A BLS entry that names a kernel is equally
|
|
/// authoritative. Symlinks are not followed, so the scan cannot escape the
|
|
/// target root.
|
|
fn target_has_kernel(root: &std::path::Path) -> bool {
|
|
for sub in ["boot", "efi"] {
|
|
let dir = root.join(sub);
|
|
if dir.is_dir() && dir_has_kernel(&dir, 0) {
|
|
return true;
|
|
}
|
|
let entries = dir.join("loader/entries");
|
|
if let Ok(read) = std::fs::read_dir(&entries) {
|
|
for entry in read.flatten() {
|
|
if let Ok(text) = std::fs::read_to_string(entry.path()) {
|
|
if text.lines().any(|line| {
|
|
let t = line.trim_start();
|
|
t.starts_with("linux ") || t.starts_with("kernel ")
|
|
}) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
fn dir_has_kernel(dir: &std::path::Path, depth: usize) -> bool {
|
|
if depth > 3 {
|
|
return false;
|
|
}
|
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
|
return false;
|
|
};
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
let Ok(meta) = std::fs::symlink_metadata(&path) else {
|
|
continue;
|
|
};
|
|
if meta.file_type().is_symlink() {
|
|
continue;
|
|
}
|
|
if meta.is_dir() {
|
|
if dir_has_kernel(&path, depth + 1) {
|
|
return true;
|
|
}
|
|
} else if meta.is_file() {
|
|
let name = entry.file_name().to_string_lossy().to_string();
|
|
if name == "linux" || name.starts_with("vmlinuz") || name.starts_with("kernel") {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use phoebus_core::{Disk, DiskKind, Redactor};
|
|
use phoebus_executor::command::{CommandOutput, RecordingRunner};
|
|
use phoebus_executor::Logger;
|
|
|
|
fn lsblk_output(lines: &str) -> CommandOutput {
|
|
CommandOutput {
|
|
status: 0,
|
|
success: true,
|
|
stdout: lines.as_bytes().to_vec(),
|
|
stderr: Vec::new(),
|
|
duration: std::time::Duration::from_millis(1),
|
|
}
|
|
}
|
|
|
|
fn installer(target: &str, lsblk: &str) -> Installer {
|
|
let runner = RecordingRunner::new();
|
|
runner.set_response("lsblk", lsblk_output(lsblk));
|
|
let dir = tempfile::tempdir().unwrap().keep();
|
|
let logger = Logger::open(dir.join("install.log"), Redactor::new(), false);
|
|
let mut config = InstallConfig::default();
|
|
config.storage.disk = target.to_string();
|
|
let exec = Exec::new(Box::new(runner), logger, false, dir.join("root"), dir);
|
|
Installer::new(config, exec)
|
|
}
|
|
|
|
const VDA_OK: &str =
|
|
"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n";
|
|
const VDA_READONLY: &str =
|
|
"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"1\"\n";
|
|
const VDB_ONLY: &str =
|
|
"NAME=\"vdb\" MODEL=\"OTHER\" SIZE=\"10737418240\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n";
|
|
|
|
#[test]
|
|
fn revalidation_accepts_the_same_observed_disk() {
|
|
let installer = installer("/dev/vda", VDA_OK);
|
|
assert!(installer.revalidate_target_disk().is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn revalidation_refuses_a_disappeared_disk() {
|
|
let installer = installer("/dev/vda", VDB_ONLY);
|
|
let err = installer.revalidate_target_disk().unwrap_err().to_string();
|
|
assert!(err.contains("disappeared"), "{err}");
|
|
}
|
|
|
|
#[test]
|
|
fn revalidation_refuses_a_now_protected_disk() {
|
|
let installer = installer("/dev/vda", VDA_READONLY);
|
|
let err = installer.revalidate_target_disk().unwrap_err().to_string();
|
|
assert!(err.contains("read-only"), "{err}");
|
|
}
|
|
|
|
#[test]
|
|
fn revalidation_refuses_reused_device_name_with_a_new_size() {
|
|
let mut installer = installer("/dev/vda", VDA_OK);
|
|
// The reviewed device had a different size; the name now points at a
|
|
// different disk.
|
|
installer.disks = vec![Disk {
|
|
path: "/dev/vda".into(),
|
|
model: Some("QEMU HARDDISK".into()),
|
|
size_bytes: 8 * 1024 * 1024 * 1024,
|
|
transport: Some("virtio".into()),
|
|
removable: false,
|
|
read_only: false,
|
|
mounted: false,
|
|
is_block_device: true,
|
|
kind: DiskKind::Physical,
|
|
live_media: false,
|
|
}];
|
|
let err = installer.revalidate_target_disk().unwrap_err().to_string();
|
|
assert!(err.contains("changed size"), "{err}");
|
|
}
|
|
|
|
#[test]
|
|
fn revalidation_refuses_reused_device_name_with_a_new_model() {
|
|
let mut installer = installer("/dev/vda", VDA_OK);
|
|
installer.disks = vec![Disk {
|
|
path: "/dev/vda".into(),
|
|
model: Some("A DIFFERENT DISK".into()),
|
|
size_bytes: 32_212_254_720,
|
|
transport: Some("virtio".into()),
|
|
removable: false,
|
|
read_only: false,
|
|
mounted: false,
|
|
is_block_device: true,
|
|
kind: DiskKind::Physical,
|
|
live_media: false,
|
|
}];
|
|
let err = installer.revalidate_target_disk().unwrap_err().to_string();
|
|
assert!(err.contains("changed identity"), "{err}");
|
|
}
|
|
|
|
#[test]
|
|
fn target_kernel_detection_handles_the_bls_layout() {
|
|
let root = tempfile::tempdir().unwrap();
|
|
let root = root.path();
|
|
// A BLS/machine-id kernel is nested and named `linux`, not `vmlinuz`.
|
|
let nested = root.join("efi/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/6.18.48");
|
|
std::fs::create_dir_all(&nested).unwrap();
|
|
std::fs::write(nested.join("linux"), b"\x1f\x8b").unwrap();
|
|
assert!(target_has_kernel(root));
|
|
|
|
// A BLS entry that names a kernel is also sufficient.
|
|
let root2 = tempfile::tempdir().unwrap();
|
|
let root2 = root2.path();
|
|
let entries = root2.join("efi/loader/entries");
|
|
std::fs::create_dir_all(&entries).unwrap();
|
|
std::fs::write(
|
|
entries.join("deadbeef-6.18.48.conf"),
|
|
"title Gentoo\nlinux /aaaa/6.18.48/linux\n",
|
|
)
|
|
.unwrap();
|
|
assert!(target_has_kernel(root2));
|
|
|
|
// An empty tree has no kernel.
|
|
let root3 = tempfile::tempdir().unwrap();
|
|
std::fs::create_dir_all(root3.path().join("efi/loader")).unwrap();
|
|
assert!(!target_has_kernel(root3.path()));
|
|
}
|
|
}
|