266 lines
15 KiB
Rust
266 lines
15 KiB
Rust
//! Experimental requested-set lifecycle. pacman and OSTree remain the engines.
|
||
use serde_json::{Value, json};
|
||
use std::{collections::{BTreeMap, BTreeSet}, fs::{self, File}, os::unix::fs::DirBuilderExt,
|
||
path::Path, process::Command, time::{SystemTime, UNIX_EPOCH}};
|
||
|
||
const REPO: &str = "--repo=/sysroot/ostree/repo";
|
||
const STATE: &str = "/var/lib/archipelago/host-extensions/generations";
|
||
const METADATA: &str = "/usr/lib/archipelago/extensions.json";
|
||
pub(crate) type Requests = BTreeMap<String, String>;
|
||
|
||
fn output(program: &str, args: &[&str]) -> Result<String, String> {
|
||
let out = Command::new(program).args(args).output().map_err(|e| e.to_string())?;
|
||
if !out.status.success() {
|
||
return Err(format!("{program}: {}", String::from_utf8_lossy(&out.stderr)));
|
||
}
|
||
String::from_utf8(out.stdout).map_err(|e| e.to_string())
|
||
}
|
||
|
||
fn run(program: &str, args: &[&str]) -> Result<(), String> {
|
||
let status = Command::new(program).args(args).status().map_err(|e| e.to_string())?;
|
||
if status.success() { Ok(()) } else { Err(format!("{program}: {status}")) }
|
||
}
|
||
|
||
fn checksum(value: &str) -> Result<String, String> {
|
||
if value.len() == 64 && value.bytes().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()) {
|
||
Ok(value.to_string())
|
||
} else { Err("invalid OSTree checksum".into()) }
|
||
}
|
||
|
||
fn names(values: &[String]) -> Result<BTreeSet<String>, String> {
|
||
if values.is_empty() { return Err("provide at least one package name".into()); }
|
||
values.iter().map(|name| {
|
||
if name.is_empty() || name.starts_with(['-', '.']) || !name.bytes().all(|c|
|
||
c.is_ascii_alphanumeric() || b"@._+-".contains(&c)) {
|
||
Err(format!("expected a package name, not an option, group or path: {name}"))
|
||
} else { Ok(name.clone()) }
|
||
}).collect()
|
||
}
|
||
|
||
pub(crate) fn status() -> Result<Value, String> {
|
||
serde_json::from_str(&output("ostree", &["admin", "status", "--json"])?).map_err(|e| e.to_string())
|
||
}
|
||
|
||
fn select(status: &Value) -> Result<(String, bool), String> {
|
||
let entries = status["deployments"].as_array().ok_or("missing deployments")?;
|
||
let own: Vec<_> = entries.iter().filter(|d| d["stateroot"] == "archipelago").collect();
|
||
if let Some(pending) = own.iter().find(|d| d["pending"] == true || d["staged"] == true) {
|
||
if pending["staged"] != true {
|
||
return Err("activate the non-staged pending deployment before modifying extensions".into());
|
||
}
|
||
return Ok((checksum(pending["checksum"].as_str().ok_or("missing pending checksum")?)?, true));
|
||
}
|
||
let booted = own.iter().find(|d| d["booted"] == true).ok_or("no booted Archipelago deployment")?;
|
||
Ok((checksum(booted["checksum"].as_str().ok_or("missing booted checksum")?)?, false))
|
||
}
|
||
|
||
fn cat(commit: &str, path: &str) -> Result<String, String> {
|
||
output("ostree", &[REPO, "cat", commit, path])
|
||
}
|
||
|
||
pub(crate) fn intent(commit: &str) -> Result<(String, Requests), String> {
|
||
// Listing first distinguishes an absent metadata file from malformed metadata.
|
||
let listing = output("ostree", &[REPO, "ls", commit, "/usr/lib/archipelago"])?;
|
||
if listing.lines().any(|line| line.ends_with("/extensions.json")) {
|
||
let data: Value = serde_json::from_str(&cat(commit, METADATA)?).map_err(|e| e.to_string())?;
|
||
if data["version"] != 1 && data["version"] != 2 && data["version"] != 3 { return Err("unsupported extension metadata version".into()); }
|
||
let requested = data["requested"].as_array().ok_or("missing requested set")?.iter()
|
||
.map(|v| v.as_str().map(str::to_string).ok_or("invalid request".to_string()))
|
||
.collect::<Result<Vec<_>, _>>()?;
|
||
let requested = if requested.is_empty() { BTreeSet::new() } else { names(&requested)? };
|
||
let origins: Requests = if data["version"] == 2 || data["version"] == 3 {
|
||
serde_json::from_value(data["request_sources"].clone()).map_err(|e| e.to_string())?
|
||
} else { requested.iter().map(|n| (n.clone(), "unknown".into())).collect() };
|
||
if origins.keys().cloned().collect::<BTreeSet<_>>() != requested ||
|
||
origins.values().any(|v| !["repository", "local-file", "unknown"].contains(&v.as_str())) {
|
||
return Err("invalid extension request provenance".into());
|
||
}
|
||
return Ok((checksum(data["base"].as_str().ok_or("missing extension base")?)?, origins));
|
||
}
|
||
if listing.lines().any(|line| line.ends_with("/host-extensions")) {
|
||
// Migrate the single-generation nano fixture used by Core ISO 01–10.
|
||
let requested: Vec<_> = cat(commit, "/usr/lib/archipelago/host-extensions")?.lines().map(str::to_string).collect();
|
||
let base = output("ostree", &[REPO, "show", "--print-metadata-key=archipelago.base", commit])?;
|
||
return Ok((checksum(base.trim().trim_matches('\''))?, names(&requested)?.into_iter().map(|n| (n, "unknown".into())).collect()));
|
||
}
|
||
Ok((commit.to_string(), Requests::new()))
|
||
}
|
||
|
||
pub fn describe() -> Result<(), String> {
|
||
let state = status()?;
|
||
for deployment in state["deployments"].as_array().ok_or("missing deployments")? {
|
||
if deployment["stateroot"] != "archipelago" ||
|
||
!(deployment["booted"] == true || deployment["pending"] == true || deployment["staged"] == true) { continue; }
|
||
let commit = checksum(deployment["checksum"].as_str().ok_or("missing checksum")?)?;
|
||
let (base, requested) = intent(&commit)?;
|
||
let role = if deployment["booted"] == true { "Booted" } else { "Pending" };
|
||
println!("{role} deployment: {commit}\n{role} base: {base}");
|
||
println!("{role} requested extensions: {}", requested.iter().map(|(n, s)| format!("{n} ({s})")).collect::<Vec<_>>().join(", "));
|
||
let files = output("ostree", &[REPO, "ls", &base, "/usr/lib/archipelago"])?;
|
||
let custom_overlay = files.lines().any(|l| l.ends_with("/overlays"));
|
||
let overridden = cat(&commit, METADATA).ok().and_then(|text| serde_json::from_str::<Value>(&text).ok())
|
||
.and_then(|data| data["requests"].as_array().map(|rows| rows.iter().any(|r| r["override"] == true))).unwrap_or(false);
|
||
let repo_only = !overridden && requested.values().all(|s| s == "repository");
|
||
if custom_overlay || !repo_only {
|
||
println!("{role} support status: unsupported");
|
||
} else {
|
||
match crate::updates::verify_supported_base(&base) {
|
||
Ok(()) => println!("{role} support status: supported"),
|
||
Err(error) => println!("{role} support status: unknown (base not verified: {error})"),
|
||
}
|
||
}
|
||
if !requested.is_empty() && repo_only {
|
||
let original: BTreeSet<_> = cat(&base, "/usr/lib/archipelago/packages.txt")?.lines()
|
||
.filter_map(|l| l.split_whitespace().next().map(str::to_string)).collect();
|
||
let effective: BTreeSet<_> = cat(&commit, "/usr/lib/archipelago/packages.txt")?.lines()
|
||
.filter_map(|l| l.split_whitespace().next().map(str::to_string)).filter(|n| !original.contains(n)).collect();
|
||
let mut label = effective.iter().take(10).cloned().collect::<Vec<_>>().join(", ");
|
||
if effective.len() > 10 { label.push_str(&format!(", … +{} packages", effective.len() - 10)); }
|
||
println!("{role} customization: customed ({label})");
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn write(path: impl AsRef<Path>, data: impl AsRef<[u8]>) -> Result<(), String> {
|
||
fs::write(path, data).map_err(|e| e.to_string())
|
||
}
|
||
|
||
pub fn add(packages: &[String]) -> Result<(), String> {
|
||
change(packages, false)
|
||
}
|
||
|
||
pub fn remove(packages: &[String]) -> Result<(), String> {
|
||
change(packages, true)
|
||
}
|
||
|
||
fn change(packages: &[String], remove: bool) -> Result<(), String> {
|
||
crate::progress::phase("Resolving requested package changes", "Определение изменений пакетов");
|
||
let additions = names(packages)?;
|
||
if output("id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); }
|
||
if !Path::new("/run/ostree-booted").exists() || !Path::new("/etc/archipelago/provisioned").exists() {
|
||
return Err("complete firstboot in an installed OSTree deployment first".into());
|
||
}
|
||
let lock = File::options().create(true).truncate(false).write(true)
|
||
.open("/run/archipelago-compose.lock").map_err(|e| e.to_string())?;
|
||
lock.try_lock().map_err(|e| format!("another composition is running: {e}"))?;
|
||
let initial = status()?;
|
||
let (source, pending) = select(&initial)?;
|
||
let (base, mut requested) = intent(&source)?;
|
||
let previous = requested.clone();
|
||
for name in additions {
|
||
if remove { requested.remove(&name); }
|
||
else { requested.entry(name).or_insert_with(|| "repository".into()); }
|
||
}
|
||
if requested == previous {
|
||
println!("Already requested in {} deployment; no changes.", if pending { "pending" } else { "booted" });
|
||
return Ok(());
|
||
}
|
||
let id = format!("{}-{}", SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos(), std::process::id());
|
||
let generation = Path::new(STATE).join(&id);
|
||
fs::DirBuilder::new().recursive(true).mode(0o700).create(&generation).map_err(|e| e.to_string())?;
|
||
let snapshot = cat(&base, "/usr/lib/archipelago/snapshot")?;
|
||
write(generation.join("base"), format!("{base}\n"))?;
|
||
write(generation.join("source"), format!("{source}\n"))?;
|
||
write(generation.join("snapshot"), &snapshot)?;
|
||
write(generation.join("requested"), requested.keys().map(|n| format!("{n}\n")).collect::<String>())?;
|
||
write(generation.join("request-sources.json"), serde_json::to_vec_pretty(&requested).map_err(|e| e.to_string())?)?;
|
||
let result = compose(&generation, &id, &base, &snapshot, &requested, &initial);
|
||
if let Err(error) = &result {
|
||
let _ = write(generation.join("failure"), error);
|
||
eprintln!("Extension composition failed; diagnostics and inputs: {}", generation.display());
|
||
}
|
||
result
|
||
}
|
||
|
||
pub(crate) fn reapply(base: &str, requested: &Requests, initial: &Value) -> Result<(), String> {
|
||
crate::progress::phase("Reapplying Host Extensions", "Повторное применение локальных пакетов");
|
||
// Caller holds the same host mutation lock as extension add.
|
||
let id = format!("update-{}-{}", SystemTime::now().duration_since(UNIX_EPOCH)
|
||
.map_err(|e| e.to_string())?.as_nanos(), std::process::id());
|
||
let generation = Path::new(STATE).join(&id);
|
||
fs::DirBuilder::new().recursive(true).mode(0o700).create(&generation).map_err(|e| e.to_string())?;
|
||
let snapshot = cat(base, "/usr/lib/archipelago/snapshot")?;
|
||
write(generation.join("base"), format!("{base}\n"))?;
|
||
write(generation.join("snapshot"), &snapshot)?;
|
||
write(generation.join("requested"), requested.keys().map(|n| format!("{n}\n")).collect::<String>())?;
|
||
write(generation.join("request-sources.json"), serde_json::to_vec_pretty(requested).map_err(|e| e.to_string())?)?;
|
||
let result = compose(&generation, &id, base, &snapshot, requested, initial);
|
||
if let Err(error) = &result { let _ = write(generation.join("failure"), error); }
|
||
result
|
||
}
|
||
|
||
fn compose(generation: &Path, id: &str, base: &str, snapshot: &str,
|
||
requested: &Requests, initial: &Value) -> Result<(), String> {
|
||
if requested.values().any(|s| s != "repository") {
|
||
return Err("Local/legacy request provenance cannot be replayed by the repository adapter; explicitly remove those requests first. Inputs and deployments preserved.".into());
|
||
}
|
||
if requested.is_empty() {
|
||
if status()? != *initial { return Err("deployment selection changed; retry".into()); }
|
||
crate::updates::stage_deployment(base)?;
|
||
write(generation.join("result"), format!("{base}\n"))?;
|
||
write(generation.join("staged"), b"success\n")?;
|
||
println!("Prepared managed base {base}; activate with an explicit reboot.");
|
||
return Ok(());
|
||
}
|
||
let root = generation.join("root");
|
||
crate::progress::phase("Checking out the managed base", "Подготовка дерева базовой системы");
|
||
let rootstr = root.to_str().ok_or("invalid workspace path")?;
|
||
run("ostree", &[REPO, "refs", &format!("--create=extensions/bases/{id}"), base])?;
|
||
run("ostree", &[REPO, "checkout", "--force-copy", base, rootstr])?;
|
||
write(generation.join("dkms-policy.tsv"), include_str!("../adapters/dkms-policy.tsv"))?;
|
||
write(generation.join("dkms-finalize.sh"), include_str!("../adapters/dkms-finalize.sh"))?;
|
||
write(generation.join("finalize-managed.sh"), include_str!("../adapters/finalize-managed.sh"))?;
|
||
let transaction = Command::new("/bin/bash").args(["-euo", "pipefail", "-c",
|
||
include_str!("../adapters/extensions.sh"), "archipelago-extension"])
|
||
.arg(generation).status().map_err(|e| e.to_string())?;
|
||
if !transaction.success() { return Err(format!("package transaction/finalization failed: {transaction}")); }
|
||
crate::progress::phase("Committing the composed image", "Сохранение собранного образа");
|
||
write(root.join("usr/lib/archipelago/extensions.json"), serde_json::to_vec_pretty(&json!({
|
||
"version": 2, "base": base, "snapshot": snapshot.trim(), "generation": id,
|
||
"requested": requested.keys().collect::<Vec<_>>(), "request_sources": requested,
|
||
})).map_err(|e| e.to_string())?)?;
|
||
write(root.join("usr/lib/archipelago/host-extensions"), requested.keys().map(|n| format!("{n}\n")).collect::<String>())?;
|
||
let commit = checksum(output("ostree", &[REPO, "commit", "-b", &format!("extensions/results/{id}"),
|
||
&format!("--tree=dir={rootstr}"), &format!("--add-metadata-string=archipelago.base={base}"),
|
||
&format!("--add-metadata-string=archipelago.snapshot={}", snapshot.trim())])?.trim())?;
|
||
write(generation.join("result"), format!("{commit}\n"))?;
|
||
// Native OSTree clients do not take our lock. Refuse a stale selection before
|
||
// asking OSTree to atomically replace its staged deployment.
|
||
if status()? != *initial { return Err("deployment selection changed during composition; retry".into()); }
|
||
crate::updates::stage_deployment(&commit)?;
|
||
if let Err(error) = write(generation.join("staged"), b"success\n") {
|
||
eprintln!("Deployment staged; could not record completion: {error}");
|
||
}
|
||
// Exact archives, DB, logs and refs remain; only disposable staging is removed.
|
||
if let Err(error) = fs::remove_dir_all(&root) {
|
||
eprintln!("Deployment staged; retained disposable workspace: {error}");
|
||
}
|
||
println!("Prepared {commit}\nRequested: {}\nActivate with an explicit reboot. Current /usr unchanged.\nHistory: {}",
|
||
requested.keys().cloned().collect::<Vec<_>>().join(" "), generation.display());
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
#[test]
|
||
fn rejects_options_paths_and_dependency_expressions() {
|
||
for value in ["--overwrite", "../x", "/tmp/pkg", "repo/pkg", "a>=1", "", "a\nb"] {
|
||
assert!(names(&[value.into()]).is_err(), "{value}");
|
||
}
|
||
assert_eq!(names(&["nano".into(), "nano".into(), "lib32-glibc".into()]).unwrap().len(), 2);
|
||
}
|
||
#[test]
|
||
fn pending_intent_precedes_booted_but_finalized_pending_is_not_overwritten() {
|
||
let boot = "a".repeat(64); let next = "b".repeat(64);
|
||
let mut s = json!({"deployments": [
|
||
{"stateroot":"archipelago", "checksum":next, "pending":true,"staged":true},
|
||
{"stateroot":"archipelago", "checksum":boot, "booted":true}]});
|
||
assert_eq!(select(&s).unwrap(), (next, true));
|
||
s["deployments"][0]["staged"] = json!(false);
|
||
assert!(select(&s).is_err());
|
||
s["deployments"][0]["pending"] = json!(false);
|
||
assert_eq!(select(&s).unwrap(), (boot, false));
|
||
}
|
||
}
|