forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

disk.rs64 lines, 2.4 KiBHistoryRawDownload
1//! The disk cap of a builtin job (`limits.job_disk_gb`).
2//!
3//! A rootless runner has no quotas, so the runner measures what the job wrote every few seconds
4//! and stops it once that passes the cap. A job can overshoot by what it writes between two
5//! checks. In subuid mode a dir the job made unreadable to the runner is not counted.
6
7use std::collections::HashSet;
8use std::fs;
9use std::os::unix::fs::MetadataExt;
10use std::path::PathBuf;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::time::{Duration, Instant};
14
15use tokio_util::sync::CancellationToken;
16
17/// How often the job's disk use is measured, at most. A measurement that takes long (a huge tree)
18/// spaces the next one out to four times its own length, so the walk stays a small share of the
19/// runner's time.
20const INTERVAL: Duration = Duration::from_secs(2);
21
22/// The bytes allocated under `roots`. Symlinks are not followed, and a file with several hard
23/// links counts once. Entries that can't be read are skipped.
24pub fn usage(roots: &[PathBuf]) -> u64 {
25 let mut seen = HashSet::new();
26 let mut total = 0u64;
27 let mut stack: Vec<PathBuf> = roots.to_vec();
28 while let Some(path) = stack.pop() {
29 let Ok(meta) = fs::symlink_metadata(&path) else {
30 continue;
31 };
32 if meta.nlink() > 1 && !meta.is_dir() && !seen.insert((meta.dev(), meta.ino())) {
33 continue;
34 }
35 total = total.saturating_add(meta.blocks().saturating_mul(512));
36 if meta.is_dir()
37 && let Ok(entries) = fs::read_dir(&path)
38 {
39 stack.extend(entries.flatten().map(|entry| entry.path()));
40 }
41 }
42 total
43}
44
45/// Measures `roots` about every [`INTERVAL`] until it passes `cap` bytes, then sets `over` and cancels
46/// `job`. Runs until it fires or is aborted.
47pub async fn watch(roots: Vec<PathBuf>, cap: u64, job: CancellationToken, over: Arc<AtomicBool>) {
48 let roots = Arc::new(roots);
49 let mut pause = INTERVAL;
50 loop {
51 tokio::time::sleep(pause).await;
52 let measured = Arc::clone(&roots);
53 let started = Instant::now();
54 let Ok(used) = tokio::task::spawn_blocking(move || usage(&measured)).await else {
55 return;
56 };
57 pause = INTERVAL.max(started.elapsed() * 4);
58 if used > cap {
59 over.store(true, Ordering::SeqCst);
60 job.cancel();
61 return;
62 }
63 }
64}