| 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 | | use anyhow::{Context, Result}; |
| 48 | | use flow_core::pipeline::Mount; |
| 49 | | use flow_init::prune::Pruned; |
| 50 | | use std::path::{Path, PathBuf}; |
| 51 | | use std::time::SystemTime; |
| 52 | |
|
| 53 | |
|
| 54 | | pub const DEFAULT_GB: u64 = 64; |
| 55 | |
|
| 56 | |
|
| 57 | |
|
| 58 | | pub type Sources = std::collections::BTreeMap<String, (String, i64)>; |
| 59 | |
|
| 60 | |
|
| 61 | | pub struct Taken { |
| 62 | | |
| 63 | | pub how: String, |
| 64 | | |
| 65 | | pub sources: Option<Sources>, |
| 66 | | } |
| 67 | |
|
| 68 | |
|
| 69 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 70 | | pub enum Form { |
| 71 | | |
| 72 | | Image, |
| 73 | | |
| 74 | | Dir, |
| 75 | | } |
| 76 | |
|
| 77 | | impl Form { |
| 78 | 44× | fn ext(self) -> &'static str { |
| 79 | 44× | match self { |
| 80 | 21× | Form::Image => "ext4", |
| 81 | 23× | Form::Dir => "tree", |
| 82 | | } |
| 83 | 44× | } |
| 84 | | } |
| 85 | |
|
| 86 | |
|
| 87 | 104× | fn form_of(p: &Path) -> Option<Form> { |
| 88 | 104× | match p.extension()?.to_str()? { |
| 89 | 104× | "ext4" => Some(Form::Image), |
| 90 | 68× | "tree" => Some(Form::Dir), |
| 91 | 27× | _ => None, |
| 92 | | } |
| 93 | 104× | } |
| 94 | |
|
| 95 | 48× | fn sources_of(disk: &Path) -> PathBuf { |
| 96 | 48× | match form_of(disk) { |
| 97 | 26× | Some(Form::Dir) => disk.with_extension("tree-sources"), |
| 98 | 22× | _ => disk.with_extension("sources"), |
| 99 | | } |
| 100 | 48× | } |
| 101 | |
|
| 102 | 16× | fn read_sources(disk: &Path) -> Option<Sources> { |
| 103 | 16× | serde_json::from_slice(&std::fs::read(sources_of(disk)).ok()?).ok() |
| 104 | 16× | } |
| 105 | |
|
| 106 | |
|
| 107 | |
|
| 108 | | pub struct Prune<'a> { |
| 109 | | |
| 110 | | |
| 111 | | pub started: SystemTime, |
| 112 | | |
| 113 | | pub percent: u8, |
| 114 | | |
| 115 | | pub guest: Option<&'a Pruned>, |
| 116 | | } |
| 117 | |
|
| 118 | |
|
| 119 | | pub struct Pool { |
| 120 | | root: PathBuf, |
| 121 | | limit: u64, |
| 122 | | } |
| 123 | |
|
| 124 | |
|
| 125 | |
|
| 126 | | pub struct Ctx<'a> { |
| 127 | | pub repo: &'a str, |
| 128 | | pub bookmark: &'a str, |
| 129 | | pub job: &'a str, |
| 130 | | pub image: &'a str, |
| 131 | | pub form: Form, |
| 132 | | } |
| 133 | |
|
| 134 | | use flow_core::api::segment; |
| 135 | |
|
| 136 | |
|
| 137 | |
|
| 138 | |
|
| 139 | | static CHANGING: std::sync::Mutex<()> = std::sync::Mutex::new(()); |
| 140 | |
|
| 141 | 44× | fn changing() -> std::sync::MutexGuard<'static, ()> { |
| 142 | 44× | CHANGING.lock().unwrap_or_else(|p| p.into_inner()) |
| 143 | 44× | } |
| 144 | |
|
| 145 | | impl Pool { |
| 146 | 6× | pub fn new(home_root: &Path, gb: Option<u64>) -> Pool { |
| 147 | 6× | Pool { root: home_root.join("cache"), limit: gb.unwrap_or(DEFAULT_GB).saturating_mul(1 << 30) } |
| 148 | 6× | } |
| 149 | |
|
| 150 | 45× | fn cache_dir(&self, ctx: &Ctx, name: &str) -> PathBuf { |
| 151 | 45× | self.root.join(segment(ctx.repo)).join(segment(ctx.job)).join(segment(name)) |
| 152 | 45× | } |
| 153 | |
|
| 154 | | |
| 155 | | |
| 156 | 9× | pub fn key(ctx: &Ctx, m: &Mount, hash_of: impl Fn(&str) -> Option<String>) -> String { |
| 157 | 9× | let mut h = blake3::Hasher::new(); |
| 158 | 27× | for part in [ctx.image, ctx.job, m.cache.as_deref().unwrap_or("")] { |
| 159 | 27× | h.update(part.as_bytes()); |
| 160 | 27× | h.update(b"\n"); |
| 161 | 27× | } |
| 162 | 14× | for k in &m.key { |
| 163 | 14× | h.update(k.as_bytes()); |
| 164 | 14× | h.update(b"="); |
| 165 | 14× | h.update(hash_of(k).unwrap_or_else(|| "absent".into()).as_bytes()); |
| 166 | 14× | h.update(b"\n"); |
| 167 | | } |
| 168 | 9× | h.finalize().to_hex()[..32].to_string() |
| 169 | 9× | } |
| 170 | |
|
| 171 | | |
| 172 | | |
| 173 | | |
| 174 | | |
| 175 | | |
| 176 | | |
| 177 | 27× | pub fn take(&self, ctx: &Ctx, m: &Mount, key: &str, dest: &Path) -> Option<Taken> { |
| 178 | 27× | let name = m.cache.as_deref()?; |
| 179 | 27× | let _changing = changing(); |
| 180 | 27× | let dir = self.cache_dir(ctx, name); |
| 181 | 27× | let size = m.size_mib as u64 * (1 << 20); |
| 182 | 27× | let form = ctx.form; |
| 183 | 34× | let fits = |p: &Path| match form { |
| 184 | 17× | Form::Image => std::fs::metadata(p).is_ok_and(|md| md.len() == size), |
| 185 | 17× | Form::Dir => std::fs::symlink_metadata(p).is_ok_and(|md| md.is_dir()), |
| 186 | 34× | }; |
| 187 | 27× | let ext = form.ext(); |
| 188 | 27× | let mine = dir.join(segment(ctx.bookmark)); |
| 189 | 27× | let exact = mine.join(format!("{key}.{ext}")); |
| 190 | | |
| 191 | 27× | if fits(&exact) { |
| 192 | 11× | let sources = read_sources(&exact); |
| 193 | 11× | if std::fs::rename(&exact, dest).is_ok() { |
| 194 | 11× | let _ = std::fs::remove_file(sources_of(&exact)); |
| 195 | 11× | return Some(Taken { how: format!("cache {name}: this bookmark's, same key"), sources }); |
| 196 | 0× | } |
| 197 | 16× | } |
| 198 | 16× | if let Some(p) = newest(&mine, form, |p| fits(p)) { |
| 199 | 2× | let sources = read_sources(&p); |
| 200 | 2× | if std::fs::rename(&p, dest).is_ok() { |
| 201 | 2× | let _ = std::fs::remove_file(sources_of(&p)); |
| 202 | 2× | return Some(Taken { how: format!("cache {name}: this bookmark's, an older key"), sources }); |
| 203 | 0× | } |
| 204 | 14× | } |
| 205 | 14× | let others: Vec<PathBuf> = |
| 206 | 14× | std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir() && *p != mine).collect(); |
| 207 | 14× | let pick = others |
| 208 | 14× | .iter() |
| 209 | 14× | .map(|d| d.join(format!("{key}.{ext}"))) |
| 210 | 14× | .filter(|p| fits(p)) |
| 211 | 14× | .max_by_key(|p| modified(p)) |
| 212 | 14× | .map(|p| (p, "same key")) |
| 213 | 14× | .or_else(|| { |
| 214 | 11× | others.iter().filter_map(|d| newest(d, form, |p| fits(p))).max_by_key(|p| modified(p)).map(|p| (p, "an older key")) |
| 215 | 11× | }); |
| 216 | 14× | if let Some((p, which)) = pick { |
| 217 | 3× | let from = p.parent().and_then(|d| d.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); |
| 218 | 3× | if copy(form, &p, dest).is_ok() { |
| 219 | 3× | return Some(Taken { |
| 220 | 3× | how: format!("cache {name}: copied from another bookmark's ({from}), {which}"), |
| 221 | 3× | sources: read_sources(&p), |
| 222 | 3× | }); |
| 223 | 0× | } |
| 224 | 11× | } |
| 225 | 11× | None |
| 226 | 27× | } |
| 227 | |
|
| 228 | | |
| 229 | | |
| 230 | 17× | pub fn keep(&self, ctx: &Ctx, m: &Mount, key: &str, disk: &Path, sources: &Sources) -> Result<()> { |
| 231 | 17× | let Some(name) = m.cache.as_deref() else { return Ok(()) }; |
| 232 | 17× | let _changing = changing(); |
| 233 | | |
| 234 | | |
| 235 | 17× | if ctx.form == Form::Dir { |
| 236 | 9× | seal(disk).with_context(|| format!("seal {}", disk.display()))?; |
| 237 | 8× | } |
| 238 | 17× | let mine = self.cache_dir(ctx, name).join(segment(ctx.bookmark)); |
| 239 | 17× | crate::portable::create_private_dir(&mine)?; |
| 240 | 17× | crate::portable::set_mode(&self.root, 0o700)?; |
| 241 | 17× | let dest = mine.join(format!("{key}.{}", ctx.form.ext())); |
| 242 | 17× | if ctx.form == Form::Dir { |
| 243 | | |
| 244 | 9× | crate::workspace::remove_tree(&dest)?; |
| 245 | 8× | } |
| 246 | 17× | if std::fs::rename(disk, &dest).is_err() { |
| 247 | 0× | copy(ctx.form, disk, &dest).with_context(|| format!("keep {}", disk.display()))?; |
| 248 | 17× | } |
| 249 | | |
| 250 | 17× | std::fs::File::open(&dest)?.set_modified(SystemTime::now())?; |
| 251 | 17× | let sidecar = sources_of(&dest); |
| 252 | 17× | let tmp = sidecar.with_extension("sources-part"); |
| 253 | 17× | let _ = std::fs::remove_file(&tmp); |
| 254 | | { |
| 255 | | use std::io::Write; |
| 256 | 17× | crate::portable::private(std::fs::OpenOptions::new().write(true).create_new(true)) |
| 257 | 17× | .open(&tmp)? |
| 258 | 17× | .write_all(&serde_json::to_vec(sources)?)?; |
| 259 | | } |
| 260 | 17× | std::fs::rename(&tmp, sidecar)?; |
| 261 | | |
| 262 | | |
| 263 | 17× | self.evict(); |
| 264 | 17× | Ok(()) |
| 265 | 17× | } |
| 266 | |
|
| 267 | | |
| 268 | | |
| 269 | | |
| 270 | | |
| 271 | | #[allow(clippy::too_many_arguments)] |
| 272 | 13× | pub fn settle( |
| 273 | 13× | &self, |
| 274 | 13× | ctx: &Ctx, |
| 275 | 13× | m: &Mount, |
| 276 | 13× | key: &str, |
| 277 | 13× | disk: &Path, |
| 278 | 13× | sources: &Sources, |
| 279 | 13× | passed: bool, |
| 280 | 13× | prune: &Prune, |
| 281 | 13× | ) -> Result<Option<String>> { |
| 282 | 13× | if passed { |
| 283 | 11× | let Some(name) = m.cache.as_deref() else { return Ok(None) }; |
| 284 | 11× | let pruned = pruned(ctx.form, m, disk, prune)?; |
| 285 | 11× | let line = describe(name, &pruned); |
| 286 | 11× | if pruned.fits() { |
| 287 | 8× | self.keep(ctx, m, key, disk, sources)?; |
| 288 | | } else { |
| 289 | 3× | discard(ctx.form, disk)?; |
| 290 | | } |
| 291 | 11× | return Ok(Some(line)); |
| 292 | 2× | } |
| 293 | 2× | discard(ctx.form, disk)?; |
| 294 | 2× | Ok(None) |
| 295 | 13× | } |
| 296 | |
|
| 297 | | |
| 298 | | |
| 299 | | |
| 300 | | |
| 301 | | |
| 302 | | |
| 303 | 6× | pub fn slot_times(&self) -> std::collections::BTreeMap<String, u64> { |
| 304 | 6× | let mut out = std::collections::BTreeMap::new(); |
| 305 | 6× | for repo in std::fs::read_dir(&self.root).into_iter().flatten().flatten() { |
| 306 | 6× | for job in std::fs::read_dir(repo.path()).into_iter().flatten().flatten() { |
| 307 | 6× | let mut newest: Option<SystemTime> = None; |
| 308 | | |
| 309 | 6× | kept(&job.path(), 2, &mut |p, _| { |
| 310 | 3× | let t = modified(p); |
| 311 | 3× | newest = Some(newest.map_or(t, |n| n.max(t))); |
| 312 | 3× | }); |
| 313 | 6× | if let Some(t) = newest { |
| 314 | 3× | let ms = t.duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0); |
| 315 | 3× | out.insert(format!("{}/{}", repo.file_name().to_string_lossy(), job.file_name().to_string_lossy()), ms); |
| 316 | 3× | } |
| 317 | | } |
| 318 | | } |
| 319 | 6× | out |
| 320 | 6× | } |
| 321 | |
|
| 322 | | |
| 323 | | |
| 324 | | |
| 325 | 17× | fn evict(&self) -> u64 { |
| 326 | 17× | let mut disks: Vec<(SystemTime, u64, PathBuf)> = Vec::new(); |
| 327 | | |
| 328 | 19× | kept(&self.root, 4, &mut |p, form| { |
| 329 | 19× | if let Ok(md) = std::fs::symlink_metadata(p) { |
| 330 | 19× | let bytes = match form { |
| 331 | 8× | Form::Image => crate::portable::disk_bytes(&md), |
| 332 | 11× | Form::Dir => tree_bytes(p), |
| 333 | | }; |
| 334 | 19× | disks.push((md.modified().unwrap_or(SystemTime::UNIX_EPOCH), bytes, p.to_path_buf())); |
| 335 | 0× | } |
| 336 | 19× | }); |
| 337 | 17× | let mut total: u64 = disks.iter().map(|d| d.1).sum(); |
| 338 | 17× | disks.sort(); |
| 339 | 17× | let mut freed = 0; |
| 340 | 18× | for (_, bytes, p) in disks { |
| 341 | 18× | if total <= self.limit { |
| 342 | 16× | break; |
| 343 | 2× | } |
| 344 | 2× | let gone = match form_of(&p) { |
| 345 | 1× | Some(Form::Dir) => crate::workspace::remove_tree(&p), |
| 346 | 1× | _ => std::fs::remove_file(&p), |
| 347 | | }; |
| 348 | 2× | if gone.is_ok() { |
| 349 | 2× | let _ = std::fs::remove_file(sources_of(&p)); |
| 350 | 2× | total -= bytes; |
| 351 | 2× | freed += bytes; |
| 352 | 2× | } |
| 353 | | } |
| 354 | 17× | freed |
| 355 | 17× | } |
| 356 | | } |
| 357 | |
|
| 358 | |
|
| 359 | 5× | fn discard(form: Form, disk: &Path) -> Result<()> { |
| 360 | 5× | let gone = match form { |
| 361 | 2× | Form::Dir => crate::workspace::remove_tree(disk), |
| 362 | 3× | Form::Image => std::fs::remove_file(disk).or_else(|e| if e.kind() == std::io::ErrorKind::NotFound { Ok(()) } else { Err(e) }), |
| 363 | | }; |
| 364 | 5× | gone.with_context(|| format!("discard {}", disk.display())) |
| 365 | 5× | } |
| 366 | |
|
| 367 | |
|
| 368 | |
|
| 369 | |
|
| 370 | |
|
| 371 | |
|
| 372 | 1× | pub fn forget_reads(form: Form, disk: &Path) -> Result<()> { |
| 373 | 1× | if form == Form::Dir && disk.is_dir() { |
| 374 | 1× | flow_init::prune::forget_reads(disk).with_context(|| format!("set the atimes in {}", disk.display()))?; |
| 375 | 0× | } |
| 376 | 1× | Ok(()) |
| 377 | 1× | } |
| 378 | |
|
| 379 | |
|
| 380 | |
|
| 381 | 11× | fn pruned(form: Form, m: &Mount, disk: &Path, prune: &Prune) -> Result<Pruned> { |
| 382 | 11× | let size = m.size_mib as u64 * (1 << 20); |
| 383 | 11× | let percent = prune.percent; |
| 384 | 11× | let unpruned = |before: u64, why: String| Pruned { size, percent, before, after: before, unpruned: Some(why), ..Pruned::default() }; |
| 385 | 11× | Ok(match form { |
| 386 | | Form::Dir => { |
| 387 | 7× | let before = tree_bytes(disk); |
| 388 | 7× | if !flow_init::prune::records_reads(disk) { |
| 389 | 0× | unpruned(before, "this runner's file system records no reads (noatime), so what the job used cannot be told".into()) |
| 390 | | } else { |
| 391 | 7× | flow_init::prune::prune(disk, prune.started, &[], size, before, percent) |
| 392 | 7× | .unwrap_or_else(|e| unpruned(tree_bytes(disk), format!("pruning failed: {e}"))) |
| 393 | | } |
| 394 | | } |
| 395 | 4× | Form::Image => match prune.guest.filter(|g| g.size > 0) { |
| 396 | 2× | Some(g) => g.clone(), |
| 397 | | None => { |
| 398 | 2× | let (before, size) = image_usage(disk)?; |
| 399 | 2× | let why = prune.guest.and_then(|g| g.unpruned.clone()).unwrap_or_else(|| "the guest did not prune it".into()); |
| 400 | 2× | Pruned { size, ..unpruned(before, why) } |
| 401 | | } |
| 402 | | }, |
| 403 | | }) |
| 404 | 11× | } |
| 405 | |
|
| 406 | |
|
| 407 | 2× | fn image_usage(image: &Path) -> Result<(u64, u64)> { |
| 408 | 2× | let out = std::process::Command::new("dumpe2fs").arg("-h").arg(image).output().context("run dumpe2fs (e2fsprogs)")?; |
| 409 | 2× | if !out.status.success() { |
| 410 | 0× | anyhow::bail!("dumpe2fs {}: {}", image.display(), String::from_utf8_lossy(&out.stderr).trim()); |
| 411 | 2× | } |
| 412 | 2× | superblock_usage(&String::from_utf8_lossy(&out.stdout)).with_context(|| format!("dumpe2fs {}: no block counts", image.display())) |
| 413 | 2× | } |
| 414 | |
|
| 415 | 4× | fn superblock_usage(header: &str) -> Option<(u64, u64)> { |
| 416 | 11× | let field = |name: &str| -> Option<u64> { |
| 417 | 107× | header.lines().find_map(|l| l.strip_prefix(name)?.strip_prefix(':')).and_then(|v| v.trim().parse().ok()) |
| 418 | 11× | }; |
| 419 | 4× | let (count, free, block) = (field("Block count")?, field("Free blocks")?, field("Block size")?); |
| 420 | 3× | Some((count.saturating_sub(free) * block, count * block)) |
| 421 | 4× | } |
| 422 | |
|
| 423 | |
|
| 424 | |
|
| 425 | 11× | pub fn describe(name: &str, p: &Pruned) -> String { |
| 426 | | use crate::images::human; |
| 427 | 11× | let cap = format!("{}% of its {} disk", p.percent, human(p.size)); |
| 428 | 11× | let pruned = format!("{} in {} file{} this run did not use", human(p.freed), p.files, if p.files == 1 { "" } else { "s" }); |
| 429 | 11× | if p.fits() && p.files > 0 { |
| 430 | 2× | format!("cache {name}: kept {} of {} (pruned {pruned}; the cap is {cap})", human(p.after), human(p.before)) |
| 431 | 9× | } else if p.fits() { |
| 432 | 6× | format!("cache {name}: kept {}, under its cap of {cap}", human(p.after)) |
| 433 | | } else { |
| 434 | 3× | let after = if p.files > 0 { format!("{} after pruning {pruned}", human(p.after)) } else { human(p.after) }; |
| 435 | 3× | let why = p.unpruned.as_ref().map(|u| format!(" ({u})")).unwrap_or_default(); |
| 436 | 3× | format!( |
| 437 | | "cache {name}: not kept: {after} is over its cap of {} ({cap}){why}; the next run starts empty, and a larger `size` on the mount gives the cache room", |
| 438 | 3× | human(p.cap()) |
| 439 | | ) |
| 440 | | } |
| 441 | 11× | } |
| 442 | |
|
| 443 | |
|
| 444 | |
|
| 445 | |
|
| 446 | 0× | pub fn disk_path(form: Form, scratch: &Path, n: usize) -> PathBuf { |
| 447 | 0× | match form { |
| 448 | 0× | Form::Image => scratch.join(format!("mount-{n}.ext4")), |
| 449 | 0× | Form::Dir => crate::syscall::disk_dir(scratch, n), |
| 450 | | } |
| 451 | 0× | } |
| 452 | |
|
| 453 | 13× | fn modified(p: &Path) -> SystemTime { |
| 454 | 13× | std::fs::symlink_metadata(p).and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH) |
| 455 | 13× | } |
| 456 | |
|
| 457 | 17× | fn newest(dir: &Path, form: Form, ok: impl Fn(&Path) -> bool) -> Option<PathBuf> { |
| 458 | 17× | std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| form_of(p) == Some(form) && ok(p)).max_by_key(|p| modified(p)) |
| 459 | 17× | } |
| 460 | |
|
| 461 | |
|
| 462 | |
|
| 463 | 104× | fn kept(dir: &Path, depth: usize, f: &mut dyn FnMut(&Path, Form)) { |
| 464 | 125× | for e in std::fs::read_dir(dir).into_iter().flatten().flatten() { |
| 465 | 125× | let p = e.path(); |
| 466 | 125× | let Ok(t) = e.file_type() else { continue }; |
| 467 | 125× | if depth == 0 { |
| 468 | 44× | match form_of(&p) { |
| 469 | 10× | Some(Form::Image) if t.is_file() => f(&p, Form::Image), |
| 470 | 12× | Some(Form::Dir) if t.is_dir() => f(&p, Form::Dir), |
| 471 | 22× | _ => {} |
| 472 | | } |
| 473 | 81× | } else if t.is_dir() { |
| 474 | 81× | kept(&p, depth - 1, f); |
| 475 | 81× | } |
| 476 | | } |
| 477 | 104× | } |
| 478 | |
|
| 479 | |
|
| 480 | |
|
| 481 | 19× | fn tree_bytes(dir: &Path) -> u64 { |
| 482 | 91× | fn walk(p: &Path, seen: &mut std::collections::HashSet<(u64, u64)>) -> u64 { |
| 483 | 91× | let Ok(md) = std::fs::symlink_metadata(p) else { return 0 }; |
| 484 | 91× | if crate::portable::shared_identity(&md).is_some_and(|id| !seen.insert(id)) { |
| 485 | 0× | return 0; |
| 486 | 91× | } |
| 487 | 91× | let mut bytes = crate::portable::disk_bytes(&md); |
| 488 | 91× | if md.is_dir() { |
| 489 | 72× | for e in std::fs::read_dir(p).into_iter().flatten().flatten() { |
| 490 | 72× | bytes += walk(&e.path(), seen); |
| 491 | 72× | } |
| 492 | 50× | } |
| 493 | 91× | bytes |
| 494 | 91× | } |
| 495 | 19× | walk(dir, &mut Default::default()) |
| 496 | 19× | } |
| 497 | |
|
| 498 | |
|
| 499 | |
|
| 500 | |
|
| 501 | |
|
| 502 | |
|
| 503 | 44× | fn seal(p: &Path) -> std::io::Result<()> { |
| 504 | 44× | let md = std::fs::symlink_metadata(p)?; |
| 505 | 44× | if md.file_type().is_symlink() { |
| 506 | 1× | return Ok(()); |
| 507 | 43× | } |
| 508 | 43× | let mode = crate::portable::mode(&md); |
| 509 | 43× | let want = (mode & !0o7022) | if md.is_dir() { 0o700 } else { 0o400 }; |
| 510 | 43× | if want != mode { |
| 511 | 5× | crate::portable::set_mode(p, want)?; |
| 512 | 38× | } |
| 513 | 43× | if md.is_dir() { |
| 514 | 35× | for e in std::fs::read_dir(p)? { |
| 515 | 35× | seal(&e?.path())?; |
| 516 | | } |
| 517 | 24× | } |
| 518 | 43× | Ok(()) |
| 519 | 44× | } |
| 520 | |
|
| 521 | 3× | fn copy(form: Form, from: &Path, to: &Path) -> Result<()> { |
| 522 | 3× | match form { |
| 523 | 1× | Form::Image => sparse_copy(from, to), |
| 524 | 2× | Form::Dir => tree_copy(from, to), |
| 525 | | } |
| 526 | 3× | } |
| 527 | |
|
| 528 | |
|
| 529 | 1× | fn sparse_copy(from: &Path, to: &Path) -> Result<()> { |
| 530 | 1× | let tmp = to.with_extension("part"); |
| 531 | 1× | let st = std::process::Command::new("cp").arg("--sparse=always").arg(from).arg(&tmp).status().context("run cp")?; |
| 532 | 1× | if !st.success() { |
| 533 | 0× | let _ = std::fs::remove_file(&tmp); |
| 534 | 0× | anyhow::bail!("cp {} failed", from.display()); |
| 535 | 1× | } |
| 536 | 1× | std::fs::rename(&tmp, to)?; |
| 537 | 1× | Ok(()) |
| 538 | 1× | } |
| 539 | |
|
| 540 | |
|
| 541 | |
|
| 542 | 2× | fn tree_copy(from: &Path, to: &Path) -> Result<()> { |
| 543 | 2× | let tmp = to.with_extension("tree-part"); |
| 544 | 2× | crate::workspace::remove_tree(&tmp)?; |
| 545 | 2× | let st = std::process::Command::new("cp") |
| 546 | 2× | .args(["-a", "--reflink=auto", "--no-target-directory"]) |
| 547 | 2× | .arg(from) |
| 548 | 2× | .arg(&tmp) |
| 549 | 2× | .status() |
| 550 | 2× | .context("run cp")?; |
| 551 | 2× | if !st.success() { |
| 552 | 0× | let _ = crate::workspace::remove_tree(&tmp); |
| 553 | 0× | anyhow::bail!("cp {} failed", from.display()); |
| 554 | 2× | } |
| 555 | 2× | std::fs::rename(&tmp, to).inspect_err(|_| { |
| 556 | 0× | let _ = crate::workspace::remove_tree(&tmp); |
| 557 | 0× | })?; |
| 558 | 2× | Ok(()) |
| 559 | 2× | } |
| 560 | |
|
| 561 | | #[cfg(all(test, unix))] |
| 562 | | mod tests { |
| 563 | | use super::*; |
| 564 | | use flow_core::pipeline::MountSource; |
| 565 | | use std::os::unix::fs::{MetadataExt, PermissionsExt}; |
| 566 | |
|
| 567 | | |
| 568 | 11× | fn keep_all() -> Prune<'static> { |
| 569 | 11× | Prune { started: SystemTime::now(), percent: 100, guest: None } |
| 570 | 11× | } |
| 571 | |
|
| 572 | 10× | fn mount(key: &[&str]) -> Mount { |
| 573 | | Mount { |
| 574 | 10× | source: MountSource::Disk, |
| 575 | 10× | target: "/src/target".into(), |
| 576 | | size_mib: 1, |
| 577 | 10× | cache: Some("target".into()), |
| 578 | 10× | key: key.iter().map(|s| s.to_string()).collect(), |
| 579 | | } |
| 580 | 10× | } |
| 581 | |
|
| 582 | 5× | fn disk(path: &Path, fill: &[u8]) { |
| 583 | 5× | let f = std::fs::File::create(path).unwrap(); |
| 584 | 5× | f.set_len(1 << 20).unwrap(); |
| 585 | 5× | std::os::unix::fs::FileExt::write_at(&f, fill, 0).unwrap(); |
| 586 | 5× | } |
| 587 | |
|
| 588 | 2× | fn first(path: &Path) -> Vec<u8> { |
| 589 | 2× | std::fs::read(path).unwrap()[..4].to_vec() |
| 590 | 2× | } |
| 591 | |
|
| 592 | | #[test] |
| 593 | 1× | fn a_kept_disk_starts_the_next_job_of_its_bookmark_then_others_copy_it() { |
| 594 | 1× | let home = tempfile::tempdir().unwrap(); |
| 595 | 1× | let work = tempfile::tempdir().unwrap(); |
| 596 | 1× | let pool = Pool::new(home.path(), None); |
| 597 | 1× | let m = mount(&["Cargo.lock"]); |
| 598 | 1× | let main = Ctx { repo: "andy/hub", bookmark: "main", job: "test", image: "img", form: Form::Image }; |
| 599 | 1× | let key = Pool::key(&main, &m, |_| Some("lock-1".into())); |
| 600 | | |
| 601 | 1× | assert!(pool.take(&main, &m, &key, &work.path().join("a.ext4")).is_none()); |
| 602 | | |
| 603 | 1× | disk(&work.path().join("a.ext4"), b"MAIN"); |
| 604 | 1× | let built: Sources = [("src/lib.rs".to_string(), ("h1".to_string(), 1_000))].into(); |
| 605 | 1× | pool.keep(&main, &m, &key, &work.path().join("a.ext4"), &built).unwrap(); |
| 606 | 1× | assert!(!work.path().join("a.ext4").exists(), "moved, not copied"); |
| 607 | 1× | let taken = pool.take(&main, &m, &key, &work.path().join("b.ext4")).unwrap(); |
| 608 | 1× | assert!(taken.how.contains("same key"), "{}", taken.how); |
| 609 | 1× | assert_eq!(taken.sources.as_ref(), Some(&built), "its sources come with it (#52)"); |
| 610 | 1× | assert_eq!(first(&work.path().join("b.ext4")), b"MAIN"); |
| 611 | 1× | pool.keep(&main, &m, &key, &work.path().join("b.ext4"), &built).unwrap(); |
| 612 | | |
| 613 | 1× | let key2 = Pool::key(&main, &m, |_| Some("lock-2".into())); |
| 614 | 1× | assert_ne!(key, key2); |
| 615 | 1× | let taken = pool.take(&main, &m, &key2, &work.path().join("c.ext4")).unwrap(); |
| 616 | 1× | assert!(taken.how.contains("older key"), "{}", taken.how); |
| 617 | 1× | assert_eq!(taken.sources.as_ref(), Some(&built)); |
| 618 | 1× | pool.keep(&main, &m, &key2, &work.path().join("c.ext4"), &built).unwrap(); |
| 619 | 1× | assert_eq!( |
| 620 | 1× | pool.slot_times().into_keys().collect::<Vec<_>>(), |
| 621 | 1× | vec![flow_core::api::cache_slot("andy/hub", "test")], |
| 622 | | "what the claim reports (#51)" |
| 623 | | ); |
| 624 | | |
| 625 | 1× | let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis() as u64; |
| 626 | 1× | let kept = pool.slot_times()[&flow_core::api::cache_slot("andy/hub", "test")]; |
| 627 | 1× | assert!(now.abs_diff(kept) < 60_000, "kept {kept}, now {now}"); |
| 628 | | |
| 629 | 1× | let feature = Ctx { bookmark: "feature", ..main }; |
| 630 | 1× | let taken = pool.take(&feature, &m, &key2, &work.path().join("d.ext4")).unwrap(); |
| 631 | 1× | assert!(taken.how.contains("copied from another bookmark"), "{}", taken.how); |
| 632 | 1× | assert_eq!(taken.sources.as_ref(), Some(&built), "a copy reads them and leaves them"); |
| 633 | 1× | assert_eq!(first(&work.path().join("d.ext4")), b"MAIN"); |
| 634 | 1× | let taken = pool.take(&main, &m, &key2, &work.path().join("e.ext4")).unwrap(); |
| 635 | 1× | assert!(taken.how.contains("this bookmark's") && taken.sources.is_some(), "main's is still there, with its sources"); |
| 636 | | |
| 637 | 1× | let other_job = Ctx { job: "build", ..main }; |
| 638 | 1× | assert!(pool.take(&other_job, &m, &key2, &work.path().join("f.ext4")).is_none()); |
| 639 | 1× | let mut bigger = mount(&["Cargo.lock"]); |
| 640 | 1× | bigger.size_mib = 2; |
| 641 | 1× | assert!(pool.take(&feature, &bigger, &key2, &work.path().join("g.ext4")).is_none()); |
| 642 | 1× | } |
| 643 | |
|
| 644 | | #[test] |
| 645 | 1× | fn the_key_follows_the_image_the_job_and_the_key_files() { |
| 646 | 1× | let ctx = Ctx { repo: "r", bookmark: "main", job: "test", image: "img-1", form: Form::Image }; |
| 647 | 1× | let m = mount(&["Cargo.lock", "rust-toolchain.toml"]); |
| 648 | 2× | let k = Pool::key(&ctx, &m, |p| Some(format!("{p}-v1"))); |
| 649 | 2× | assert_eq!(k, Pool::key(&ctx, &m, |p| Some(format!("{p}-v1")))); |
| 650 | 2× | assert_ne!(k, Pool::key(&ctx, &m, |p| Some(format!("{p}-v2"))), "a key file changed"); |
| 651 | 2× | assert_ne!(k, Pool::key(&Ctx { image: "img-2", ..ctx }, &m, |p| Some(format!("{p}-v1"))), "another image"); |
| 652 | 1× | assert_ne!(k, Pool::key(&ctx, &m, |_| None), "a key file missing"); |
| 653 | 1× | } |
| 654 | |
|
| 655 | | #[test] |
| 656 | 1× | fn the_pool_drops_the_disks_used_longest_ago() { |
| 657 | 1× | let home = tempfile::tempdir().unwrap(); |
| 658 | 1× | let work = tempfile::tempdir().unwrap(); |
| 659 | 1× | let pool = Pool { root: home.path().join("cache"), limit: 0 }; |
| 660 | 1× | let m = mount(&[]); |
| 661 | 1× | let ctx = Ctx { repo: "r", bookmark: "main", job: "j", image: "i", form: Form::Image }; |
| 662 | 2× | let full = |p: &Path| { |
| 663 | 2× | let f = std::fs::File::create(p).unwrap(); |
| 664 | 2× | std::os::unix::fs::FileExt::write_at(&f, &vec![7u8; 1 << 20], 0).unwrap(); |
| 665 | 2× | }; |
| 666 | 1× | full(&work.path().join("a.ext4")); |
| 667 | | |
| 668 | 1× | pool.keep(&ctx, &m, "k1", &work.path().join("a.ext4"), &Sources::new()).unwrap(); |
| 669 | 1× | assert!(pool.take(&ctx, &m, "k1", &work.path().join("b.ext4")).is_none()); |
| 670 | 1× | let roomy = Pool { root: home.path().join("cache"), limit: 1 << 30 }; |
| 671 | 1× | full(&work.path().join("c.ext4")); |
| 672 | 1× | roomy.keep(&ctx, &m, "k2", &work.path().join("c.ext4"), &Sources::new()).unwrap(); |
| 673 | 1× | assert!(roomy.take(&ctx, &m, "k2", &work.path().join("d.ext4")).is_some(), "under the limit it stays"); |
| 674 | 1× | } |
| 675 | |
|
| 676 | | |
| 677 | | |
| 678 | 5× | fn tree(path: &Path, marker: &[u8], kib: usize) { |
| 679 | 5× | std::fs::create_dir_all(path.join("debug")).unwrap(); |
| 680 | 5× | std::fs::write(path.join("debug/marker"), marker).unwrap(); |
| 681 | | |
| 682 | 1054720× | let bytes: Vec<u8> = (0..kib << 10).map(|i: usize| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); |
| 683 | 5× | std::fs::write(path.join("debug/blob"), bytes).unwrap(); |
| 684 | 5× | } |
| 685 | |
|
| 686 | 7× | fn dir_ctx<'a>(bookmark: &'a str) -> Ctx<'a> { |
| 687 | 7× | Ctx { repo: "andy/flow", bookmark, job: "test", image: "img", form: Form::Dir } |
| 688 | 7× | } |
| 689 | |
|
| 690 | | |
| 691 | | |
| 692 | | #[test] |
| 693 | 1× | fn a_kept_directory_starts_the_next_syscall_job_and_others_copy_it() { |
| 694 | 1× | let home = tempfile::tempdir().unwrap(); |
| 695 | 1× | let work = tempfile::tempdir().unwrap(); |
| 696 | 1× | let pool = Pool::new(home.path(), None); |
| 697 | 1× | let m = mount(&["Cargo.lock"]); |
| 698 | 1× | let main = dir_ctx("main"); |
| 699 | 1× | let key = Pool::key(&main, &m, |_| Some("lock-1".into())); |
| 700 | 29× | let w = |n: &str| work.path().join(n); |
| 701 | 1× | assert!(pool.take(&main, &m, &key, &w("a")).is_none(), "nothing kept yet"); |
| 702 | | |
| 703 | 1× | tree(&w("a"), b"FIRST", 4); |
| 704 | | |
| 705 | 1× | std::fs::write(w("a/debug/inner.ext4"), b"not a disk").unwrap(); |
| 706 | 1× | let old = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000); |
| 707 | 1× | std::fs::File::open(w("a/debug/marker")).unwrap().set_modified(old).unwrap(); |
| 708 | 1× | let built: Sources = [("src/lib.rs".to_string(), ("h1".to_string(), 1_000))].into(); |
| 709 | 1× | pool.settle(&main, &m, &key, &w("a"), &built, true, &keep_all()).unwrap(); |
| 710 | 1× | assert!(!w("a").exists(), "moved, not copied"); |
| 711 | 1× | assert_eq!( |
| 712 | 1× | pool.slot_times().into_keys().collect::<Vec<_>>(), |
| 713 | 1× | vec![flow_core::api::cache_slot("andy/flow", "test")], |
| 714 | | "the claim reports it like an image (#51)" |
| 715 | | ); |
| 716 | | |
| 717 | | |
| 718 | 1× | let taken = pool.take(&main, &m, &key, &w("b")).unwrap(); |
| 719 | 1× | assert!(taken.how.contains("this bookmark's, same key"), "{}", taken.how); |
| 720 | 1× | assert_eq!(taken.sources.as_ref(), Some(&built), "its sources come with it (#52)"); |
| 721 | 1× | assert_eq!(std::fs::read(w("b/debug/marker")).unwrap(), b"FIRST"); |
| 722 | 1× | assert_eq!(modified(&w("b/debug/marker")), old, "its files keep their times"); |
| 723 | 1× | assert_eq!(std::fs::read(w("b/debug/inner.ext4")).unwrap(), b"not a disk"); |
| 724 | 1× | assert!(pool.take(&main, &m, &key, &w("c")).is_none(), "taken once"); |
| 725 | 1× | assert!(pool.slot_times().is_empty()); |
| 726 | | |
| 727 | 1× | std::fs::write(w("b/debug/marker"), b"SECOND").unwrap(); |
| 728 | 1× | pool.settle(&main, &m, &key, &w("b"), &built, true, &keep_all()).unwrap(); |
| 729 | 1× | let key2 = Pool::key(&main, &m, |_| Some("lock-2".into())); |
| 730 | 1× | let taken = pool.take(&main, &m, &key2, &w("d")).unwrap(); |
| 731 | 1× | assert!(taken.how.contains("older key"), "{}", taken.how); |
| 732 | 1× | assert_eq!(std::fs::read(w("d/debug/marker")).unwrap(), b"SECOND"); |
| 733 | 1× | pool.settle(&main, &m, &key2, &w("d"), &built, true, &keep_all()).unwrap(); |
| 734 | | |
| 735 | 1× | let feature = dir_ctx("feature"); |
| 736 | 1× | let taken = pool.take(&feature, &m, &key2, &w("e")).unwrap(); |
| 737 | 1× | assert!(taken.how.contains("copied from another bookmark's (main-"), "{}", taken.how); |
| 738 | 1× | assert_eq!(taken.sources.as_ref(), Some(&built)); |
| 739 | 1× | assert_eq!(std::fs::read(w("e/debug/marker")).unwrap(), b"SECOND"); |
| 740 | 1× | assert!(pool.take(&main, &m, &key2, &w("f")).is_some(), "main's is still there"); |
| 741 | 1× | assert_eq!(modified(&w("e/debug/marker")), modified(&w("f/debug/marker")), "a copy keeps the times"); |
| 742 | 1× | pool.settle(&main, &m, &key2, &w("f"), &built, true, &keep_all()).unwrap(); |
| 743 | | |
| 744 | | |
| 745 | 1× | let image = Ctx { form: Form::Image, ..main }; |
| 746 | 1× | assert!(pool.take(&image, &m, &key2, &w("g.ext4")).is_none()); |
| 747 | 1× | disk(&w("h.ext4"), b"DISK"); |
| 748 | 1× | pool.keep(&image, &m, &key2, &w("h.ext4"), &built).unwrap(); |
| 749 | 1× | let taken = pool.take(&main, &m, &key2, &w("i")).unwrap(); |
| 750 | 1× | assert!(w("i/debug/marker").is_file(), "{}", taken.how); |
| 751 | 1× | assert!(pool.take(&main, &m, &key2, &w("j")).is_none(), "the image is not a directory"); |
| 752 | 1× | assert!(pool.take(&image, &m, &key2, &w("k.ext4")).is_some(), "and is still there for a microVM"); |
| 753 | 1× | } |
| 754 | |
|
| 755 | | #[test] |
| 756 | 1× | fn a_failing_jobs_directory_is_thrown_away() { |
| 757 | 1× | let home = tempfile::tempdir().unwrap(); |
| 758 | 1× | let work = tempfile::tempdir().unwrap(); |
| 759 | 1× | let pool = Pool::new(home.path(), None); |
| 760 | 1× | let m = mount(&[]); |
| 761 | 1× | let main = dir_ctx("main"); |
| 762 | 1× | tree(&work.path().join("a"), b"GOOD", 1); |
| 763 | 1× | pool.settle(&main, &m, "k", &work.path().join("a"), &Sources::new(), true, &keep_all()).unwrap(); |
| 764 | 1× | let taken = pool.take(&main, &m, "k", &work.path().join("b")); |
| 765 | 1× | assert!(taken.is_some()); |
| 766 | | |
| 767 | 1× | std::fs::write(work.path().join("b/debug/marker"), b"POISON").unwrap(); |
| 768 | 1× | pool.settle(&main, &m, "k", &work.path().join("b"), &Sources::new(), false, &keep_all()).unwrap(); |
| 769 | 1× | assert!(!work.path().join("b").exists()); |
| 770 | 1× | assert!(pool.take(&main, &m, "k", &work.path().join("c")).is_none(), "nothing it wrote reaches a later job"); |
| 771 | 1× | assert!(pool.slot_times().is_empty()); |
| 772 | | |
| 773 | 1× | let image = Ctx { form: Form::Image, ..main }; |
| 774 | 1× | disk(&work.path().join("d.ext4"), b"BAD!"); |
| 775 | 1× | pool.settle(&image, &m, "k", &work.path().join("d.ext4"), &Sources::new(), false, &keep_all()).unwrap(); |
| 776 | 1× | assert!(!work.path().join("d.ext4").exists() && pool.slot_times().is_empty()); |
| 777 | 1× | } |
| 778 | |
|
| 779 | | #[test] |
| 780 | 1× | fn directories_are_evicted_by_their_size_oldest_first() { |
| 781 | 1× | let home = tempfile::tempdir().unwrap(); |
| 782 | 1× | let work = tempfile::tempdir().unwrap(); |
| 783 | | |
| 784 | 1× | let pool = Pool { root: home.path().join("cache"), limit: 800 << 10 }; |
| 785 | 1× | let m = mount(&[]); |
| 786 | 1× | let (main, feature) = (dir_ctx("main"), dir_ctx("feature")); |
| 787 | 1× | tree(&work.path().join("a"), b"OLD", 512); |
| 788 | 1× | pool.keep(&main, &m, "k1", &work.path().join("a"), &Sources::new()).unwrap(); |
| 789 | 1× | let kept = pool.cache_dir(&main, "target").join(segment("main")).join("k1.tree"); |
| 790 | 1× | assert!(kept.is_dir(), "under the limit it stays"); |
| 791 | 1× | assert!(tree_bytes(&kept) >= 512 << 10, "a directory counts what is in it"); |
| 792 | | |
| 793 | 1× | std::fs::File::open(&kept).unwrap().set_modified(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1)).unwrap(); |
| 794 | 1× | tree(&work.path().join("b"), b"NEW", 512); |
| 795 | 1× | pool.keep(&feature, &m, "k1", &work.path().join("b"), &Sources::new()).unwrap(); |
| 796 | 1× | assert!(!kept.exists() && !kept.with_extension("tree-sources").exists(), "the one used longest ago goes, sources and all"); |
| 797 | 1× | let taken = pool.take(&main, &m, "k1", &work.path().join("c")).unwrap(); |
| 798 | 1× | assert!(taken.how.contains("bookmark's (feature-"), "{}", taken.how); |
| 799 | 1× | assert_eq!(std::fs::read(work.path().join("c/debug/marker")).unwrap(), b"NEW"); |
| 800 | 1× | } |
| 801 | |
|
| 802 | | |
| 803 | | |
| 804 | | #[test] |
| 805 | 1× | fn nothing_kept_is_writable_by_others_or_set_id() { |
| 806 | 1× | let home = tempfile::tempdir().unwrap(); |
| 807 | 1× | let work = tempfile::tempdir().unwrap(); |
| 808 | 1× | let pool = Pool::new(home.path(), None); |
| 809 | 1× | let m = mount(&[]); |
| 810 | 1× | let main = dir_ctx("main"); |
| 811 | 1× | let a = work.path().join("a"); |
| 812 | 1× | tree(&a, b"X", 1); |
| 813 | 5× | let mode = |p: &Path, m: u32| std::fs::set_permissions(p, std::fs::Permissions::from_mode(m)).unwrap(); |
| 814 | 1× | std::fs::write(a.join("open"), b"").unwrap(); |
| 815 | 1× | mode(&a.join("open"), 0o777); |
| 816 | 1× | std::fs::write(a.join("suid"), b"").unwrap(); |
| 817 | 1× | mode(&a.join("suid"), 0o4755); |
| 818 | 1× | std::fs::write(a.join("debug/sealed"), b"secret").unwrap(); |
| 819 | 1× | mode(&a.join("debug/sealed"), 0o000); |
| 820 | 1× | std::os::unix::fs::symlink("/etc/passwd", a.join("link")).unwrap(); |
| 821 | 1× | let when = modified(&a.join("debug/marker")); |
| 822 | 1× | mode(&a.join("debug"), 0o1777); |
| 823 | 1× | mode(&a, 0o500); |
| 824 | 1× | pool.keep(&main, &m, "k", &a, &Sources::new()).unwrap(); |
| 825 | 1× | let root = home.path().join("cache"); |
| 826 | 1× | assert_eq!(std::fs::metadata(&root).unwrap().mode() & 0o777, 0o700, "the pool is the runner's alone"); |
| 827 | 1× | let mut seen = 0; |
| 828 | 14× | fn each(p: &Path, f: &mut dyn FnMut(&Path, &std::fs::Metadata)) { |
| 829 | 14× | let md = std::fs::symlink_metadata(p).unwrap(); |
| 830 | 14× | f(p, &md); |
| 831 | 14× | if md.is_dir() { |
| 832 | 13× | for e in std::fs::read_dir(p).unwrap() { |
| 833 | 13× | each(&e.unwrap().path(), f); |
| 834 | 13× | } |
| 835 | 7× | } |
| 836 | 14× | } |
| 837 | 14× | each(&root, &mut |p, md| { |
| 838 | 14× | seen += 1; |
| 839 | 14× | if !md.file_type().is_symlink() { |
| 840 | 13× | assert_eq!(md.mode() & 0o7022, 0, "{} is {:o}", p.display(), md.mode()); |
| 841 | 1× | } |
| 842 | 14× | }); |
| 843 | 1× | assert!(seen >= 10, "{seen}"); |
| 844 | | |
| 845 | 1× | let taken = pool.take(&main, &m, "k", &work.path().join("b")); |
| 846 | 1× | assert!(taken.is_some()); |
| 847 | 1× | let b = work.path().join("b"); |
| 848 | 1× | assert_eq!(std::fs::read(b.join("debug/sealed")).unwrap(), b"secret"); |
| 849 | 1× | assert_eq!(std::fs::metadata(b.join("open")).unwrap().mode() & 0o777, 0o755); |
| 850 | 1× | assert_eq!(std::fs::read_link(b.join("link")).unwrap(), Path::new("/etc/passwd"), "a link is kept, not followed"); |
| 851 | 1× | assert_eq!(modified(&b.join("debug/marker")), when); |
| 852 | 1× | } |
| 853 | | |
| 854 | | |
| 855 | | |
| 856 | 3× | fn aged(root: &Path, rel: &str, kib: usize, secs: u64) -> PathBuf { |
| 857 | 3× | let p = root.join(rel); |
| 858 | 3× | std::fs::create_dir_all(p.parent().unwrap()).unwrap(); |
| 859 | 8388608× | let bytes: Vec<u8> = (0..kib << 10).map(|i: usize| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); |
| 860 | 3× | std::fs::write(&p, bytes).unwrap(); |
| 861 | 3× | let t = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(secs); |
| 862 | 3× | std::fs::File::options() |
| 863 | 3× | .write(true) |
| 864 | 3× | .open(&p) |
| 865 | 3× | .unwrap() |
| 866 | 3× | .set_times(std::fs::FileTimes::new().set_accessed(t).set_modified(t)) |
| 867 | 3× | .unwrap(); |
| 868 | 3× | p |
| 869 | 3× | } |
| 870 | |
|
| 871 | | const T: u64 = 4_000_000_000; |
| 872 | |
|
| 873 | 1× | fn at_t() -> SystemTime { |
| 874 | 1× | SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(T) |
| 875 | 1× | } |
| 876 | |
|
| 877 | | |
| 878 | | |
| 879 | | |
| 880 | | #[test] |
| 881 | 1× | fn a_directory_is_pruned_of_what_the_job_did_not_use_before_it_is_kept() { |
| 882 | 1× | let home = tempfile::tempdir().unwrap(); |
| 883 | 1× | let work = tempfile::tempdir().unwrap(); |
| 884 | 1× | let pool = Pool::new(home.path(), None); |
| 885 | 1× | let main = dir_ctx("main"); |
| 886 | 1× | let mut m = mount(&[]); |
| 887 | 1× | m.size_mib = 8; |
| 888 | 1× | let a = work.path().join("a"); |
| 889 | | |
| 890 | 1× | aged(&a, "debug/deps/libnew-aaaaaaaaaaaaaaaa.rlib", 2 << 10, T + 10); |
| 891 | 1× | aged(&a, "debug/deps/libold-bbbbbbbbbbbbbbbb.rlib", 3 << 10, T - 1_000); |
| 892 | 1× | let prune = Prune { started: at_t(), percent: 50, guest: None }; |
| 893 | 1× | let line = pool.settle(&main, &m, "k", &a, &Sources::new(), true, &prune).unwrap().unwrap(); |
| 894 | 1× | assert_eq!( |
| 895 | | line, |
| 896 | | "cache target: kept 2 MiB of 5 MiB (pruned 3 MiB in 1 file this run did not use; the cap is 50% of its 8 MiB disk)" |
| 897 | | ); |
| 898 | 1× | let b = work.path().join("b"); |
| 899 | 1× | assert!(pool.take(&main, &m, "k", &b).unwrap().how.contains("same key")); |
| 900 | 1× | assert!(b.join("debug/deps/libnew-aaaaaaaaaaaaaaaa.rlib").is_file() && !b.join("debug/deps/libold-bbbbbbbbbbbbbbbb.rlib").exists()); |
| 901 | | |
| 902 | 1× | forget_reads(Form::Dir, &b).unwrap(); |
| 903 | 1× | let md = std::fs::metadata(b.join("debug/deps/libnew-aaaaaaaaaaaaaaaa.rlib")).unwrap(); |
| 904 | 1× | assert_eq!((md.atime(), md.mtime()), (0, (T + 10) as i64)); |
| 905 | | |
| 906 | | |
| 907 | 1× | aged(&b, "debug/deps/libbig-cccccccccccccccc.rlib", 3 << 10, T + 20); |
| 908 | 1× | let line = pool.settle(&main, &m, "k", &b, &Sources::new(), true, &prune).unwrap().unwrap(); |
| 909 | 1× | assert!( |
| 910 | 1× | line.starts_with("cache target: not kept: 5 MiB is over its cap of 4 MiB (50% of its 8 MiB disk); the next run starts empty"), |
| 911 | | "{line}" |
| 912 | | ); |
| 913 | 1× | assert!(!b.exists() && pool.take(&main, &m, "k", &work.path().join("c")).is_none()); |
| 914 | 1× | } |
| 915 | |
|
| 916 | | |
| 917 | | |
| 918 | | #[test] |
| 919 | 1× | fn an_image_is_kept_by_what_its_guest_pruned_or_else_by_its_size() { |
| 920 | 1× | let home = tempfile::tempdir().unwrap(); |
| 921 | 1× | let work = tempfile::tempdir().unwrap(); |
| 922 | 1× | let pool = Pool::new(home.path(), None); |
| 923 | 1× | let ctx = Ctx { repo: "r", bookmark: "main", job: "j", image: "i", form: Form::Image }; |
| 924 | 1× | let mut m = mount(&[]); |
| 925 | 1× | m.size_mib = 16; |
| 926 | 1× | let fits = Pruned { size: 16 << 20, percent: 60, before: 12 << 20, after: 6 << 20, freed: 6 << 20, files: 40, unpruned: None }; |
| 927 | 1× | let over = Pruned { after: 11 << 20, ..fits.clone() }; |
| 928 | 1× | disk(&work.path().join("a.ext4"), b"KEEP"); |
| 929 | 1× | let line = pool |
| 930 | 1× | .settle(&ctx, &m, "k", &work.path().join("a.ext4"), &Sources::new(), true, &Prune { guest: Some(&fits), ..keep_all() }) |
| 931 | 1× | .unwrap() |
| 932 | 1× | .unwrap(); |
| 933 | 1× | assert_eq!( |
| 934 | | line, |
| 935 | | "cache target: kept 6 MiB of 12 MiB (pruned 6 MiB in 40 files this run did not use; the cap is 60% of its 16 MiB disk)" |
| 936 | | ); |
| 937 | 1× | assert!(pool.take(&ctx, &m, "k", &work.path().join("b.ext4")).is_none(), "a 1 MiB disk is not the mount's 16 MiB"); |
| 938 | 1× | disk(&work.path().join("c.ext4"), b"OVER"); |
| 939 | 1× | let line = pool |
| 940 | 1× | .settle(&ctx, &m, "k", &work.path().join("c.ext4"), &Sources::new(), true, &Prune { guest: Some(&over), ..keep_all() }) |
| 941 | 1× | .unwrap() |
| 942 | 1× | .unwrap(); |
| 943 | 1× | assert!(line.starts_with("cache target: not kept: 11 MiB after pruning 6 MiB in 40 files"), "{line}"); |
| 944 | 1× | assert!(!work.path().join("c.ext4").exists()); |
| 945 | | |
| 946 | 1× | let img = work.path().join("d.ext4"); |
| 947 | 1× | crate::workspace::empty_ext4(&img, 16, "scratch").unwrap(); |
| 948 | 1× | let line = pool.settle(&ctx, &m, "k", &img, &Sources::new(), true, &Prune { percent: 60, ..keep_all() }).unwrap().unwrap(); |
| 949 | 1× | assert!(line.starts_with("cache target: kept ") && line.contains("under its cap of 60% of its 16 MiB disk"), "{line}"); |
| 950 | 1× | assert!(pool.take(&ctx, &m, "k", &work.path().join("e.ext4")).is_some()); |
| 951 | | |
| 952 | 1× | let line = pool |
| 953 | 1× | .settle(&ctx, &m, "k", &work.path().join("e.ext4"), &Sources::new(), true, &Prune { percent: 1, ..keep_all() }) |
| 954 | 1× | .unwrap() |
| 955 | 1× | .unwrap(); |
| 956 | 1× | assert!(line.contains("not kept") && line.contains("(the guest did not prune it)"), "{line}"); |
| 957 | 1× | } |
| 958 | |
|
| 959 | | #[test] |
| 960 | 1× | fn the_superblock_says_what_is_in_use() { |
| 961 | 1× | let h = "Filesystem volume name: scratch\nBlock count: 4096\nFree blocks: 1024\nBlock size: 4096\n"; |
| 962 | 1× | assert_eq!(superblock_usage(h), Some((3072 * 4096, 4096 * 4096))); |
| 963 | 1× | assert_eq!(superblock_usage("Block count: 1\n"), None); |
| 964 | 1× | } |
| 965 | | } |