| 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 |
use serde::{Deserialize, Serialize}; |
| 33 |
#[cfg(unix)] |
| 34 |
use std::collections::{HashMap, HashSet}; |
| 35 |
#[cfg(unix)] |
| 36 |
use std::os::unix::fs::MetadataExt; |
| 37 |
use std::path::Path; |
| 38 |
#[cfg(unix)] |
| 39 |
use std::path::PathBuf; |
| 40 |
use std::time::{Duration, SystemTime}; |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
pub const DEFAULT_PERCENT: u8 = 60; |
| 45 |
|
| 46 |
|
| 47 |
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] |
| 48 |
pub struct Pruned { |
| 49 |
|
| 50 |
pub size: u64, |
| 51 |
pub percent: u8, |
| 52 |
|
| 53 |
pub before: u64, |
| 54 |
pub after: u64, |
| 55 |
|
| 56 |
pub freed: u64, |
| 57 |
pub files: u64, |
| 58 |
|
| 59 |
|
| 60 |
#[serde(default, skip_serializing_if = "Option::is_none")] |
| 61 |
pub unpruned: Option<String>, |
| 62 |
} |
| 63 |
|
| 64 |
impl Pruned { |
| 65 |
|
| 66 |
pub fn cap(&self) -> u64 { |
| 67 |
cap(self.size, self.percent) |
| 68 |
} |
| 69 |
|
| 70 |
|
| 71 |
pub fn fits(&self) -> bool { |
| 72 |
self.after <= self.cap() |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
fn cap(size: u64, percent: u8) -> u64 { |
| 77 |
(size as u128 * percent.min(100) as u128 / 100) as u64 |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
pub fn start_clock() -> SystemTime { |
| 85 |
std::thread::sleep(Duration::from_millis(20)); |
| 86 |
let t = SystemTime::now(); |
| 87 |
std::thread::sleep(Duration::from_millis(20)); |
| 88 |
t |
| 89 |
} |
| 90 |
|
| 91 |
#[cfg(unix)] |
| 92 |
|
| 93 |
pub fn records_reads(path: &Path) -> bool { |
| 94 |
let Ok(c) = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()) else { return false }; |
| 95 |
let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; |
| 96 |
if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 { |
| 97 |
return false; |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
#[cfg(any(target_os = "linux", target_os = "android"))] |
| 102 |
return st.f_flag & libc::ST_NOATIME == 0; |
| 103 |
#[cfg(not(any(target_os = "linux", target_os = "android")))] |
| 104 |
true |
| 105 |
} |
| 106 |
|
| 107 |
#[cfg(unix)] |
| 108 |
|
| 109 |
|
| 110 |
pub fn usage(path: &Path) -> std::io::Result<(u64, u64)> { |
| 111 |
let c = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())?; |
| 112 |
let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; |
| 113 |
if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 { |
| 114 |
return Err(std::io::Error::last_os_error()); |
| 115 |
} |
| 116 |
let unit = st.f_frsize as u64; |
| 117 |
Ok(((st.f_blocks as u64).saturating_sub(st.f_bfree as u64) * unit, st.f_blocks as u64 * unit)) |
| 118 |
} |
| 119 |
|
| 120 |
#[cfg(unix)] |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
pub fn forget_reads(root: &Path) -> std::io::Result<u64> { |
| 126 |
let mut n = 0; |
| 127 |
let mut err = None; |
| 128 |
walk(root, &mut |p, md| { |
| 129 |
if !md.file_type().is_file() { |
| 130 |
return; |
| 131 |
} |
| 132 |
let Ok(c) = std::ffi::CString::new(p.as_os_str().as_encoded_bytes()) else { return }; |
| 133 |
let times = [libc::timespec { tv_sec: 0, tv_nsec: 0 }, libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT }]; |
| 134 |
if unsafe { libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), libc::AT_SYMLINK_NOFOLLOW) } == 0 { |
| 135 |
n += 1; |
| 136 |
} else if err.is_none() { |
| 137 |
err = Some(std::io::Error::last_os_error()); |
| 138 |
} |
| 139 |
})?; |
| 140 |
match err { |
| 141 |
Some(e) => Err(e), |
| 142 |
None => Ok(n), |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
#[cfg(unix)] |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
fn walk(root: &Path, f: &mut dyn FnMut(&Path, &std::fs::Metadata)) -> std::io::Result<()> { |
| 151 |
let dev = std::fs::symlink_metadata(root)?.dev(); |
| 152 |
let mut dirs = vec![root.to_path_buf()]; |
| 153 |
while let Some(d) = dirs.pop() { |
| 154 |
let Ok(entries) = std::fs::read_dir(&d) else { continue }; |
| 155 |
for e in entries.flatten() { |
| 156 |
let p = e.path(); |
| 157 |
let Ok(md) = std::fs::symlink_metadata(&p) else { continue }; |
| 158 |
if md.dev() != dev { |
| 159 |
continue; |
| 160 |
} |
| 161 |
f(&p, &md); |
| 162 |
if md.is_dir() { |
| 163 |
dirs.push(p); |
| 164 |
} |
| 165 |
} |
| 166 |
} |
| 167 |
Ok(()) |
| 168 |
} |
| 169 |
|
| 170 |
#[cfg(unix)] |
| 171 |
|
| 172 |
|
| 173 |
fn hashes(rel: &Path) -> impl Iterator<Item = String> + '_ { |
| 174 |
rel.components().filter_map(|c| c.as_os_str().to_str()).flat_map(|name| { |
| 175 |
name.split('-').skip(1).filter_map(|w| { |
| 176 |
let w = w.split('.').next().unwrap_or(""); |
| 177 |
(w.len() == 16 && w.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))).then(|| w.to_string()) |
| 178 |
}) |
| 179 |
}) |
| 180 |
} |
| 181 |
|
| 182 |
#[cfg(unix)] |
| 183 |
fn nanos(s: i64, ns: i64) -> i128 { |
| 184 |
s as i128 * 1_000_000_000 + ns as i128 |
| 185 |
} |
| 186 |
|
| 187 |
#[cfg(unix)] |
| 188 |
|
| 189 |
struct File { |
| 190 |
paths: Vec<PathBuf>, |
| 191 |
links: u64, |
| 192 |
bytes: u64, |
| 193 |
|
| 194 |
|
| 195 |
last: i128, |
| 196 |
used: bool, |
| 197 |
} |
| 198 |
|
| 199 |
#[cfg(unix)] |
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
pub fn prune(root: &Path, started: SystemTime, keep: &[String], size: u64, before: u64, percent: u8) -> std::io::Result<Pruned> { |
| 208 |
let mut out = Pruned { size, percent, before, after: before, ..Pruned::default() }; |
| 209 |
if before <= out.cap() { |
| 210 |
return Ok(out); |
| 211 |
} |
| 212 |
let since = started.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_nanos() as i128).unwrap_or(0); |
| 213 |
let keep: Vec<PathBuf> = keep.iter().map(|k| PathBuf::from(k.trim_start_matches('/'))).filter(|k| !k.as_os_str().is_empty()).collect(); |
| 214 |
let mut files: HashMap<(u64, u64), File> = HashMap::new(); |
| 215 |
walk(root, &mut |p, md| { |
| 216 |
if !md.file_type().is_file() { |
| 217 |
return; |
| 218 |
} |
| 219 |
let rel = p.strip_prefix(root).unwrap_or(p); |
| 220 |
let used = [nanos(md.atime(), md.atime_nsec()), nanos(md.mtime(), md.mtime_nsec()), nanos(md.ctime(), md.ctime_nsec())] |
| 221 |
.into_iter() |
| 222 |
.any(|t| t >= since) |
| 223 |
|| keep.iter().any(|k| rel.starts_with(k)); |
| 224 |
let f = files.entry((md.dev(), md.ino())).or_insert_with(|| File { |
| 225 |
paths: Vec::new(), |
| 226 |
links: md.nlink(), |
| 227 |
bytes: md.blocks() * 512, |
| 228 |
last: nanos(md.atime(), md.atime_nsec()).max(nanos(md.mtime(), md.mtime_nsec())), |
| 229 |
used: false, |
| 230 |
}); |
| 231 |
f.paths.push(p.to_path_buf()); |
| 232 |
f.used |= used; |
| 233 |
})?; |
| 234 |
|
| 235 |
let live: HashSet<String> = |
| 236 |
files.values().filter(|f| f.used).flat_map(|f| f.paths.iter().flat_map(|p| hashes(p.strip_prefix(root).unwrap_or(p)))).collect(); |
| 237 |
let mut gone: Vec<File> = files |
| 238 |
.into_values() |
| 239 |
.filter(|f| { |
| 240 |
!f.used |
| 241 |
|
| 242 |
&& f.links == f.paths.len() as u64 |
| 243 |
&& !f.paths.iter().any(|p| hashes(p.strip_prefix(root).unwrap_or(p)).any(|h| live.contains(&h))) |
| 244 |
}) |
| 245 |
.collect(); |
| 246 |
gone.sort_by_key(|f| f.last); |
| 247 |
let mut emptied: HashSet<PathBuf> = HashSet::new(); |
| 248 |
for f in gone { |
| 249 |
if out.after <= out.cap() { |
| 250 |
break; |
| 251 |
} |
| 252 |
let mut removed = true; |
| 253 |
for p in &f.paths { |
| 254 |
if std::fs::remove_file(p).is_err() { |
| 255 |
removed = false; |
| 256 |
} else if let Some(parent) = p.parent() { |
| 257 |
emptied.insert(parent.to_path_buf()); |
| 258 |
} |
| 259 |
} |
| 260 |
if removed { |
| 261 |
out.after = out.after.saturating_sub(f.bytes); |
| 262 |
out.freed += f.bytes; |
| 263 |
out.files += 1; |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
let mut dirs: Vec<PathBuf> = emptied.into_iter().collect(); |
| 268 |
dirs.sort_by_key(|d| std::cmp::Reverse(d.components().count())); |
| 269 |
for d in dirs { |
| 270 |
let mut d = d.as_path(); |
| 271 |
while d != root && d.starts_with(root) && std::fs::remove_dir(d).is_ok() { |
| 272 |
match d.parent() { |
| 273 |
Some(p) => d = p, |
| 274 |
None => break, |
| 275 |
} |
| 276 |
} |
| 277 |
} |
| 278 |
Ok(out) |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
#[cfg(not(unix))] |
| 285 |
pub fn records_reads(_path: &Path) -> bool { |
| 286 |
false |
| 287 |
} |
| 288 |
|
| 289 |
#[cfg(not(unix))] |
| 290 |
pub fn usage(_path: &Path) -> std::io::Result<(u64, u64)> { |
| 291 |
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "cache disks are pruned only on Linux")) |
| 292 |
} |
| 293 |
|
| 294 |
#[cfg(not(unix))] |
| 295 |
pub fn forget_reads(_root: &Path) -> std::io::Result<u64> { |
| 296 |
Ok(0) |
| 297 |
} |
| 298 |
|
| 299 |
#[cfg(not(unix))] |
| 300 |
pub fn prune(_root: &Path, _started: SystemTime, _keep: &[String], _size: u64, _before: u64, _percent: u8) -> std::io::Result<Pruned> { |
| 301 |
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "cache disks are pruned only on Linux")) |
| 302 |
} |
| 303 |
|
| 304 |
#[cfg(all(test, unix))] |
| 305 |
mod tests { |
| 306 |
use super::*; |
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
const T: u64 = 4_000_000_000; |
| 311 |
|
| 312 |
fn at(secs: u64) -> SystemTime { |
| 313 |
SystemTime::UNIX_EPOCH + Duration::from_secs(secs) |
| 314 |
} |
| 315 |
|
| 316 |
|
| 317 |
fn file(root: &Path, rel: &str, kib: usize, secs: u64) -> PathBuf { |
| 318 |
let p = root.join(rel); |
| 319 |
std::fs::create_dir_all(p.parent().unwrap()).unwrap(); |
| 320 |
let bytes: Vec<u8> = (0..kib << 10).map(|i: usize| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); |
| 321 |
std::fs::write(&p, bytes).unwrap(); |
| 322 |
let f = std::fs::File::options().write(true).open(&p).unwrap(); |
| 323 |
f.set_times(std::fs::FileTimes::new().set_accessed(at(secs)).set_modified(at(secs))).unwrap(); |
| 324 |
p |
| 325 |
} |
| 326 |
|
| 327 |
fn bytes(p: &Path) -> u64 { |
| 328 |
std::fs::metadata(p).unwrap().blocks() * 512 |
| 329 |
} |
| 330 |
|
| 331 |
#[test] |
| 332 |
fn hashes_are_cargos_unit_hashes() { |
| 333 |
let h = |p: &str| hashes(Path::new(p)).collect::<Vec<_>>(); |
| 334 |
assert_eq!(h("debug/deps/libdep-8f2b19826c505967.rlib"), ["8f2b19826c505967"]); |
| 335 |
assert_eq!(h("debug/.fingerprint/dep-8f2b19826c505967/lib-dep"), ["8f2b19826c505967"]); |
| 336 |
assert_eq!(h("debug/build/my-crate-0123456789abcdef/out/x.o"), ["0123456789abcdef"]); |
| 337 |
assert!(h("debug/incremental/app-2dadnjnzlrswc/s-hndl5uwdpw-1uaho4m.lock").is_empty()); |
| 338 |
assert!(h("debug/app").is_empty() && h("debug/deps/x-0123456789ABCDEF").is_empty() && h("x-0123456789abcde").is_empty()); |
| 339 |
} |
| 340 |
|
| 341 |
#[test] |
| 342 |
fn under_the_cap_nothing_is_touched() { |
| 343 |
let dir = tempfile::tempdir().unwrap(); |
| 344 |
let old = file(dir.path(), "debug/deps/libold-1111111111111111.rlib", 64, 1_000); |
| 345 |
let p = prune(dir.path(), at(T), &[], 1 << 30, 64 << 10, 60).unwrap(); |
| 346 |
assert!(old.exists() && p.fits() && p.freed == 0 && p.after == p.before, "{p:?}"); |
| 347 |
} |
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
#[test] |
| 353 |
fn what_this_run_did_not_use_goes_oldest_first_and_its_units_stay_whole() { |
| 354 |
let dir = tempfile::tempdir().unwrap(); |
| 355 |
let root = dir.path(); |
| 356 |
let app = file(root, "debug/deps/app-aaaaaaaaaaaaaaaa", 256, T + 100); |
| 357 |
let app_fp = file(root, "debug/.fingerprint/app-aaaaaaaaaaaaaaaa/bin-app", 1, T + 100); |
| 358 |
let dep_rlib = file(root, "debug/deps/libdep-bbbbbbbbbbbbbbbb.rlib", 256, T - 5_000); |
| 359 |
let dep_fp = file(root, "debug/.fingerprint/dep-bbbbbbbbbbbbbbbb/lib-dep", 1, T - 5_000); |
| 360 |
std::fs::File::open(&dep_fp).unwrap().set_times(std::fs::FileTimes::new().set_accessed(at(T + 50))).unwrap(); |
| 361 |
let script = file(root, "debug/build/dep-bbbbbbbbbbbbbbbb/out/gen.rs", 64, T - 5_000); |
| 362 |
|
| 363 |
std::fs::hard_link(&app, root.join("debug/app")).unwrap(); |
| 364 |
|
| 365 |
let oldest = file(root, "debug/deps/libdep-cccccccccccccccc.rlib", 256, T - 9_000); |
| 366 |
let oldest_fp = file(root, "debug/.fingerprint/dep-cccccccccccccccc/lib-dep", 1, T - 8_999); |
| 367 |
let older = file(root, "debug/deps/libdep-dddddddddddddddd.rlib", 256, T - 8_000); |
| 368 |
|
| 369 |
let output = file(root, "release/tool", 128, T - 10_000); |
| 370 |
let all = [&app, &app_fp, &dep_rlib, &dep_fp, &script, &oldest, &oldest_fp, &older, &output]; |
| 371 |
let before: u64 = all.iter().map(|p| bytes(p)).sum(); |
| 372 |
|
| 373 |
let want = before - bytes(&oldest) - bytes(&oldest_fp); |
| 374 |
let size = (want * 100).div_ceil(60); |
| 375 |
let p = prune(root, at(T), &["/release/tool".into()], size, before, 60).unwrap(); |
| 376 |
assert!(p.fits(), "{p:?}"); |
| 377 |
assert!( |
| 378 |
!oldest.exists() && !root.join("debug/.fingerprint/dep-cccccccccccccccc").exists(), |
| 379 |
"the oldest unit went, its emptied directory too" |
| 380 |
); |
| 381 |
assert!(older.exists(), "and pruning stopped under the cap: {p:?}"); |
| 382 |
for kept in [&app, &app_fp, &dep_rlib, &dep_fp, &script, &output, &root.join("debug/app")] { |
| 383 |
assert!(kept.exists(), "{} stays", kept.display()); |
| 384 |
} |
| 385 |
assert_eq!((p.files, p.freed, p.after), (2, p.before - want, want)); |
| 386 |
|
| 387 |
let p = prune(root, at(T), &["release/tool".into()], 1, p.after, 60).unwrap(); |
| 388 |
assert!(!older.exists() && !p.fits() && p.files == 1, "{p:?}"); |
| 389 |
for kept in [&app, &dep_rlib, &dep_fp, &script, &output] { |
| 390 |
assert!(kept.exists(), "{} stays", kept.display()); |
| 391 |
} |
| 392 |
assert!(root.join("debug/deps").is_dir(), "a directory still holding files stays"); |
| 393 |
} |
| 394 |
|
| 395 |
#[test] |
| 396 |
fn reads_are_forgotten_so_the_next_is_seen() { |
| 397 |
let dir = tempfile::tempdir().unwrap(); |
| 398 |
let p = file(dir.path(), "a/b", 1, 5_000); |
| 399 |
std::os::unix::fs::symlink("/etc/passwd", dir.path().join("link")).unwrap(); |
| 400 |
assert_eq!(forget_reads(dir.path()).unwrap(), 1); |
| 401 |
let md = std::fs::metadata(&p).unwrap(); |
| 402 |
assert_eq!((md.atime(), md.mtime()), (0, 5_000), "the mtime is kept"); |
| 403 |
assert!(std::fs::symlink_metadata(dir.path().join("link")).unwrap().atime() > 0, "a link is not followed"); |
| 404 |
} |
| 405 |
} |