Some checks are pending
ci / test (push) Waiting to run
- Default natural-language and conversational routing for sys install, sys please install, and sys ask through shared AI workflow - Constrain AI candidate evaluation when source flags are supplied without bypassing the model - Enforce explicit --legacy flag for deterministic administration; legacy install without a source flag refuses execution and offers choices - Audit --action and --action-file entry points to require --legacy or --broker - Provide truthful guidance on absent or failing AI models without silent mutation or unverified fallback - Implement package correctness safeguards: Nix attribute evaluation probe, Portage binary check with source compile abort guard, cross-source installed application tracking, and data preservation on removal - Provide Quickshell desktop assistant (phoebus-assistant) backed by stdio JSON-RPC bridge (sys --assistant-bridge) and desktop integration - Implement unified multi-source update checking across all package lanes - Implement quiet proactive assistance monitor with alert deduplication and snoozing - Expand acceptance suite in installer/tests/vm/sys-acceptance.sh to 22 cases (22/22 PASS)
447 lines
16 KiB
Rust
447 lines
16 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)
|
|
}
|
|
|
|
use phoebus_core::selection::Backend;
|
|
use phoebus_core::update::{PackageUpdateItem, SourceUpdateOverview, UnifiedUpdateOverview};
|
|
|
|
/// Check updates across all supported package sources (Portage, Flatpak, Snap, AppImage, Nix)
|
|
/// and report a unified, truthful overview.
|
|
pub fn check_unified_updates(exec: &Exec, root: &Path) -> UnifiedUpdateOverview {
|
|
let mut sources = Vec::new();
|
|
|
|
// 1. Portage
|
|
let mut portage_items = Vec::new();
|
|
let portage_res = exec.runner.execute(
|
|
&crate::command::CommandSpec::new("sys", "check portage updates", "emerge").args([
|
|
"--pretend",
|
|
"--update",
|
|
"--deep",
|
|
"--newuse",
|
|
"--color=n",
|
|
"@world",
|
|
]),
|
|
);
|
|
let mut portage_note = "native OS packages".to_string();
|
|
if let Ok(res) = portage_res {
|
|
if res.success {
|
|
let plan = phoebus_core::effects::parse_emerge_pretend(&res.stdout_lossy());
|
|
for effect in plan.effects {
|
|
if effect.kind == phoebus_core::effects::EffectKind::Upgrade
|
|
|| effect.kind == phoebus_core::effects::EffectKind::New
|
|
{
|
|
portage_items.push(PackageUpdateItem {
|
|
name: effect.target.clone(),
|
|
current_version: effect.previous.clone(),
|
|
new_version: effect.target,
|
|
source: "Portage @world".into(),
|
|
});
|
|
}
|
|
}
|
|
} else {
|
|
portage_note = "emerge check failed or offline".into();
|
|
}
|
|
}
|
|
sources.push(SourceUpdateOverview {
|
|
backend: Backend::PortageSource,
|
|
updates: portage_items,
|
|
supported: true,
|
|
note: portage_note,
|
|
});
|
|
|
|
// 2. Flatpak
|
|
let mut flatpak_items = Vec::new();
|
|
let flatpak_supported = crate::exec::find_in_path("flatpak").is_some();
|
|
let mut flatpak_note = "sandboxed desktop applications".to_string();
|
|
if flatpak_supported {
|
|
let fp_res =
|
|
exec.runner.execute(
|
|
&crate::command::CommandSpec::new("sys", "check flatpak updates", "flatpak")
|
|
.args(["remote-ls", "--updates", "--columns=application,version"]),
|
|
);
|
|
if let Ok(res) = fp_res {
|
|
if res.success {
|
|
for line in res.stdout_lossy().lines() {
|
|
let mut parts = line.split_whitespace();
|
|
if let (Some(id), Some(ver)) = (parts.next(), parts.next()) {
|
|
flatpak_items.push(PackageUpdateItem {
|
|
name: id.to_string(),
|
|
current_version: None,
|
|
new_version: ver.to_string(),
|
|
source: "flathub".into(),
|
|
});
|
|
}
|
|
}
|
|
} else {
|
|
flatpak_note = "flatpak remote check failed or offline".into();
|
|
}
|
|
}
|
|
}
|
|
sources.push(SourceUpdateOverview {
|
|
backend: Backend::Flatpak,
|
|
updates: flatpak_items,
|
|
supported: flatpak_supported,
|
|
note: if flatpak_supported {
|
|
flatpak_note
|
|
} else {
|
|
"flatpak is not installed".into()
|
|
},
|
|
});
|
|
|
|
// 3. Snap
|
|
let mut snap_items = Vec::new();
|
|
let snap_status = crate::snap::status(exec);
|
|
let snap_supported = matches!(snap_status, Ok(ref s) if s.usable());
|
|
let snap_note = "snapd automatic refresh lane".to_string();
|
|
if snap_supported {
|
|
let snap_res = exec.runner.execute(
|
|
&crate::command::CommandSpec::new("sys", "check snap updates", "snap")
|
|
.args(["refresh", "--list"]),
|
|
);
|
|
if let Ok(res) = snap_res {
|
|
if res.success {
|
|
for line in res.stdout_lossy().lines().skip(1) {
|
|
let mut parts = line.split_whitespace();
|
|
if let (Some(name), Some(ver)) = (parts.next(), parts.next()) {
|
|
snap_items.push(PackageUpdateItem {
|
|
name: name.to_string(),
|
|
current_version: None,
|
|
new_version: ver.to_string(),
|
|
source: "Snap Store".into(),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
sources.push(SourceUpdateOverview {
|
|
backend: Backend::Snap,
|
|
updates: snap_items,
|
|
supported: snap_supported,
|
|
note: if snap_supported {
|
|
snap_note
|
|
} else {
|
|
"snapd is not installed or active".into()
|
|
},
|
|
});
|
|
|
|
// 4. AppImage
|
|
let appimages = crate::appimage::list(root).unwrap_or_default();
|
|
sources.push(SourceUpdateOverview {
|
|
backend: Backend::AppImage,
|
|
updates: Vec::new(),
|
|
supported: false,
|
|
note: format!(
|
|
"{} managed AppImage(s); automatic repository updates are not supported by the format (manual update required)",
|
|
appimages.len()
|
|
),
|
|
});
|
|
|
|
// 5. Nix
|
|
let nix_installed = crate::nix::installed(root);
|
|
sources.push(SourceUpdateOverview {
|
|
backend: Backend::Nix,
|
|
updates: Vec::new(),
|
|
supported: nix_installed,
|
|
note: if nix_installed {
|
|
"Nix dev packages are declarative/pinned; updates are managed per-project or via profile updates".into()
|
|
} else {
|
|
"Nix is not installed".into()
|
|
},
|
|
});
|
|
|
|
// Reboot check: check /var/run/reboot-required
|
|
let reboot_required = root.join("var/run/reboot-required").exists();
|
|
let reboot_reason = if reboot_required {
|
|
Some("Kernel or core system changes require a reboot (/var/run/reboot-required)".into())
|
|
} else {
|
|
None
|
|
};
|
|
|
|
UnifiedUpdateOverview {
|
|
sources,
|
|
reboot_required,
|
|
reboot_reason,
|
|
}
|
|
}
|
|
|
|
#[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);
|
|
}
|
|
}
|