diff --git a/SERVICE.md b/SERVICE.md index 0f6e037..484482f 100644 --- a/SERVICE.md +++ b/SERVICE.md @@ -37,8 +37,17 @@ and, paradoxically, could keep old objects pinned forever. The record stores protected commit identities and the before/after repo size. This safely removes objects already unreachable from every ref; it cannot yet reclaim commits kept alive by obsolete deployment/history refs. +- The last step of a successful update/overlay Stage runs the same object collection + inside the transaction, while it still owns the shared sysroot lock. That call may + observe the pending deployment it has just written (D-120): the pending commit and + all inputs it names stay protected, but superseded keep/service composition refs + are expired and unreachable objects collected without waiting for a reboot or a + separate cleanup command. The result is reported as `cleanup` on the Stage/apply + outcome; a collection failure is reported as `skipped` and does not turn the + successfully staged deployment into a failed update. - The `archipelago-ostree-gc.timer` unit (30 minutes after boot, then weekly) runs the - guarded apply on installed hosts; the live ISO is excluded by condition. + guarded apply on installed hosts; the live ISO is excluded by condition. Manual and + timer collection remain fail-closed and still refuse a pending deployment. Unit tests cover deployment parsing, pending/unbooted guards, keep-root calculation, overlay source/layer roots and the non-retirement of stale refs. This is deliberately diff --git a/src/gc.rs b/src/gc.rs index 67fa967..78a8e6d 100644 --- a/src/gc.rs +++ b/src/gc.rs @@ -10,7 +10,12 @@ //! superseded service composition refs whose commits are no longer named by a //! deployment, plan or retained intent; `stable/*`, plans and history stay. The //! timer therefore collects objects already unreachable from every retained ref. -use serde_json::Value; +//! +//! A successful update/overlay Stage additionally calls `after_stage` while it still +//! owns the shared lock. That call may observe the pending deployment it has just +//! written, so the update does not need a separate reboot or manual cleanup to free +//! superseded objects. Periodic/manual collection remains fail-closed on pending. +use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use std::{collections::BTreeSet, fs, io::Write, os::unix::fs::{MetadataExt, OpenOptionsExt}, path::Path, process::Command, time::{SystemTime, UNIX_EPOCH}}; @@ -81,17 +86,32 @@ pub(crate) fn parse_deployments(status: &Value) -> Result, Strin Ok(result) } -/// Refuse to collect while the protected set is not stable. A pending or staged -/// deployment may still be finalized, and a repository without a booted -/// deployment is not a host we understand. +/// Refuse periodic/manual collection while a pending deployment can still be +/// finalized: after an interrupted or not-yet-rebooted update the repository must +/// stay untouched until the host reboots. pub(crate) fn preconditions(deployments: &[Deployment]) -> Result<(), String> { + preconditions_with(deployments, false) +} + +/// The update transaction has just returned from a successful Stage while holding +/// the shared sysroot lock. At that point the pending deployment is complete and +/// no further writer exists until reboot; allowing it lets the same transaction +/// release superseded composition objects before the user reboots. The pending +/// commit and every input it names are still protected by the normal root graph. +pub(crate) fn preconditions_for_update(deployments: &[Deployment]) -> Result<(), String> { + preconditions_with(deployments, true) +} + +fn preconditions_with(deployments: &[Deployment], allow_pending: bool) -> Result<(), String> { if deployments.is_empty() { return Err("no OSTree deployments; refusing to collect objects".into()); } if !deployments.iter().any(|deployment| deployment.booted) { return Err("no booted OSTree deployment; refusing to collect objects".into()); } - if let Some(deployment) = deployments.iter().find(|deployment| deployment.pending) { - return Err(format!("pending deployment {} is not activated yet; run cleanup after reboot", - deployment.checksum)); + if !allow_pending { + if let Some(deployment) = deployments.iter().find(|deployment| deployment.pending) { + return Err(format!("pending deployment {} is not activated yet; run cleanup after reboot", + deployment.checksum)); + } } Ok(()) } @@ -328,11 +348,36 @@ pub fn plan(as_json: bool) -> Result<(), String> { pub fn apply() -> Result<(), String> { require_host()?; let _lock = lock()?; + let record = collect(false)?; + println!("Protected deployments: {}", record["deployments"]); + let prune = record["prune"].as_str().unwrap_or("").trim(); + if !prune.is_empty() { println!("{prune}"); } + if let (Some(before), Some(after)) = (record["bytes_before"].as_u64(), record["bytes_after"].as_u64()) { + println!("Repository bytes: {before} -> {after} ({} freed)", before.saturating_sub(after)); + } + Ok(()) +} + +/// Best-effort collection at the very end of a successful update/overlay Stage. +/// The caller holds the shared sysroot lock; this function must not take it again. +/// A pending deployment is allowed because the transaction has just finished +/// writing it. Failures are returned as data so a completed deployment is never +/// reported as failed just because object collection could not run. +pub(crate) fn after_stage() -> Value { + match collect(true) { + Ok(record) => json!({"state": "completed", "record": record}), + Err(error) => json!({"state": "skipped", "error": error}), + } +} + +fn collect(allow_pending: bool) -> Result { + require_host()?; let before = repository_bytes(); let status: Value = serde_json::from_str(&ostree(&["admin", "status", "--json"])?) .map_err(|_| "invalid OSTree deployment status".to_string())?; let deployments = parse_deployments(&status)?; - preconditions(&deployments)?; + if allow_pending { preconditions_for_update(&deployments)?; } + else { preconditions(&deployments)?; } let protected = protected_commits(&deployments)?; let refs = list_refs()?; for (name, commit) in keep_ref_sync(&ref_names(&refs), &protected) { @@ -361,15 +406,11 @@ pub fn apply() -> Result<(), String> { let record = serde_json::json!({ "version": 1, "finished_unix": now()?, "deployments": deployments.len(), "protected_commits": protected, "keep_refs_checked": true, + "pending_allowed": allow_pending, "prune": prune.trim(), "bytes_before": before, "bytes_after": after, }); record_journal(&record)?; - println!("Protected deployments: {}", deployments.len()); - println!("{}", prune.trim()); - if let (Some(before), Some(after)) = (before, after) { - println!("Repository bytes: {before} -> {after} ({} freed)", before.saturating_sub(after)); - } - Ok(()) + Ok(record) } fn now() -> Result { @@ -483,10 +524,13 @@ mod tests { {"checksum":"c".repeat(64),"serial":1,"booted":false,"pending":true}]}); let deployments = parse_deployments(&pending).unwrap(); assert!(preconditions(&deployments).unwrap_err().contains("not activated")); + assert!(preconditions_for_update(&deployments).is_ok()); let staged = json!({"deployments": [ {"checksum":"a".repeat(64),"serial":0,"booted":true,"staged":true}]}); - assert!(preconditions(&parse_deployments(&staged).unwrap()).unwrap_err().contains("not activated")); + let deployments = parse_deployments(&staged).unwrap(); + assert!(preconditions(&deployments).unwrap_err().contains("not activated")); + assert!(preconditions_for_update(&deployments).is_ok()); let unbooted = json!({"deployments": [{"checksum":"a".repeat(64),"serial":0,"booted":false}]}); assert!(preconditions(&parse_deployments(&unbooted).unwrap()).unwrap_err().contains("no booted")); diff --git a/src/service/packages.rs b/src/service/packages.rs index b1707a8..69ee6bd 100644 --- a/src/service/packages.rs +++ b/src/service/packages.rs @@ -611,7 +611,10 @@ pub(crate) fn execute_locked(worker: &Worker, plan: &Plan, download_only: bool, let deployment = crate::updates::managed::staged(&crate::updates::managed::status(worker)?,&target)?; super::kargs::verify(&deployment, &arguments)?; worker.events.effect("deployment",deployment.clone())?; - Ok(json!({"outcome":"staged","changed":true,"generation":id,"deployment":deployment,"effects":{"deployment_staged":true}})) + worker.events.checkpoint(Phase::Reconciling,false,"Collecting unreachable OSTree objects")?; + let cleanup = crate::gc::after_stage(); + Ok(json!({"outcome":"staged","changed":true,"generation":id,"deployment":deployment, + "cleanup":cleanup,"effects":{"deployment_staged":true}})) } /// Resolve retained intent afresh against the next managed base. The caller owns diff --git a/src/updates.rs b/src/updates.rs index 7fa0043..0be4ed4 100644 --- a/src/updates.rs +++ b/src/updates.rs @@ -325,20 +325,34 @@ fn execute_plan(id: &str, download_only: bool) -> Result<(), String> { let operation = Path::new(STATE).join(format!("operation-{}.json", SystemTime::now().duration_since(UNIX_EPOCH).map_err(|e| e.to_string())?.as_nanos())); write(&operation, &json!({"plan":id,"state":"executing"}))?; let result = apply_plan(&plan, download_only); - let terminal = match &result { Ok(()) => json!({"plan":id,"state":"completed"}), Err(e) => json!({"plan":id,"state":"failed","error":e}) }; + let cleanup = if matches!(&result, Ok(true)) { + crate::progress::phase("Collecting unreachable OSTree objects", "Очистка неиспользуемых объектов"); + Some(crate::gc::after_stage()) + } else { None }; + let terminal = match &result { Ok(_) => json!({"plan":id,"state":"completed"}), Err(e) => json!({"plan":id,"state":"failed","error":e}) }; if let Err(error) = write(&operation, &terminal) { eprintln!("Could not record terminal operation state: {error}; inspect deployment status"); } - result + if let Some(cleanup) = cleanup { + if cleanup["state"] == "completed" { + let record = &cleanup["record"]; + if let (Some(before), Some(after)) = (record["bytes_before"].as_u64(), record["bytes_after"].as_u64()) { + println!("Unreachable objects collected: {before} -> {after} ({} freed)", before.saturating_sub(after)); + } else { println!("Unreachable objects collected."); } + } else { + eprintln!("Object collection skipped: {}", cleanup["error"].as_str().unwrap_or("unknown error")); + } + } + result.map(|_| ()) } -fn apply_plan(plan: &Value, download_only: bool) -> Result<(), String> { +fn apply_plan(plan: &Value, download_only: bool) -> Result { let binding = binding()?; if plan["version"] != 3 || plan["binding"] != binding || plan["variant"] != variant()? { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); } let initial = crate::extensions::status()?; booted(&initial)?; if initial != plan["initial"] { return Err("deployment state changed; create a new plan".into()); } let target = plan["target"].as_str().filter(|s| digest(s)).ok_or("invalid target")?; - if plan["base"] == target { println!("Already on the selected base; no deployment created."); return Ok(()); } + if plan["base"] == target { println!("Already on the selected base; no deployment created."); return Ok(false); } configure(&binding)?; require_newer(plan["base"].as_str().filter(|s| digest(s)).ok_or("invalid base")?, target)?; crate::progress::phase("Downloading and verifying the image", "Загрузка и проверка подписанного образа"); @@ -358,7 +372,7 @@ fn apply_plan(plan: &Value, download_only: bool) -> Result<(), String> { if download_only { if crate::extensions::status()? != initial { return Err("deployment state changed during download".into()); } println!("Verified image downloaded; no deployment staged."); - return Ok(()); + return Ok(false); } output("ostree", &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), target])?; crate::progress::phase("Preparing the new system", "Подготовка новой системы"); @@ -368,7 +382,7 @@ fn apply_plan(plan: &Value, download_only: bool) -> Result<(), String> { stage_deployment(target)?; } else { crate::extensions::reapply(target, &requested, &initial)?; } println!("Update prepared. Activate with an explicit reboot. Current /usr unchanged."); - Ok(()) + Ok(true) } #[cfg(test)] diff --git a/src/updates/managed.rs b/src/updates/managed.rs index 6b0bf92..3f15d2e 100644 --- a/src/updates/managed.rs +++ b/src/updates/managed.rs @@ -381,7 +381,10 @@ pub(crate) fn execute(worker: &Worker, plan: &Plan, download_only: bool, offline let deployment = staged(&observed, &plan.target)?; crate::service::kargs::verify(&deployment, &arguments)?; worker.events.effect("deployment", deployment.clone())?; - Ok(json!({"outcome":"staged","changed":true,"deployment":deployment,"effects":{"deployment_staged":true}})) + worker.events.checkpoint(Phase::Reconciling, false, "Collecting unreachable OSTree objects")?; + let cleanup = crate::gc::after_stage(); + Ok(json!({"outcome":"staged","changed":true,"deployment":deployment, + "cleanup":cleanup,"effects":{"deployment_staged":true}})) } pub(crate) fn staged(state: &Value, target: &str) -> Result {