OXYGENHUB
# 9e5fd161efc3 oxygenflow / crates / flow-init / src / prune.rs
16.0 KiB · Rust · last changed Prune build caches before they are kept 16 days ago source blame history raw
1
//! Pruning a build cache before it is kept (oxygenflow#72, spec §5.4).
2
//!
3
//! A kept disk starts the next run, so without pruning it carries every
4
//! build's files: each crate's artifacts under every hash a lockfile or a
5
//! feature set ever gave it. Before a passing job's cache disk goes back
6
//! into the pool, the files this run did not use are removed, oldest
7
//! first, until what is on the disk is at most a share of its size (the
8
//! cap). The microVM's guest init prunes its disks before it powers off,
9
//! since only it can see inside them; the runner prunes the syscall
10
//! tier's directories itself. Both use this module.
11
//!
12
//! What the run used is told by the files' times against when the job
13
//! started: written (mtime), changed (ctime) or read (atime). Reads are
14
//! seen only where the file system records them: the guest mounts a cache
15
//! disk `strictatime`; on the runner, where a directory sits on whatever
16
//! file system the runner has, each file's atime is set to the epoch
17
//! before the job ([`forget_reads`]), so even `relatime` records its
18
//! first read. A file system mounted `noatime` records none, and then
19
//! nothing is pruned.
20
//!
21
//! A build tool does not read everything it relies on. Cargo, finding a
22
//! crate fresh, reads its fingerprint and only looks at its rlib and
23
//! binaries, so their times say nothing. Every name cargo gives a unit's
24
//! files carries the unit's hash (`.fingerprint/foo-<hash>/`,
25
//! `deps/libfoo-<hash>.rlib`, `build/foo-<hash>/`), so a file stays when
26
//! a file this run used carries one of the hashes in its path: a fresh
27
//! crate's fingerprint keeps its artifacts. A file with another link
28
//! that stays, or under a path the job's outputs name, stays too. What
29
//! goes is what this run's build did not touch, which a later build needs
30
//! only if an older lockfile comes back, and then cargo rebuilds it.
31
32
use serde::{Deserialize, Serialize};
33
use std::collections::{HashMap, HashSet};
34
use std::os::unix::fs::MetadataExt;
35
use std::path::{Path, PathBuf};
36
use std::time::{Duration, SystemTime};
37
38
/// The share of a cache disk a kept cache may fill when no runner says
39
/// otherwise: room for this run's build and as much again.
40
pub const DEFAULT_PERCENT: u8 = 60;
41
42
/// What pruning a cache found and did, in bytes of blocks on its disk.
43
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
44
pub struct Pruned {
45
    /// The disk's size, and the share of it the cache may fill.
46
    pub size: u64,
47
    pub percent: u8,
48
    /// What was on the disk before pruning, and after.
49
    pub before: u64,
50
    pub after: u64,
51
    /// What went: bytes and files.
52
    pub freed: u64,
53
    pub files: u64,
54
    /// Why nothing could be pruned, when so (no access times, or an
55
    /// error): only the size then decides.
56
    #[serde(default, skip_serializing_if = "Option::is_none")]
57
    pub unpruned: Option<String>,
58
}
59
60
impl Pruned {
61
    /// The most the cache may keep: `percent` of `size`.
62
    pub fn cap(&self) -> u64 {
63
        cap(self.size, self.percent)
64
    }
65
66
    /// Whether what is left may be kept.
67
    pub fn fits(&self) -> bool {
68
        self.after <= self.cap()
69
    }
70
}
71
72
fn cap(size: u64, percent: u8) -> u64 {
73
    (size as u128 * percent.min(100) as u128 / 100) as u64
74
}
75
76
/// Now, as a job's start to compare file times against. File systems
77
/// stamp times from a clock that may lag this one by a tick, so the
78
/// moments either side of it are left to pass: nothing done before the
79
/// call (such as [`forget_reads`]) can look as though it came after.
80
pub fn start_clock() -> SystemTime {
81
    std::thread::sleep(Duration::from_millis(20));
82
    let t = SystemTime::now();
83
    std::thread::sleep(Duration::from_millis(20));
84
    t
85
}
86
87
/// Whether the file system holding `path` records reads (not `noatime`).
88
pub fn records_reads(path: &Path) -> bool {
89
    let Ok(c) = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()) else { return false };
90
    let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
91
    if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
92
        return false;
93
    }
94
    st.f_flag & libc::ST_NOATIME == 0
95
}
96
97
/// The blocks in use on the file system mounted at `path`, and its size
98
/// (as `df` counts them).
99
pub fn usage(path: &Path) -> std::io::Result<(u64, u64)> {
100
    let c = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())?;
101
    let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
102
    if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
103
        return Err(std::io::Error::last_os_error());
104
    }
105
    let unit = st.f_frsize as u64;
106
    Ok(((st.f_blocks as u64).saturating_sub(st.f_bfree as u64) * unit, st.f_blocks as u64 * unit))
107
}
108
109
/// Set every regular file's atime under `root` to the epoch, its mtime
110
/// kept, so the job's first read of each is recorded even on `relatime`
111
/// (which records a read only of a file read no later than it changed).
112
/// Links are not followed. The count of files.
113
pub fn forget_reads(root: &Path) -> std::io::Result<u64> {
114
    let mut n = 0;
115
    let mut err = None;
116
    walk(root, &mut |p, md| {
117
        if !md.file_type().is_file() {
118
            return;
119
        }
120
        let Ok(c) = std::ffi::CString::new(p.as_os_str().as_encoded_bytes()) else { return };
121
        let times = [libc::timespec { tv_sec: 0, tv_nsec: 0 }, libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT }];
122
        if unsafe { libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), libc::AT_SYMLINK_NOFOLLOW) } == 0 {
123
            n += 1;
124
        } else if err.is_none() {
125
            err = Some(std::io::Error::last_os_error());
126
        }
127
    })?;
128
    match err {
129
        Some(e) => Err(e),
130
        None => Ok(n),
131
    }
132
}
133
134
/// Each entry under `root` (not `root` itself) with its metadata, parents
135
/// before children; links are not followed, nor other file systems
136
/// entered.
137
fn walk(root: &Path, f: &mut dyn FnMut(&Path, &std::fs::Metadata)) -> std::io::Result<()> {
138
    let dev = std::fs::symlink_metadata(root)?.dev();
139
    let mut dirs = vec![root.to_path_buf()];
140
    while let Some(d) = dirs.pop() {
141
        let Ok(entries) = std::fs::read_dir(&d) else { continue };
142
        for e in entries.flatten() {
143
            let p = e.path();
144
            let Ok(md) = std::fs::symlink_metadata(&p) else { continue };
145
            if md.dev() != dev {
146
                continue;
147
            }
148
            f(&p, &md);
149
            if md.is_dir() {
150
                dirs.push(p);
151
            }
152
        }
153
    }
154
    Ok(())
155
}
156
157
/// The unit hashes in `rel`: a 16-digit lowercase hex word after a `-`
158
/// in any of its names, as cargo names a unit's files.
159
fn hashes(rel: &Path) -> impl Iterator<Item = String> + '_ {
160
    rel.components().filter_map(|c| c.as_os_str().to_str()).flat_map(|name| {
161
        name.split('-').skip(1).filter_map(|w| {
162
            let w = w.split('.').next().unwrap_or("");
163
            (w.len() == 16 && w.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))).then(|| w.to_string())
164
        })
165
    })
166
}
167
168
fn nanos(s: i64, ns: i64) -> i128 {
169
    s as i128 * 1_000_000_000 + ns as i128
170
}
171
172
/// One file, however many names it has.
173
struct File {
174
    paths: Vec<PathBuf>,
175
    links: u64,
176
    bytes: u64,
177
    /// When it was last used as far as can be told: the later of its
178
    /// atime and mtime.
179
    last: i128,
180
    used: bool,
181
}
182
183
/// Prune the cache at `root`, a disk of `size` bytes with `before` in
184
/// use, down to `percent` of its size, removing only regular files this
185
/// run did not use (see the module's notes), those used longest ago
186
/// first. `started` is when the job started ([`start_clock`]); `keep` are
187
/// paths relative to `root` (the job's outputs) that stay whatever their
188
/// times. Under the cap nothing is touched. `after` is `before` less what
189
/// was freed.
190
pub fn prune(root: &Path, started: SystemTime, keep: &[String], size: u64, before: u64, percent: u8) -> std::io::Result<Pruned> {
191
    let mut out = Pruned { size, percent, before, after: before, ..Pruned::default() };
192
    if before <= out.cap() {
193
        return Ok(out);
194
    }
195
    let since = started.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_nanos() as i128).unwrap_or(0);
196
    let keep: Vec<PathBuf> = keep.iter().map(|k| PathBuf::from(k.trim_start_matches('/'))).filter(|k| !k.as_os_str().is_empty()).collect();
197
    let mut files: HashMap<(u64, u64), File> = HashMap::new();
198
    walk(root, &mut |p, md| {
199
        if !md.file_type().is_file() {
200
            return;
201
        }
202
        let rel = p.strip_prefix(root).unwrap_or(p);
203
        let used = [nanos(md.atime(), md.atime_nsec()), nanos(md.mtime(), md.mtime_nsec()), nanos(md.ctime(), md.ctime_nsec())]
204
            .into_iter()
205
            .any(|t| t >= since)
206
            || keep.iter().any(|k| rel.starts_with(k));
207
        let f = files.entry((md.dev(), md.ino())).or_insert_with(|| File {
208
            paths: Vec::new(),
209
            links: md.nlink(),
210
            bytes: md.blocks() * 512,
211
            last: nanos(md.atime(), md.atime_nsec()).max(nanos(md.mtime(), md.mtime_nsec())),
212
            used: false,
213
        });
214
        f.paths.push(p.to_path_buf());
215
        f.used |= used;
216
    })?;
217
    // A hash any used file carries keeps every file carrying it.
218
    let live: HashSet<String> =
219
        files.values().filter(|f| f.used).flat_map(|f| f.paths.iter().flat_map(|p| hashes(p.strip_prefix(root).unwrap_or(p)))).collect();
220
    let mut gone: Vec<File> = files
221
        .into_values()
222
        .filter(|f| {
223
            !f.used
224
                // A link from outside the cache: removing it frees nothing.
225
                && f.links == f.paths.len() as u64
226
                && !f.paths.iter().any(|p| hashes(p.strip_prefix(root).unwrap_or(p)).any(|h| live.contains(&h)))
227
        })
228
        .collect();
229
    gone.sort_by_key(|f| f.last);
230
    let mut emptied: HashSet<PathBuf> = HashSet::new();
231
    for f in gone {
232
        if out.after <= out.cap() {
233
            break;
234
        }
235
        let mut removed = true;
236
        for p in &f.paths {
237
            if std::fs::remove_file(p).is_err() {
238
                removed = false;
239
            } else if let Some(parent) = p.parent() {
240
                emptied.insert(parent.to_path_buf());
241
            }
242
        }
243
        if removed {
244
            out.after = out.after.saturating_sub(f.bytes);
245
            out.freed += f.bytes;
246
            out.files += 1;
247
        }
248
    }
249
    // Directories pruning emptied go too, deepest first; never `root`.
250
    let mut dirs: Vec<PathBuf> = emptied.into_iter().collect();
251
    dirs.sort_by_key(|d| std::cmp::Reverse(d.components().count()));
252
    for d in dirs {
253
        let mut d = d.as_path();
254
        while d != root && d.starts_with(root) && std::fs::remove_dir(d).is_ok() {
255
            match d.parent() {
256
                Some(p) => d = p,
257
                None => break,
258
            }
259
        }
260
    }
261
    Ok(out)
262
}
263
264
#[cfg(test)]
265
mod tests {
266
    use super::*;
267
268
    /// Times around a job that started at `T`, ahead of the clock: a file
269
    /// whose times are set is changed (ctime) now, before it.
270
    const T: u64 = 4_000_000_000;
271
272
    fn at(secs: u64) -> SystemTime {
273
        SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
274
    }
275
276
    /// A file of `kib` KiB at `rel`, last read and written at `secs`.
277
    fn file(root: &Path, rel: &str, kib: usize, secs: u64) -> PathBuf {
278
        let p = root.join(rel);
279
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
280
        let bytes: Vec<u8> = (0..kib << 10).map(|i: usize| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
281
        std::fs::write(&p, bytes).unwrap();
282
        let f = std::fs::File::options().write(true).open(&p).unwrap();
283
        f.set_times(std::fs::FileTimes::new().set_accessed(at(secs)).set_modified(at(secs))).unwrap();
284
        p
285
    }
286
287
    fn bytes(p: &Path) -> u64 {
288
        std::fs::metadata(p).unwrap().blocks() * 512
289
    }
290
291
    #[test]
292
    fn hashes_are_cargos_unit_hashes() {
293
        let h = |p: &str| hashes(Path::new(p)).collect::<Vec<_>>();
294
        assert_eq!(h("debug/deps/libdep-8f2b19826c505967.rlib"), ["8f2b19826c505967"]);
295
        assert_eq!(h("debug/.fingerprint/dep-8f2b19826c505967/lib-dep"), ["8f2b19826c505967"]);
296
        assert_eq!(h("debug/build/my-crate-0123456789abcdef/out/x.o"), ["0123456789abcdef"]);
297
        assert!(h("debug/incremental/app-2dadnjnzlrswc/s-hndl5uwdpw-1uaho4m.lock").is_empty());
298
        assert!(h("debug/app").is_empty() && h("debug/deps/x-0123456789ABCDEF").is_empty() && h("x-0123456789abcde").is_empty());
299
    }
300
301
    #[test]
302
    fn under_the_cap_nothing_is_touched() {
303
        let dir = tempfile::tempdir().unwrap();
304
        let old = file(dir.path(), "debug/deps/libold-1111111111111111.rlib", 64, 1_000);
305
        let p = prune(dir.path(), at(T), &[], 1 << 30, 64 << 10, 60).unwrap();
306
        assert!(old.exists() && p.fits() && p.freed == 0 && p.after == p.before, "{p:?}");
307
    }
308
309
    /// A cargo target as a run leaves it: this lockfile's units used this
310
    /// run (one rebuilt, one fresh: only its fingerprint read), an older
311
    /// lockfile's not, and an output the run did not touch.
312
    #[test]
313
    fn what_this_run_did_not_use_goes_oldest_first_and_its_units_stay_whole() {
314
        let dir = tempfile::tempdir().unwrap();
315
        let root = dir.path();
316
        let app = file(root, "debug/deps/app-aaaaaaaaaaaaaaaa", 256, T + 100);
317
        let app_fp = file(root, "debug/.fingerprint/app-aaaaaaaaaaaaaaaa/bin-app", 1, T + 100);
318
        let dep_rlib = file(root, "debug/deps/libdep-bbbbbbbbbbbbbbbb.rlib", 256, T - 5_000);
319
        let dep_fp = file(root, "debug/.fingerprint/dep-bbbbbbbbbbbbbbbb/lib-dep", 1, T - 5_000);
320
        std::fs::File::open(&dep_fp).unwrap().set_times(std::fs::FileTimes::new().set_accessed(at(T + 50))).unwrap();
321
        let script = file(root, "debug/build/dep-bbbbbbbbbbbbbbbb/out/gen.rs", 64, T - 5_000);
322
        // Uplifted: another name of the rebuilt binary.
323
        std::fs::hard_link(&app, root.join("debug/app")).unwrap();
324
        // An older lockfile's units, untouched, the oldest first to go.
325
        let oldest = file(root, "debug/deps/libdep-cccccccccccccccc.rlib", 256, T - 9_000);
326
        let oldest_fp = file(root, "debug/.fingerprint/dep-cccccccccccccccc/lib-dep", 1, T - 8_999);
327
        let older = file(root, "debug/deps/libdep-dddddddddddddddd.rlib", 256, T - 8_000);
328
        // A declared output, older still, that the run did not touch.
329
        let output = file(root, "release/tool", 128, T - 10_000);
330
        let all = [&app, &app_fp, &dep_rlib, &dep_fp, &script, &oldest, &oldest_fp, &older, &output];
331
        let before: u64 = all.iter().map(|p| bytes(p)).sum();
332
        // Room for all but the oldest unit.
333
        let want = before - bytes(&oldest) - bytes(&oldest_fp);
334
        let size = (want * 100).div_ceil(60);
335
        let p = prune(root, at(T), &["/release/tool".into()], size, before, 60).unwrap();
336
        assert!(p.fits(), "{p:?}");
337
        assert!(
338
            !oldest.exists() && !root.join("debug/.fingerprint/dep-cccccccccccccccc").exists(),
339
            "the oldest unit went, its emptied directory too"
340
        );
341
        assert!(older.exists(), "and pruning stopped under the cap: {p:?}");
342
        for kept in [&app, &app_fp, &dep_rlib, &dep_fp, &script, &output, &root.join("debug/app")] {
343
            assert!(kept.exists(), "{} stays", kept.display());
344
        }
345
        assert_eq!((p.files, p.freed, p.after), (2, p.before - want, want));
346
        // With no room at all: still only what the run did not use goes.
347
        let p = prune(root, at(T), &["release/tool".into()], 1, p.after, 60).unwrap();
348
        assert!(!older.exists() && !p.fits() && p.files == 1, "{p:?}");
349
        for kept in [&app, &dep_rlib, &dep_fp, &script, &output] {
350
            assert!(kept.exists(), "{} stays", kept.display());
351
        }
352
        assert!(root.join("debug/deps").is_dir(), "a directory still holding files stays");
353
    }
354
355
    #[test]
356
    fn reads_are_forgotten_so_the_next_is_seen() {
357
        let dir = tempfile::tempdir().unwrap();
358
        let p = file(dir.path(), "a/b", 1, 5_000);
359
        std::os::unix::fs::symlink("/etc/passwd", dir.path().join("link")).unwrap();
360
        assert_eq!(forget_reads(dir.path()).unwrap(), 1);
361
        let md = std::fs::metadata(&p).unwrap();
362
        assert_eq!((md.atime(), md.mtime()), (0, 5_000), "the mtime is kept");
363
        assert!(std::fs::symlink_metadata(dir.path().join("link")).unwrap().atime() > 0, "a link is not followed");
364
    }
365
}