//! Background update preparation. //! //! Fetches distfiles and builds reusable local binary packages without //! installing them. Activation stays explicit. Uses only real Portage flags. use std::path::{Path, PathBuf}; use phoebus_core::update::{build_args, fetch_args, should_prepare, PowerState, PrepareState, PrepareStatus}; use crate::error::{ExecError, Result}; use crate::exec::Exec; use crate::portage; pub struct PrepareOutcome { pub started: bool, pub note: String, } pub fn state_path(root: &Path) -> PathBuf { root.join("var/lib/phoebus/update-state.toml") } pub fn load_state(root: &Path) -> PrepareState { let path = state_path(root); if !path.exists() { return PrepareState::default(); } std::fs::read_to_string(&path) .ok() .and_then(|t| toml::from_str(&t).ok()) .unwrap_or_default() } pub fn save_state(exec: &Exec, root: &Path, state: &PrepareState) -> Result<()> { let path = state_path(root); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| ExecError::io(parent.to_path_buf(), e))?; } let text = toml::to_string_pretty(state) .map_err(|e| ExecError::operation("update", "serialize state", e.to_string()))?; std::fs::write(&path, text).map_err(|e| ExecError::io(path.clone(), e))?; exec.logger.info(format!("update state -> {}", path.display())); Ok(()) } /// Read the current power source from sysfs. pub fn read_power_state() -> PowerState { let Ok(entries) = std::fs::read_dir("/sys/class/power_supply") else { return PowerState::Unknown; }; let mut saw_battery = false; for entry in entries.flatten() { let name = entry.file_name().to_string_lossy().to_string(); let base = entry.path(); if name.starts_with("AC") || name.starts_with("ADP") || name.starts_with("Mains") { if let Ok(v) = std::fs::read_to_string(base.join("online")) { if v.trim() == "1" { return PowerState::Ac; } } } if name.starts_with("BAT") { saw_battery = true; } } if saw_battery { PowerState::Battery } else { PowerState::Unknown } } fn read_load_average() -> f32 { std::fs::read_to_string("/proc/loadavg") .ok() .and_then(|t| t.split_whitespace().next().and_then(|v| v.parse().ok())) .unwrap_or(0.0) } /// Prepare updates: fetch distfiles, then build reusable binary packages. pub fn prepare( exec: &Exec, root: &Path, cores: u32, force: bool, ) -> Result { let power = read_power_state(); let load = read_load_average(); if !force && !should_prepare(power, load, cores, false) { let note = format!("deferred (power={power:?}, load={load:.2})"); exec.logger.info(format!("background prepare {note}")); return Ok(PrepareOutcome { started: false, note, }); } let mut state = PrepareState { status: PrepareStatus::Running, note: "fetching distfiles".into(), ..load_state(root) }; save_state(exec, root, &state)?; let result = (|| -> Result<()> { portage::chroot(exec, root, "emerge", &fetch_args())?; state.note = "building binary packages".into(); let _ = save_state(exec, root, &state); portage::chroot(exec, root, "emerge", &build_args())?; Ok(()) })(); match result { Ok(()) => { state.status = PrepareStatus::Ready; state.note = "updates prepared (not activated)".into(); state.last_prepared_unix = now_unix(); save_state(exec, root, &state)?; exec.logger .info("background update preparation complete (not activated)"); Ok(PrepareOutcome { started: true, note: state.note.clone(), }) } Err(e) => { state.status = PrepareStatus::Failed; state.note = format!("{e}"); let _ = save_state(exec, root, &state); Err(e) } } } fn now_unix() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) } #[cfg(test)] mod tests { use super::*; use crate::command::RecordingRunner; use crate::log::Logger; use phoebus_core::Redactor; 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) } #[test] fn prepare_forces_fetch_and_build_without_install() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let root = Path::new(&exec.root); let outcome = prepare(&exec, root, 8, true).unwrap(); assert!(outcome.started); let specs = runner.recorded(); let emerge_specs: Vec<_> = specs .iter() .filter(|s| s.args.iter().any(|a| a == "emerge")) .collect(); assert_eq!(emerge_specs.len(), 2); assert!(emerge_specs[0].args.iter().any(|a| a == "--fetchonly")); assert!(emerge_specs[1].args.iter().any(|a| a == "--buildpkgonly")); assert!(!emerge_specs.iter().any(|s| s.args.iter().any(|a| a == "@world" && false))); let state = load_state(root); assert_eq!(state.status, PrepareStatus::Ready); } #[test] fn state_roundtrip() { let runner = RecordingRunner::new(); let exec = make_exec(runner); let root = Path::new(&exec.root); let state = PrepareState { last_prepared_unix: 123, status: PrepareStatus::Ready, prepared_packages: 5, note: "ok".into(), }; save_state(&exec, root, &state).unwrap(); assert_eq!(load_state(root), state); } }