summaryrefslogtreecommitdiffstats
path: root/src/ops.rs
blob: fd644c39a57783fdae3b5abb926049c82cc2918d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! 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<i64>,
    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<i64>,
    pub poll_lag_age_secs: Option<i64>,
}

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<Metrics> {
    let mut m = Metrics::default();
    let now = time::now();

    m.builds = db::build_state_counts(db)?;
    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");

    m.oldest_queued_age_secs = db::oldest_queued_age_secs(db, &now)?;

    m.pending_review = db::count_pending_reviews(db)?;
    m.review_ages = db::pending_review_ages_secs(db, &now)?;
    m.review_ages.sort();

    m.index_packages = db::count_index_packages(db)?;
    m.releases = db::count_published_releases(db)?;
    m.subscriptions = db::count_subscriptions(db)?;
    m.notices_unseen = db::count_unacknowledged_notices(db)?;

    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::artifact_bytes_served(db)?;
    let (dirs, bytes) = staging_usage(&cfg.staging_dir());
    m.staging_dirs = dirs;
    m.staging_bytes = bytes;

    m.last_gc_age_secs = db::last_gc_age_secs(db, &now)?;
    m.poll_lag_age_secs = db::last_poll_age_secs(db, &now)?;
    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 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<i64>, Vec<EvictPlan>)> {
    let keep = keep.max(1);
    let pkgbases = db::pkgbase_release_pointers(db)?;

    let mut kept = Vec::new();
    let mut evict = Vec::new();
    for (pb_id, accepted) in pkgbases {
        let releases = db::published_release_ids(db, pb_id)?;
        // Still in the index? Then it is being served and is not a candidate for
        // eviction no matter how old it is.
        let serving = db::serving_release_ids(db, pb_id)?;

        let mut keep_set: std::collections::BTreeSet<i64> = 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<usize>) -> Result<RetentionReport> {
    let keep = keep.unwrap_or_else(|| db::setting_i64(db, "retention_versions", DEFAULT_KEEP as i64) as usize);
    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<PathBuf> = 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;
            db::mark_release_purged(&db.writer, 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<Vec<PathBuf>> {
    let mut out = Vec::new();
    for (path, sig, log) in db::release_artifact_paths(db, release_id)? {
        for p in [path, sig, log].into_iter().flatten() {
            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 = db::release_by_id(db, release_id)?
        .map(|r| r.source_digests_json)
        .unwrap_or_else(|| "[]".into());
    if let Ok(list) = serde_json::from_str::<Vec<db::SourceDigest>>(&digests) {
        for d in list {
            if !d.digest.is_empty() {
                out.push(cfg.source_cache_path(&d.digest));
            }
        }
    }
    Ok(out)
}

/// 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 = db::builds::get(db, &build_id)?.map(|b| b.state);
        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<i64> {
    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<()> {
    db::record_gc_run(
        &db.writer,
        &time::now(),
        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,
    )
}

/// 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<PathBuf> {
    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)?;
        }
    }
    db::backup_to(&db.writer, &dest)?;
    // 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 version = db::schema_version(&dest)
        .map_err(|e| crate::error::Error::db(format!("backup unreadable: {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)
}