phoebus_os/installer-rs/crates/phoebus-executor/src/update.rs
Phoebus a20e064680 fix(update): keep fetched distfiles when binary prebuild is skipped
emerge --buildpkgonly refuses while dependencies still need merging, which
is normal for an out-of-date system. Record that as Ready with the fetched
distfiles and the Portage reason instead of a hard Failure, and include the
redacted stderr tail in the state note. The VM harness check timeout is now
configurable.
2026-09-20 05:00:45 -07:00

284 lines
9.8 KiB
Rust

//! 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;
#[derive(Debug)]
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<PrepareOutcome> {
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)?;
// Phase 1: distfiles. A failure here is a real failure.
if let Err(e) = portage::chroot(exec, root, "emerge", &fetch_args()) {
state.status = PrepareStatus::Failed;
state.note = describe_failure(&e);
let _ = save_state(exec, root, &state);
return Err(e);
}
// Phase 2: reusable binary packages. `--buildpkgonly` refuses while
// dependencies still need merging, which is the common case for a system
// that is behind on updates. The distfiles are already fetched, so record
// that honestly as Ready with the reason rather than a hard failure that
// would hide the successful fetch. Activation stays explicit.
state.note = "building binary packages".into();
let _ = save_state(exec, root, &state);
match portage::chroot(exec, root, "emerge", &build_args()) {
Ok(()) => {
state.status = PrepareStatus::Ready;
state.note = "updates prepared (not activated)".into();
exec.logger
.info("background update preparation complete (not activated)");
}
Err(e) => {
state.status = PrepareStatus::Ready;
state.note = format!(
"distfiles fetched; binary prebuild skipped: {}",
describe_failure(&e)
);
exec.logger.warn(format!("binary prebuild skipped: {e}"));
}
}
state.last_prepared_unix = now_unix();
save_state(exec, root, &state)?;
Ok(PrepareOutcome {
started: true,
note: state.note.clone(),
})
}
/// Include the (already redacted) stderr tail of a failed command so the state
/// explains *why* preparation failed instead of only the exit status.
fn describe_failure(error: &ExecError) -> String {
match error {
ExecError::Command { stderr, .. } if !stderr.trim().is_empty() => {
let lines: Vec<&str> = stderr.lines().collect();
let tail = lines[lines.len().saturating_sub(5)..].join("\n");
format!("{error}: {tail}")
}
_ => format!("{error}"),
}
}
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()
.all(|s| s.args.iter().any(|a| a == "@world")));
let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Ready);
}
#[test]
fn failed_prepare_records_stderr_detail() {
let runner = RecordingRunner::new();
runner.fail("chroot", "!!! emerge failed: unsatisfied dependency");
let exec = make_exec(runner);
let root = Path::new(&exec.root);
let err = prepare(&exec, root, 8, true).unwrap_err();
assert!(matches!(err, ExecError::Command { .. }));
let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Failed);
assert!(
state.note.contains("unsatisfied dependency"),
"note was {}",
state.note
);
}
#[test]
fn binary_prebuild_skipped_after_a_successful_fetch_is_ready() {
use crate::command::{CommandOutput, ProcessRunner};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
// First emerge (fetch) succeeds; second (buildpkgonly) fails with the
// real Portage "dependencies must be merged" condition.
struct FetchOkBuildFail {
calls: AtomicUsize,
}
impl ProcessRunner for FetchOkBuildFail {
fn execute(&self, _spec: &crate::command::CommandSpec) -> Result<CommandOutput> {
let n = self.calls.fetch_add(1, Ordering::SeqCst);
if n == 0 {
Ok(CommandOutput {
status: 0,
success: true,
stdout: Vec::new(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
})
} else {
Ok(CommandOutput {
status: 1,
success: false,
stdout: Vec::new(),
stderr: b"!!! --buildpkgonly requires all dependencies to be merged."
.to_vec(),
duration: Duration::from_millis(1),
})
}
}
}
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
let exec = Exec::new(
Box::new(FetchOkBuildFail {
calls: AtomicUsize::new(0),
}),
logger,
false,
path.join("root"),
path,
);
let root = Path::new(&exec.root);
let outcome = prepare(&exec, root, 8, true).unwrap();
assert!(outcome.started);
assert!(outcome.note.contains("binary prebuild skipped"));
let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Ready);
assert!(state.note.contains("dependencies to be merged"));
}
#[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);
}
}