//! Retention, metrics and backups (§15). //! //! Three separate jobs that share one premise: the database is the thing that //! must survive, and the bytes on disk are the thing that cannot be kept forever. //! //! *Retention* evicts files for releases beyond the last N of a pkgbase. It never //! deletes a row. The artifact keeps its digest, size and provenance and gains a //! `purged_at`, so the record says "these bytes existed and were dropped at T" //! rather than continuing to claim a file that is no longer there. //! //! *Metrics* are computed on read, like staleness. A counter that has to be //! incremented on every state change is a counter that drifts. //! //! *Backups* use `VACUUM INTO`. Copying a live WAL database with `cp` produces a //! main file plus a WAL that may or may not belong to it, which is to say a backup //! that is only sometimes restorable. use std::path::{Path, PathBuf}; use crate::config::Config; use crate::db::{self, Db}; use crate::error::Result; use crate::time; /// Default number of versions kept per pkgbase (§11 `retention_versions`). pub const DEFAULT_KEEP: usize = 3; #[derive(Debug, Default, Clone)] pub struct RetentionReport { pub releases_kept: usize, pub releases_evicted: usize, pub files_removed: usize, pub bytes_freed: u64, pub staging_swept: usize, } /// Everything a metrics scrape reports, computed in one pass over the database. /// /// Kept as a struct rather than a string builder so the HTTP handler, the CLI and /// the tests all read the same numbers from the same source. #[derive(Debug, Default, Clone)] pub struct Metrics { pub builds: Vec<(String, i64)>, pub queue_depth: i64, pub oldest_queued_age_secs: i64, pub pending_review: i64, /// Age of pending candidates in seconds, already sorted, for bucketing. pub review_ages: Vec, pub succeeded: i64, pub failed: i64, pub blocked_missing_dep: i64, pub index_packages: i64, pub releases: i64, pub stale_outdated: i64, pub stale_missing: i64, pub downgrades: i64, pub subscriptions: i64, pub notices_unseen: i64, pub db_bytes: u64, pub wal_bytes: u64, pub artifact_bytes: u64, pub staging_dirs: usize, pub staging_bytes: u64, pub last_gc_age_secs: Option, pub poll_lag_age_secs: Option, } impl Metrics { /// Share of recorded builds that published. Reported as 1.0 when nothing has /// run yet: a fresh install is not a failing install, and an alert rule that /// reads 0% success on an empty system pages someone for no reason. pub fn build_success_rate(&self) -> f64 { match self.succeeded + self.failed { 0 => 1.0, n => self.succeeded as f64 / n as f64, } } /// Render in Prometheus text exposition format. /// /// Every family is declared with `# HELP` and `# TYPE` because a scrape that /// fails validation silently drops the whole payload, not just the bad line. pub fn to_prometheus(&self) -> String { let mut o = String::new(); o.push_str("# HELP aurbuild_up Always 1: the process answered the scrape.\n# TYPE aurbuild_up gauge\naurbuild_up 1\n"); o.push_str(&header("aurbuild_queue_depth", "Builds waiting to run.")); o.push_str(&format!("aurbuild_queue_depth {}\n", self.queue_depth)); o.push_str(&header("aurbuild_oldest_queued_age_seconds", "How long the oldest queued build has waited.")); o.push_str(&format!("aurbuild_oldest_queued_age_seconds {}\n", self.oldest_queued_age_secs)); o.push_str("# HELP aurbuild_builds_total Builds by state.\n# TYPE aurbuild_builds_total gauge\n"); for (state, n) in &self.builds { o.push_str(&format!("aurbuild_builds_total{{state=\"{state}\"}} {n}\n")); } o.push_str(&header("aurbuild_pending_review_candidates", "Reviews waiting on a human — the review debt.")); o.push_str(&format!("aurbuild_pending_review_candidates {}\n", self.pending_review)); // The debt number nobody asks for until it is weeks old: not how many // reviews are pending, but how stale the pending ones are. o.push_str("# HELP aurbuild_pending_review_age_seconds Histogram of how long pending reviews have waited.\n# TYPE aurbuild_pending_review_age_seconds histogram\n"); for le in [3600i64, 21600, 86400, 259200, 604800] { let n = self.review_ages.iter().filter(|a| **a <= le).count(); o.push_str(&format!("aurbuild_pending_review_age_seconds_bucket{{le=\"{le}\"}} {n}\n")); } o.push_str(&format!( "aurbuild_pending_review_age_seconds_bucket{{le=\"+Inf\"}} {}\n", self.review_ages.len() )); let sum: i64 = self.review_ages.iter().sum(); o.push_str(&format!("aurbuild_pending_review_age_seconds_sum {sum}\n")); o.push_str(&format!("aurbuild_pending_review_age_seconds_count {}\n", self.review_ages.len())); o.push_str(&header("aurbuild_builds_succeeded_total", "Builds that published.")); o.push_str(&format!("aurbuild_builds_succeeded_total {}\n", self.succeeded)); o.push_str(&header("aurbuild_builds_failed_total", "Builds that failed.")); o.push_str(&format!("aurbuild_builds_failed_total {}\n", self.failed)); let rate = self.build_success_rate(); o.push_str(&header("aurbuild_build_success_rate", "Share of recorded builds that succeeded.")); o.push_str(&format!("aurbuild_build_success_rate {rate:.4}\n")); o.push_str(&header("aurbuild_blocked_missing_dep", "Builds blocked on a package we have not published.")); o.push_str(&format!("aurbuild_blocked_missing_dep {}\n", self.blocked_missing_dep)); o.push_str(&header("aurbuild_index_packages", "Packages in the served index.")); o.push_str(&format!("aurbuild_index_packages {}\n", self.index_packages)); o.push_str(&header("aurbuild_releases", "Published releases on record.")); o.push_str(&format!("aurbuild_releases {}\n", self.releases)); o.push_str(&header("aurbuild_subscriptions", "Subscribed pkgbases.")); o.push_str(&format!("aurbuild_subscriptions {}\n", self.subscriptions)); o.push_str(&header("aurbuild_notices_unseen", "Notices no human has looked at.")); o.push_str(&format!("aurbuild_notices_unseen {}\n", self.notices_unseen)); o.push_str("# HELP aurbuild_stale_releases Releases whose recorded world no longer matches the index, by reason.\n# TYPE aurbuild_stale_releases gauge\n"); o.push_str(&format!("aurbuild_stale_releases{{reason=\"outdated\"}} {}\n", self.stale_outdated)); o.push_str(&format!("aurbuild_stale_releases{{reason=\"missing\"}} {}\n", self.stale_missing)); o.push_str(&header("aurbuild_downgrades", "Subscriptions where AUR offers a lower version than we serve.")); o.push_str(&format!("aurbuild_downgrades {}\n", self.downgrades)); o.push_str(&header("aurbuild_sqlite_size_bytes", "Main database file size.")); o.push_str(&format!("aurbuild_sqlite_size_bytes {}\n", self.db_bytes)); o.push_str(&header("aurbuild_sqlite_wal_size_bytes", "Write-ahead log size — large means nobody is checkpointing.")); o.push_str(&format!("aurbuild_sqlite_wal_size_bytes {}\n", self.wal_bytes)); o.push_str(&header("aurbuild_artifact_bytes", "Bytes held in the content-addressed store.")); o.push_str(&format!("aurbuild_artifact_bytes {}\n", self.artifact_bytes)); o.push_str(&header("aurbuild_staging_bytes", "Bytes in disposable staging directories.")); o.push_str(&format!("aurbuild_staging_bytes {}\n", self.staging_bytes)); o.push_str(&format!("# TYPE aurbuild_staging_dirs gauge\naurbuild_staging_dirs {}\n", self.staging_dirs)); match self.poll_lag_age_secs { Some(a) => { o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source.")); o.push_str(&format!("aurbuild_poll_lag_seconds {a}\n")); } None => { o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source.")); o.push_str("aurbuild_poll_lag_seconds nan\n"); } } match self.last_gc_age_secs { Some(a) => { o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run.")); o.push_str(&format!("aurbuild_last_gc_age_seconds {a}\n")); } None => { o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run.")); o.push_str("aurbuild_last_gc_age_seconds nan\n"); } } o } } /// Compute every metric from live state. pub fn metrics(cfg: &Config, db: &Db) -> Result { let mut m = Metrics::default(); let now = time::now(); m.builds = db.read(|c| { let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?; let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok::<_, crate::error::Error>(out) })?; let count = |state: &str| -> i64 { m.builds.iter().find(|(s, _)| s == state).map(|(_, n)| *n).unwrap_or(0) }; m.queue_depth = count("queued"); m.succeeded = count("succeeded"); m.failed = count("failed"); m.blocked_missing_dep = count("blocked_missing_dep"); let oldest = db.read(|c| { c.query_row( "SELECT julianday(?1) - julianday(min(created_at)) FROM build WHERE state='queued'", rusqlite::params![now], |r| r.get::<_, Option>(0), ) .map(|v| (v.unwrap_or(0.0) * 86400.0) as i64) .map_err(|e| crate::error::Error::db(e.to_string())) })?; m.oldest_queued_age_secs = oldest.max(0); m.pending_review = scalar(db, "SELECT count(*) FROM candidate WHERE state='pending_review'")?; m.review_ages = db.read(|c| { let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?; let rows = st.query_map(rusqlite::params![now], |r| r.get::<_, Option>(0))?; let mut out = Vec::new(); for r in rows { out.push((r?.unwrap_or(0.0) * 86400.0) as i64); } Ok::<_, crate::error::Error>(out) })?; m.review_ages.sort(); m.index_packages = scalar(db, "SELECT count(*) FROM package WHERE state='in_index'")?; m.releases = scalar(db, "SELECT count(*) FROM release WHERE state='published'")?; m.subscriptions = scalar(db, "SELECT count(*) FROM subscription")?; m.notices_unseen = scalar(db, "SELECT count(*) FROM notice WHERE acknowledged_at IS NULL")?; let stale = crate::watch::staleness::stale_rows(db)?; m.stale_outdated = stale.iter().filter(|s| s.kind == crate::watch::staleness::Kind::Outdated).count() as i64; m.stale_missing = stale.iter().filter(|s| s.kind == crate::watch::staleness::Kind::Missing).count() as i64; m.downgrades = crate::watch::staleness::downgrades(db)?.len() as i64; m.db_bytes = file_len(&cfg.db_path()); m.wal_bytes = file_len(&PathBuf::from(format!("{}-wal", cfg.db_path().display()))); m.artifact_bytes = db.read(|c| { c.query_row( "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL", [], |r| r.get::<_, i64>(0), ) .map(|v| v.max(0) as u64) .map_err(|e| crate::error::Error::db(e.to_string())) })?; let (dirs, bytes) = staging_usage(&cfg.staging_dir()); m.staging_dirs = dirs; m.staging_bytes = bytes; m.last_gc_age_secs = db .read(|c| { c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option>(0)) .map_err(|e| crate::error::Error::db(e.to_string())) })? .and_then(|t| time::delta_secs(&now, &t)); m.poll_lag_age_secs = db .read(|c| { c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option>(0)) .map_err(|e| crate::error::Error::db(e.to_string())) })? .and_then(|t| time::delta_secs(&now, &t)); let _ = cfg; Ok(m) } /// A Prometheus family header. Kept as a function rather than a closure over the /// output buffer so the borrow checker does not object to interleaving. fn header(name: &str, help: &str) -> String { format!("# HELP {name} {help}\n# TYPE {name} gauge\n") } fn scalar(db: &Db, sql: &str) -> Result { let sql = sql.to_string(); db.read(move |c| c.query_row(&sql, [], |r| r.get::<_, i64>(0)).map_err(|e| crate::error::Error::db(e.to_string()))) } fn file_len(p: &Path) -> u64 { std::fs::metadata(p).map(|m| m.len()).unwrap_or(0) } /// `(dir count, total bytes)` under a directory, tolerating concurrent removal. fn staging_usage(root: &Path) -> (usize, u64) { let mut dirs = 0; let mut bytes = 0; let Ok(entries) = std::fs::read_dir(root) else { return (0, 0) }; for e in entries.flatten() { if e.path().is_dir() { dirs += 1; bytes += dir_bytes(&e.path()); } } (dirs, bytes) } fn dir_bytes(path: &Path) -> u64 { let mut total = 0; let Ok(entries) = std::fs::read_dir(path) else { return 0 }; for e in entries.flatten() { let p = e.path(); if p.is_dir() { total += dir_bytes(&p); } else if let Ok(m) = std::fs::metadata(&p) { total += m.len(); } } total } /// Which releases of a pkgbase keep their files, and which lose them. /// /// The rule is "newest N, plus anything that would be a lie to evict": the /// currently accepted release and any release still backing an `in_index` /// package are kept regardless of how far down the list they sit. Evicting those /// would delete the bytes the index is actively pointing at, which is the one /// thing retention must never do — a rollback target is worth disk, a served /// package is not optional. pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec, Vec)> { let keep = keep.max(1); let pkgbases: Vec<(i64, Option)> = db.read(|c| { let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?; let rows = st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option>(1)?)))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok::<_, crate::error::Error>(out) })?; let mut kept = Vec::new(); let mut evict = Vec::new(); for (pb_id, accepted) in pkgbases { let releases: Vec = db.read(|c| { let mut st = c.prepare( "SELECT id FROM release WHERE pkgbase_id=?1 AND state='published' ORDER BY id DESC", )?; let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok::<_, crate::error::Error>(out) })?; // Still in the index? Then it is being served and is not a candidate for // eviction no matter how old it is. let serving: Vec = db.read(|c| { let mut st = c.prepare( "SELECT DISTINCT r.id FROM release r JOIN package p ON p.release_id=r.id WHERE r.pkgbase_id=?1 AND p.state='in_index' ORDER BY r.id DESC", )?; let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok::<_, crate::error::Error>(out) })?; let mut keep_set: std::collections::BTreeSet = serving.iter().cloned().collect(); if let Some(a) = accepted { keep_set.insert(a); } for id in releases.iter().take(keep) { keep_set.insert(*id); } for id in &releases { if keep_set.contains(id) { kept.push(*id); } else { evict.push(EvictPlan { release_id: *id }); } } } Ok((kept, evict)) } #[derive(Debug, Clone)] pub struct EvictPlan { pub release_id: i64, } /// Run retention: evict files for releases beyond the keep window, then sweep /// abandoned staging directories. /// /// Files are only removed when no *retained* release still references them. The /// store is content-addressed, so two releases built from the same source share /// one cached archive; deleting it because one release aged out would corrupt a /// release that is still current. pub fn retention(cfg: &Config, db: &Db, keep: Option) -> Result { let keep = keep.unwrap_or_else(|| setting_usize(db, "retention_versions", DEFAULT_KEEP)); let (kept, evict) = plan_retention(db, keep)?; // Everything still held by a kept release, so we do not evict a shared file. let mut retained_files: std::collections::BTreeSet = std::collections::BTreeSet::new(); for id in &kept { for f in release_files(cfg, db, *id)? { retained_files.insert(f); } } let mut report = RetentionReport { releases_kept: kept.len(), ..Default::default() }; for e in &evict { let files = release_files(cfg, db, e.release_id)?; let mut removed = 0usize; let mut freed = 0u64; for f in &files { if retained_files.contains(f) { continue; } if let Ok(m) = std::fs::metadata(f) { freed += m.len(); // A missing file is the state we are trying to reach, not an error. let _ = std::fs::remove_file(f); removed += 1; } } report.files_removed += removed; report.bytes_freed += freed; if removed > 0 || !files.is_empty() { report.releases_evicted += 1; mark_purged(db, e.release_id)?; } } let (swept, swept_bytes) = sweep_staging(cfg, db, STAGING_GRACE_SECS)?; report.staging_swept = swept; report.bytes_freed += swept_bytes; record_run(db, &report)?; let _ = db::audit( &db.writer, "system", "gc", "retention", "gc_run", "", serde_json::json!({ "keep": keep, "kept": report.releases_kept, "evicted": report.releases_evicted, "files_removed": report.files_removed, "bytes_freed": report.bytes_freed, "staging_swept": report.staging_swept, }), ); Ok(report) } /// Grace period before an abandoned staging dir is swept. Anything younger could /// belong to a build that is still running right now. pub const STAGING_GRACE_SECS: i64 = 3600; /// The files a release holds on disk: package, signature, build log, and the /// cached sources it was built from. /// /// These are returned as a unit because that is how they must be treated. A /// package without its build log is a byte nobody can explain, and a package /// without its sources cannot be rebuilt — keeping one and dropping the others /// is how a store ends up full of orphans and empty of answers. pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result> { let mut out = Vec::new(); let rows: Vec<(Option, Option, Option)> = db.read(|c| { let mut st = c.prepare( "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1", )?; let rows = st.query_map(rusqlite::params![release_id], |r| { Ok((r.get::<_, Option>(0)?, r.get::<_, Option>(1)?, r.get::<_, Option>(2)?)) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok::<_, crate::error::Error>(out) })?; for (path, sig, log) in rows { if let Some(p) = path { out.push(PathBuf::from(p)); } if let Some(p) = sig { out.push(PathBuf::from(p)); } if let Some(p) = log { out.push(PathBuf::from(p)); } } // Cached sources, by content digest (§5.1a: the mirror and the source cache // are what make an old release rebuildable). let digests: String = db .read(|c| { c.query_row( "SELECT source_digests_json FROM release WHERE id=?1", rusqlite::params![release_id], |r| r.get::<_, String>(0), ) .map_err(|e| crate::error::Error::db(e.to_string())) }) .unwrap_or_else(|_| "[]".into()); if let Ok(list) = serde_json::from_str::>(&digests) { for d in list { if !d.digest.is_empty() { out.push(cfg.source_cache_path(&d.digest)); } } } Ok(out) } fn mark_purged(db: &Db, release_id: i64) -> Result<()> { let at = time::now(); db.writer.tx(move |tx| { tx.execute( "UPDATE release SET purged_at=?1 WHERE id=?2", rusqlite::params![at, release_id], )?; tx.execute( "UPDATE artifact SET purged_at=?1 WHERE purged_at IS NULL AND id IN (SELECT a.id FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.release_id=?2)", rusqlite::params![at, release_id], )?; Ok(()) }) } /// Remove staging directories whose build is finished or unknown (§8.2: staging /// is disposable, and a GC pass sweeps what was abandoned). /// /// "Abandoned" is derived, not guessed: a dir is swept when its build row is in a /// terminal state, or when no build row exists at all, and the dir is older than /// the grace period. A dir belonging to a live build is left alone no matter how /// old it looks, because a long build is not an abandoned one. pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u64)> { let root = cfg.staging_dir(); let Ok(entries) = std::fs::read_dir(&root) else { return Ok((0, 0)) }; let now = time::now(); let mut swept = 0usize; let mut freed = 0u64; for e in entries.flatten() { let path = e.path(); if !path.is_dir() { continue; } let Some(build_id) = path.file_name().map(|s| s.to_string_lossy().to_string()) else { continue; }; let state: Option = db .read(|c| { Ok(c.query_row("SELECT state FROM build WHERE id=?1", rusqlite::params![build_id], |r| { r.get::<_, String>(0) }) .ok()) }) .unwrap_or(None); let abandonable = match &state { // No build row: staging left over from a crash before the row was // written, or from a build id that no longer exists. None => true, Some(s) => matches!(s.as_str(), "succeeded" | "failed" | "cancelled"), }; if !abandonable { continue; } let age = dir_age_secs(&path).unwrap_or(0); if age < grace_secs { continue; } let bytes = dir_bytes(&path); if std::fs::remove_dir_all(&path).is_ok() { swept += 1; freed += bytes; } } let _ = now; Ok((swept, freed)) } fn dir_age_secs(path: &Path) -> Option { let m = std::fs::metadata(path).ok()?; let t = m.modified().ok()?; let age = std::time::SystemTime::now().duration_since(t).ok()?; Some(age.as_secs() as i64) } fn record_run(db: &Db, r: &RetentionReport) -> Result<()> { let at = time::now(); let (kept, evicted, files, bytes, swept) = ( r.releases_kept as i64, r.releases_evicted as i64, r.files_removed as i64, r.bytes_freed as i64, r.staging_swept as i64, ); db.writer.tx(move |tx| { tx.execute( "INSERT INTO gc_run (ran_at, releases_kept, releases_evicted, files_removed, bytes_freed, staging_swept) VALUES (?1,?2,?3,?4,?5,?6)", rusqlite::params![at, kept, evicted, files, bytes, swept], )?; Ok(()) }) } fn setting_usize(db: &Db, key: &str, default: usize) -> usize { db.read(|c| { Ok(c.query_row("SELECT value FROM settings WHERE key=?1", rusqlite::params![key], |r| r.get::<_, String>(0)).ok()) }) .ok() .flatten() .and_then(|v| v.parse().ok()) .unwrap_or(default) } /// A consistent snapshot of the database, written to `dest`. /// /// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave /// with a write, and it produces a compacted single file with no WAL — which is /// what you want to be holding at 3am when the main file is gone. A `cp` of a /// live WAL database gives you a main file and a sidecar log that may or may not /// belong to it, and you find out which during the restore. pub fn backup(db: &Db, dest: &Path) -> Result { let dest = dest.to_path_buf(); if dest.exists() { return Err(crate::error::Error::not_found(format!( "refusing to overwrite an existing backup: {}", dest.display() ))); } if let Some(parent) = dest.parent() { if !parent.as_os_str().is_empty() && !parent.exists() { std::fs::create_dir_all(parent)?; } } let sql = format!("VACUUM INTO '{}'", dest.display().to_string().replace('\'', "''")); db.writer.call(move |conn| { conn.execute_batch(&sql) .map_err(|e| crate::error::Error::db(format!("VACUUM INTO: {e}")))?; Ok(()) })?; // The snapshot must be readable on its own: if it does not open and report // the same schema version, the backup is a file, not a backup. let probe = rusqlite::Connection::open(&dest) .map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?; let version: i64 = probe .query_row("PRAGMA user_version", [], |r| r.get(0)) .map_err(|e| crate::error::Error::db(format!("backup has no schema: {e}")))?; if version <= 0 { return Err(crate::error::Error::db("backup does not contain a migrated database")); } let _ = db::audit_system( &db.writer, "backup", "vacuum_into", &dest.display().to_string(), serde_json::json!({ "bytes": file_len(&dest), "schema_version": version }), ); Ok(dest) }