//! 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, HardwareReport, InstallConfig, InstallPlan, SecretString}; use phoebus_executor::storage::StorageState; use phoebus_executor::{ boot, desktop, encryption, kernel, portage, probe, services, stage3, storage, users, Exec, Result, }; pub struct Installer { pub config: InstallConfig, pub hardware: HardwareReport, pub disks: Vec, pub exec: Exec, pub engine: PackagePolicyEngine, pub policy_ctx: PolicyContext, pub state: StorageState, } 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) } 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 { 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<()> { let steps = self.plan().steps.clone(); for step in steps { let name = step.name(); self.exec.logger.section(name); 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}")); 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}")); } 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(), BootInstall => self.boot_install(), UsersConfigure => self.users_configure(user_password, root_password), ServicesConfigure => self.services_configure(), DesktopInstall => self.desktop_install(), Finalize => self.finalize(auth), } } 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("".into()); return Ok(()); } 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}")); } 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 = 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)?; 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 } 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 = services::configure(&self.exec, &self.config); 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_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(); let _ = self.exec.umount_chroot(); 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}")); } } self.exec.logger.info("installation finished"); Ok(()) } }