summaryrefslogtreecommitdiffstats
path: root/src/ops.rs
blob: d43c5280101b85e6af79bcbc9f8be1181cee71dd (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
use std::path::{Path, PathBuf};

use crate::config::Config;
use crate::db::{self, Db};
use crate::error::Result;
use crate::time;

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,
}

#[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,
    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 {
    /// The metrics report computes it internally; a test checks the arithmetic.
    ///
    /// Module-internal in a production build, `pub` only under `test-support`:
    /// one body behind two visibility declarations, exactly one of which compiles.
    #[cfg(feature = "test-support")]
    pub fn build_success_rate(&self) -> f64 {
        Self::build_success_rate_impl(self)
    }

    #[cfg(not(feature = "test-support"))]
    pub(crate) fn build_success_rate(&self) -> f64 {
        Self::build_success_rate_impl(self)
    }

    fn build_success_rate_impl(&self) -> f64 {
        match self.succeeded + self.failed {
            0 => 1.0,
            n => self.succeeded as f64 / n as f64,
        }
    }

    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));

        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
    }
}

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)
}

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)
}

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
}

pub(crate) 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)?;
        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(crate) struct EvictPlan {
    pub release_id: i64,
}

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)?;

    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();
                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)
}

/// How long a file may sit in staging before the sweep considers it abandoned.
///
/// The value lives once, in a private const, so the two visibility aliases below
/// cannot drift apart. Production reaches the grace period through
/// `run_maintenance`, which is the only thing that sweeps; a test that pins the
/// number is a test, not a caller.
const STAGING_GRACE_SECS_VALUE: i64 = 3600;

#[cfg(feature = "test-support")]
pub const STAGING_GRACE_SECS: i64 = STAGING_GRACE_SECS_VALUE;

#[cfg(not(feature = "test-support"))]
pub(crate) const STAGING_GRACE_SECS: i64 = STAGING_GRACE_SECS_VALUE;

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));
        }
    }
    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)
}

/// The maintenance pass calls it; a test pins what it sweeps without running the whole pass.
///
/// Module-internal in a production build, `pub` only under `test-support`:
/// one body behind two visibility declarations, exactly one of which compiles.
#[cfg(feature = "test-support")]
pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u64)> {
    sweep_staging_impl(cfg, db, grace_secs)
}

#[cfg(not(feature = "test-support"))]
pub(crate) fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u64)> {
    sweep_staging_impl(cfg, db, grace_secs)
}

fn sweep_staging_impl(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 {
            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,
    )
}

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)?;
    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)
}