| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | use std::fs; |
| 15 | use std::io; |
| 16 | use std::path::{Component, Path, PathBuf}; |
| 17 | use std::process::Stdio; |
| 18 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 19 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 20 | |
| 21 | use forge_ci::proto::{JobAssignment, Outcome}; |
| 22 | use serde::{Deserialize, Serialize}; |
| 23 | use sha2::{Digest, Sha256}; |
| 24 | use tokio::process::Command; |
| 25 | |
| 26 | use crate::sandbox::idmap::{IdMap, remove_tree}; |
| 27 | |
| 28 | |
| 29 | const MAX_PATHS: usize = 32; |
| 30 | |
| 31 | const MAX_PATH_LEN: usize = 512; |
| 32 | |
| 33 | const MAX_KEY_LEN: usize = 256; |
| 34 | |
| 35 | const MAX_STDERR: usize = 500; |
| 36 | const MANIFEST: &str = "manifest.json"; |
| 37 | const META: &str = "meta.json"; |
| 38 | const SCRATCH_PREFIXES: [&str; 3] = [".inuse-", ".new-", ".old-"]; |
| 39 | |
| 40 | |
| 41 | #[derive(Debug, thiserror::Error)] |
| 42 | pub enum CacheError { |
| 43 | #[error("cache io: {0}")] |
| 44 | Io(#[from] io::Error), |
| 45 | #[error("cache path {path:?} refused: {reason}")] |
| 46 | Path { path: String, reason: &'static str }, |
| 47 | #[error("{} is a symlink, not following it", .0.display())] |
| 48 | Symlink(PathBuf), |
| 49 | #[error("{} is not a directory", .0.display())] |
| 50 | NotDir(PathBuf), |
| 51 | #[error("cp failed: {0}")] |
| 52 | Copy(String), |
| 53 | } |
| 54 | |
| 55 | |
| 56 | #[derive(Debug, Serialize, Deserialize)] |
| 57 | struct Meta { |
| 58 | repo: String, |
| 59 | job: String, |
| 60 | key: String, |
| 61 | |
| 62 | saved_at: u64, |
| 63 | size_bytes: u64, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | struct Found { |
| 68 | path: PathBuf, |
| 69 | size: u64, |
| 70 | saved_at: u64, |
| 71 | } |
| 72 | |
| 73 | |
| 74 | pub struct CacheStore { |
| 75 | root: PathBuf, |
| 76 | |
| 77 | max_bytes: u64, |
| 78 | idmap: IdMap, |
| 79 | helper: PathBuf, |
| 80 | |
| 81 | lock: tokio::sync::Mutex<()>, |
| 82 | |
| 83 | last_stamp: AtomicU64, |
| 84 | } |
| 85 | |
| 86 | impl CacheStore { |
| 87 | |
| 88 | |
| 89 | pub fn new(root: PathBuf, max_bytes: u64, idmap: IdMap, helper: PathBuf) -> Self { |
| 90 | Self { |
| 91 | root, |
| 92 | max_bytes, |
| 93 | idmap, |
| 94 | helper, |
| 95 | lock: tokio::sync::Mutex::new(()), |
| 96 | last_stamp: AtomicU64::new(0), |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | |
| 101 | pub async fn sweep_stale(&self) -> Result<(), CacheError> { |
| 102 | let mut dir = match tokio::fs::read_dir(&self.root).await { |
| 103 | Ok(dir) => dir, |
| 104 | Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), |
| 105 | Err(e) => return Err(e.into()), |
| 106 | }; |
| 107 | let mut stale = Vec::new(); |
| 108 | while let Some(entry) = dir.next_entry().await? { |
| 109 | if is_scratch(&entry.file_name().to_string_lossy()) { |
| 110 | stale.push(entry.path()); |
| 111 | } |
| 112 | } |
| 113 | for path in stale { |
| 114 | tracing::info!(path = %path.display(), "removing scratch dir of a crashed job"); |
| 115 | self.remove(&path).await?; |
| 116 | } |
| 117 | Ok(()) |
| 118 | } |
| 119 | |
| 120 | |
| 121 | |
| 122 | pub async fn restore(&self, job: &JobAssignment, workspace: &Path) -> Vec<String> { |
| 123 | let mut lines = Vec::new(); |
| 124 | if job.cache.is_empty() || self.max_bytes == 0 { |
| 125 | return lines; |
| 126 | } |
| 127 | let wanted = match validate_paths(&job.cache) { |
| 128 | Ok(wanted) => wanted, |
| 129 | Err(e) => { |
| 130 | lines.push(format!("runner: cache skipped: {e}")); |
| 131 | return lines; |
| 132 | } |
| 133 | }; |
| 134 | |
| 135 | if !job.cache_key.is_empty() { |
| 136 | let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key); |
| 137 | match self.claim(&job.job_id, &entry).await { |
| 138 | Ok(Some(inuse)) => { |
| 139 | let size = self |
| 140 | .restore_claimed(&inuse, workspace, &wanted, &mut lines) |
| 141 | .await; |
| 142 | lines.push(format!( |
| 143 | "runner: cache hit {} ({})", |
| 144 | job.cache_key, |
| 145 | human(size) |
| 146 | )); |
| 147 | return lines; |
| 148 | } |
| 149 | Ok(None) => {} |
| 150 | Err(e) => lines.push(format!("runner: cache restore failed: {e}")), |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | for key in &job.cache_restore_keys { |
| 155 | if key.is_empty() || key.len() > MAX_KEY_LEN { |
| 156 | continue; |
| 157 | } |
| 158 | if self |
| 159 | .restore_fallback(job, key, workspace, &wanted, &mut lines) |
| 160 | .await |
| 161 | { |
| 162 | return lines; |
| 163 | } |
| 164 | } |
| 165 | lines.push("runner: cache miss".to_owned()); |
| 166 | lines |
| 167 | } |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | pub async fn save( |
| 173 | &self, |
| 174 | job: &JobAssignment, |
| 175 | outcome: Outcome, |
| 176 | workspace: &Path, |
| 177 | ) -> Vec<String> { |
| 178 | let mut lines = Vec::new(); |
| 179 | let finished = matches!(outcome, Outcome::Success | Outcome::Failure); |
| 180 | if finished && self.max_bytes > 0 && !job.cache.is_empty() && !job.cache_key.is_empty() { |
| 181 | match validate_paths(&job.cache) { |
| 182 | Ok(paths) => { |
| 183 | if let Err(e) = self.save_paths(job, workspace, &paths, &mut lines).await { |
| 184 | lines.push(format!("runner: cache not saved: {e}")); |
| 185 | } |
| 186 | } |
| 187 | Err(e) => lines.push(format!("runner: cache not saved: {e}")), |
| 188 | } |
| 189 | } |
| 190 | if let Err(e) = self.remove_scratch(&job.job_id).await { |
| 191 | tracing::warn!(job_id = %job.job_id, error = %e, "cannot remove cache scratch dirs"); |
| 192 | } |
| 193 | lines |
| 194 | } |
| 195 | |
| 196 | |
| 197 | |
| 198 | async fn restore_claimed( |
| 199 | &self, |
| 200 | inuse: &Path, |
| 201 | workspace: &Path, |
| 202 | wanted: &[PathBuf], |
| 203 | lines: &mut Vec<String>, |
| 204 | ) -> u64 { |
| 205 | let size = match read_meta(inuse) { |
| 206 | Some(meta) => meta.size_bytes, |
| 207 | None => dir_size(inuse).await, |
| 208 | }; |
| 209 | let manifest = match read_manifest(inuse) { |
| 210 | Ok(manifest) => manifest, |
| 211 | Err(e) => { |
| 212 | lines.push(format!("runner: cache restore failed: {e}")); |
| 213 | return size; |
| 214 | } |
| 215 | }; |
| 216 | for (k, rel) in selected(&manifest, wanted, lines) { |
| 217 | let src = inuse.join(format!("p{k}")); |
| 218 | match move_into(workspace, &rel, &src).await { |
| 219 | Ok(true) => {} |
| 220 | Ok(false) => lines.push(skipped(&rel)), |
| 221 | Err(e) => lines.push(format!( |
| 222 | "runner: cache restore failed for {}: {e}", |
| 223 | rel.display() |
| 224 | )), |
| 225 | } |
| 226 | } |
| 227 | size |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | async fn restore_fallback( |
| 233 | &self, |
| 234 | job: &JobAssignment, |
| 235 | key: &str, |
| 236 | workspace: &Path, |
| 237 | wanted: &[PathBuf], |
| 238 | lines: &mut Vec<String>, |
| 239 | ) -> bool { |
| 240 | let source = self.entry_dir(&job.repo, &job.job_name, key); |
| 241 | if !is_dir(&source) { |
| 242 | return false; |
| 243 | } |
| 244 | let manifest = match read_manifest(&source) { |
| 245 | Ok(manifest) => manifest, |
| 246 | Err(e) => { |
| 247 | lines.push(format!("runner: cache restore failed: {e}")); |
| 248 | return false; |
| 249 | } |
| 250 | }; |
| 251 | let mut restored = 0usize; |
| 252 | for (k, rel) in selected(&manifest, wanted, lines) { |
| 253 | let src = source.join(format!("p{k}")); |
| 254 | match copy_into(workspace, &rel, &src).await { |
| 255 | Ok(true) => restored += 1, |
| 256 | Ok(false) => lines.push(skipped(&rel)), |
| 257 | Err(e) => lines.push(format!( |
| 258 | "runner: cache restore failed for {}: {e}", |
| 259 | rel.display() |
| 260 | )), |
| 261 | } |
| 262 | } |
| 263 | if restored == 0 { |
| 264 | return false; |
| 265 | } |
| 266 | lines.push(format!("runner: cache restored from fallback {key}")); |
| 267 | true |
| 268 | } |
| 269 | |
| 270 | |
| 271 | |
| 272 | async fn save_paths( |
| 273 | &self, |
| 274 | job: &JobAssignment, |
| 275 | workspace: &Path, |
| 276 | paths: &[PathBuf], |
| 277 | lines: &mut Vec<String>, |
| 278 | ) -> Result<(), CacheError> { |
| 279 | tokio::fs::create_dir_all(&self.root).await?; |
| 280 | let new = self.scratch(".new-", &job.job_id); |
| 281 | self.remove(&new).await?; |
| 282 | tokio::fs::create_dir(&new).await?; |
| 283 | |
| 284 | let mut manifest: Vec<String> = Vec::new(); |
| 285 | for rel in paths { |
| 286 | let src = match existing_in_workspace(workspace, rel) { |
| 287 | Ok(Some(src)) => src, |
| 288 | Ok(None) => continue, |
| 289 | Err(e) => { |
| 290 | lines.push(format!("runner: cache skipped {}: {e}", rel.display())); |
| 291 | continue; |
| 292 | } |
| 293 | }; |
| 294 | let dst = new.join(format!("p{}", manifest.len())); |
| 295 | match tokio::fs::rename(&src, &dst).await { |
| 296 | Ok(()) => manifest.push(rel.display().to_string()), |
| 297 | Err(e) => lines.push(format!("runner: cache skipped {}: {e}", rel.display())), |
| 298 | } |
| 299 | } |
| 300 | if manifest.is_empty() { |
| 301 | self.remove(&new).await?; |
| 302 | return Ok(()); |
| 303 | } |
| 304 | |
| 305 | |
| 306 | let size = dir_size(&new).await; |
| 307 | write_json(&new.join(MANIFEST), &manifest).await?; |
| 308 | let meta = Meta { |
| 309 | repo: job.repo.clone(), |
| 310 | job: job.job_name.clone(), |
| 311 | key: job.cache_key.clone(), |
| 312 | saved_at: self.stamp(), |
| 313 | size_bytes: size, |
| 314 | }; |
| 315 | write_json(&new.join(META), &meta).await?; |
| 316 | |
| 317 | let entry = self.entry_dir(&job.repo, &job.job_name, &job.cache_key); |
| 318 | let old = self.scratch(".old-", &job.job_id); |
| 319 | { |
| 320 | let _guard = self.lock.lock().await; |
| 321 | self.remove(&old).await?; |
| 322 | let had_old = is_dir(&entry); |
| 323 | if had_old { |
| 324 | tokio::fs::rename(&entry, &old).await?; |
| 325 | } |
| 326 | if let Err(e) = tokio::fs::rename(&new, &entry).await { |
| 327 | if had_old { |
| 328 | |
| 329 | let _ = tokio::fs::rename(&old, &entry).await; |
| 330 | } |
| 331 | return Err(e.into()); |
| 332 | } |
| 333 | match self.evict().await { |
| 334 | Ok(0) => {} |
| 335 | Ok(removed) => tracing::info!(removed, "cache entries evicted"), |
| 336 | Err(e) => tracing::warn!(error = %e, "cache eviction failed"), |
| 337 | } |
| 338 | } |
| 339 | lines.push(format!("runner: cache saved ({})", human(size))); |
| 340 | Ok(()) |
| 341 | } |
| 342 | |
| 343 | |
| 344 | |
| 345 | async fn claim(&self, job_id: &str, entry: &Path) -> Result<Option<PathBuf>, CacheError> { |
| 346 | let _guard = self.lock.lock().await; |
| 347 | if !is_dir(entry) { |
| 348 | return Ok(None); |
| 349 | } |
| 350 | let inuse = self.scratch(".inuse-", job_id); |
| 351 | self.remove(&inuse).await?; |
| 352 | match tokio::fs::rename(entry, &inuse).await { |
| 353 | Ok(()) => Ok(Some(inuse)), |
| 354 | Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), |
| 355 | Err(e) => Err(e.into()), |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | |
| 360 | |
| 361 | async fn evict(&self) -> Result<usize, CacheError> { |
| 362 | let mut entries = self.list_entries().await?; |
| 363 | let mut total = entries |
| 364 | .iter() |
| 365 | .fold(0u64, |sum, e| sum.saturating_add(e.size)); |
| 366 | entries.sort_by_key(|e| e.saved_at); |
| 367 | let mut removed = 0; |
| 368 | for entry in entries { |
| 369 | if total <= self.max_bytes { |
| 370 | break; |
| 371 | } |
| 372 | self.remove(&entry.path).await?; |
| 373 | total = total.saturating_sub(entry.size); |
| 374 | removed += 1; |
| 375 | } |
| 376 | Ok(removed) |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | async fn list_entries(&self) -> Result<Vec<Found>, CacheError> { |
| 382 | let mut found = Vec::new(); |
| 383 | let mut dir = match tokio::fs::read_dir(&self.root).await { |
| 384 | Ok(dir) => dir, |
| 385 | Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(found), |
| 386 | Err(e) => return Err(e.into()), |
| 387 | }; |
| 388 | while let Some(item) = dir.next_entry().await? { |
| 389 | let name = item.file_name().to_string_lossy().into_owned(); |
| 390 | let path = item.path(); |
| 391 | if !is_entry_name(&name) || !is_dir(&path) { |
| 392 | continue; |
| 393 | } |
| 394 | let entry = match read_meta(&path) { |
| 395 | Some(meta) => Found { |
| 396 | path, |
| 397 | size: meta.size_bytes, |
| 398 | saved_at: meta.saved_at, |
| 399 | }, |
| 400 | None => { |
| 401 | let saved_at = fs::metadata(&path) |
| 402 | .and_then(|m| m.modified()) |
| 403 | .ok() |
| 404 | .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) |
| 405 | .map_or(0, nanos); |
| 406 | Found { |
| 407 | size: dir_size(&path).await, |
| 408 | path, |
| 409 | saved_at, |
| 410 | } |
| 411 | } |
| 412 | }; |
| 413 | found.push(entry); |
| 414 | } |
| 415 | Ok(found) |
| 416 | } |
| 417 | |
| 418 | |
| 419 | fn stamp(&self) -> u64 { |
| 420 | let now = nanos( |
| 421 | SystemTime::now() |
| 422 | .duration_since(UNIX_EPOCH) |
| 423 | .unwrap_or_default(), |
| 424 | ); |
| 425 | let mut prev = self.last_stamp.load(Ordering::SeqCst); |
| 426 | loop { |
| 427 | let next = now.max(prev.saturating_add(1)); |
| 428 | match self |
| 429 | .last_stamp |
| 430 | .compare_exchange(prev, next, Ordering::SeqCst, Ordering::SeqCst) |
| 431 | { |
| 432 | Ok(_) => return next, |
| 433 | Err(actual) => prev = actual, |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | fn entry_dir(&self, repo: &str, job_name: &str, key: &str) -> PathBuf { |
| 439 | self.root.join(entry_name(repo, job_name, key)) |
| 440 | } |
| 441 | |
| 442 | fn scratch(&self, prefix: &str, job_id: &str) -> PathBuf { |
| 443 | self.root.join(format!("{prefix}{job_id}")) |
| 444 | } |
| 445 | |
| 446 | |
| 447 | async fn remove_scratch(&self, job_id: &str) -> Result<(), CacheError> { |
| 448 | for prefix in SCRATCH_PREFIXES { |
| 449 | self.remove(&self.scratch(prefix, job_id)).await?; |
| 450 | } |
| 451 | Ok(()) |
| 452 | } |
| 453 | |
| 454 | |
| 455 | |
| 456 | async fn remove(&self, path: &Path) -> Result<(), CacheError> { |
| 457 | let (map, helper, path) = (self.idmap.clone(), self.helper.clone(), path.to_owned()); |
| 458 | tokio::task::spawn_blocking(move || remove_tree(&map, &path, &helper)) |
| 459 | .await |
| 460 | .map_err(io::Error::other)??; |
| 461 | Ok(()) |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | |
| 466 | |
| 467 | pub fn validate_path(path: &str) -> Result<PathBuf, CacheError> { |
| 468 | let refuse = |reason: &'static str| CacheError::Path { |
| 469 | path: path.to_owned(), |
| 470 | reason, |
| 471 | }; |
| 472 | if path.is_empty() { |
| 473 | return Err(refuse("empty")); |
| 474 | } |
| 475 | if path.len() > MAX_PATH_LEN { |
| 476 | return Err(refuse("too long")); |
| 477 | } |
| 478 | if path.contains(['\0', '\\']) { |
| 479 | return Err(refuse("contains NUL or backslash")); |
| 480 | } |
| 481 | if path.starts_with('/') { |
| 482 | return Err(refuse("absolute")); |
| 483 | } |
| 484 | let mut out = PathBuf::new(); |
| 485 | for part in path.split('/') { |
| 486 | match part { |
| 487 | "" | "." => return Err(refuse("empty or . part")), |
| 488 | ".." => return Err(refuse("contains ..")), |
| 489 | part if part.eq_ignore_ascii_case(".git") => return Err(refuse(".git is not cached")), |
| 490 | part => out.push(part), |
| 491 | } |
| 492 | } |
| 493 | Ok(out) |
| 494 | } |
| 495 | |
| 496 | |
| 497 | pub fn validate_paths(paths: &[String]) -> Result<Vec<PathBuf>, CacheError> { |
| 498 | if paths.len() > MAX_PATHS { |
| 499 | return Err(CacheError::Path { |
| 500 | path: format!("{} paths", paths.len()), |
| 501 | reason: "too many cache paths", |
| 502 | }); |
| 503 | } |
| 504 | let parsed = paths |
| 505 | .iter() |
| 506 | .map(|p| validate_path(p)) |
| 507 | .collect::<Result<Vec<_>, _>>()?; |
| 508 | for (i, a) in parsed.iter().enumerate() { |
| 509 | for b in &parsed[i + 1..] { |
| 510 | if a.starts_with(b) || b.starts_with(a) { |
| 511 | return Err(CacheError::Path { |
| 512 | path: a.display().to_string(), |
| 513 | reason: "overlaps another cache path", |
| 514 | }); |
| 515 | } |
| 516 | } |
| 517 | } |
| 518 | Ok(parsed) |
| 519 | } |
| 520 | |
| 521 | |
| 522 | |
| 523 | fn selected( |
| 524 | manifest: &[String], |
| 525 | wanted: &[PathBuf], |
| 526 | lines: &mut Vec<String>, |
| 527 | ) -> Vec<(usize, PathBuf)> { |
| 528 | let mut out = Vec::new(); |
| 529 | for (k, raw) in manifest.iter().enumerate() { |
| 530 | match validate_path(raw) { |
| 531 | Ok(rel) if wanted.contains(&rel) => out.push((k, rel)), |
| 532 | Ok(_) => {} |
| 533 | Err(e) => lines.push(format!("runner: cache skipped: {e}")), |
| 534 | } |
| 535 | } |
| 536 | out |
| 537 | } |
| 538 | |
| 539 | |
| 540 | |
| 541 | |
| 542 | fn workspace_path( |
| 543 | workspace: &Path, |
| 544 | rel: &Path, |
| 545 | create: bool, |
| 546 | ) -> Result<Option<PathBuf>, CacheError> { |
| 547 | if !fs::symlink_metadata(workspace)?.is_dir() { |
| 548 | return Err(CacheError::NotDir(workspace.to_owned())); |
| 549 | } |
| 550 | let mut cur = workspace.to_owned(); |
| 551 | let parent = rel.parent().unwrap_or(Path::new("")); |
| 552 | for part in parent.components() { |
| 553 | let Component::Normal(name) = part else { |
| 554 | return Err(CacheError::Path { |
| 555 | path: rel.display().to_string(), |
| 556 | reason: "not a plain relative path", |
| 557 | }); |
| 558 | }; |
| 559 | cur.push(name); |
| 560 | match fs::symlink_metadata(&cur) { |
| 561 | Ok(meta) if meta.file_type().is_symlink() => return Err(CacheError::Symlink(cur)), |
| 562 | Ok(meta) if meta.is_dir() => {} |
| 563 | Ok(_) => return Err(CacheError::NotDir(cur)), |
| 564 | Err(e) if e.kind() == io::ErrorKind::NotFound => { |
| 565 | if !create { |
| 566 | return Ok(None); |
| 567 | } |
| 568 | fs::create_dir(&cur)?; |
| 569 | } |
| 570 | Err(e) => return Err(e.into()), |
| 571 | } |
| 572 | } |
| 573 | let Some(name) = rel.file_name() else { |
| 574 | return Err(CacheError::Path { |
| 575 | path: rel.display().to_string(), |
| 576 | reason: "no file name", |
| 577 | }); |
| 578 | }; |
| 579 | Ok(Some(cur.join(name))) |
| 580 | } |
| 581 | |
| 582 | |
| 583 | fn existing_in_workspace(workspace: &Path, rel: &Path) -> Result<Option<PathBuf>, CacheError> { |
| 584 | let Some(path) = workspace_path(workspace, rel, false)? else { |
| 585 | return Ok(None); |
| 586 | }; |
| 587 | Ok(exists_no_follow(&path).then_some(path)) |
| 588 | } |
| 589 | |
| 590 | |
| 591 | async fn move_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> { |
| 592 | let Some(dest) = workspace_path(workspace, rel, true)? else { |
| 593 | return Ok(false); |
| 594 | }; |
| 595 | if exists_no_follow(&dest) { |
| 596 | return Ok(false); |
| 597 | } |
| 598 | tokio::fs::rename(src, &dest).await?; |
| 599 | Ok(true) |
| 600 | } |
| 601 | |
| 602 | |
| 603 | |
| 604 | async fn copy_into(workspace: &Path, rel: &Path, src: &Path) -> Result<bool, CacheError> { |
| 605 | let Some(dest) = workspace_path(workspace, rel, true)? else { |
| 606 | return Ok(false); |
| 607 | }; |
| 608 | if exists_no_follow(&dest) { |
| 609 | return Ok(false); |
| 610 | } |
| 611 | let output = Command::new("cp") |
| 612 | .args(["-a", "--reflink=auto", "--"]) |
| 613 | .arg(src) |
| 614 | .arg(&dest) |
| 615 | .stdin(Stdio::null()) |
| 616 | .stdout(Stdio::null()) |
| 617 | .stderr(Stdio::piped()) |
| 618 | .kill_on_drop(true) |
| 619 | .output() |
| 620 | .await?; |
| 621 | if output.status.success() { |
| 622 | return Ok(true); |
| 623 | } |
| 624 | |
| 625 | let _ = plain_remove(&dest).await; |
| 626 | let stderr: String = String::from_utf8_lossy(&output.stderr) |
| 627 | .chars() |
| 628 | .take(MAX_STDERR) |
| 629 | .collect(); |
| 630 | Err(CacheError::Copy(stderr.trim().to_owned())) |
| 631 | } |
| 632 | |
| 633 | |
| 634 | |
| 635 | async fn plain_remove(path: &Path) -> io::Result<()> { |
| 636 | match fs::symlink_metadata(path) { |
| 637 | Ok(meta) if meta.is_dir() => tokio::fs::remove_dir_all(path).await, |
| 638 | Ok(_) => tokio::fs::remove_file(path).await, |
| 639 | Err(e) => Err(e), |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | fn read_meta(dir: &Path) -> Option<Meta> { |
| 644 | let bytes = fs::read(dir.join(META)).ok()?; |
| 645 | serde_json::from_slice(&bytes).ok() |
| 646 | } |
| 647 | |
| 648 | fn read_manifest(dir: &Path) -> Result<Vec<String>, CacheError> { |
| 649 | let bytes = fs::read(dir.join(MANIFEST))?; |
| 650 | serde_json::from_slice(&bytes).map_err(|e| CacheError::Io(io::Error::other(e))) |
| 651 | } |
| 652 | |
| 653 | async fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), CacheError> { |
| 654 | let bytes = serde_json::to_vec(value).map_err(io::Error::other)?; |
| 655 | tokio::fs::write(path, bytes).await?; |
| 656 | Ok(()) |
| 657 | } |
| 658 | |
| 659 | |
| 660 | |
| 661 | async fn dir_size(root: &Path) -> u64 { |
| 662 | let root = root.to_owned(); |
| 663 | tokio::task::spawn_blocking(move || tree_size(&root)) |
| 664 | .await |
| 665 | .unwrap_or(0) |
| 666 | } |
| 667 | |
| 668 | fn tree_size(root: &Path) -> u64 { |
| 669 | let mut total = 0u64; |
| 670 | let mut stack = vec![root.to_owned()]; |
| 671 | while let Some(dir) = stack.pop() { |
| 672 | let Ok(entries) = fs::read_dir(&dir) else { |
| 673 | continue; |
| 674 | }; |
| 675 | for entry in entries.flatten() { |
| 676 | let Ok(meta) = fs::symlink_metadata(entry.path()) else { |
| 677 | continue; |
| 678 | }; |
| 679 | if meta.is_dir() { |
| 680 | stack.push(entry.path()); |
| 681 | } else { |
| 682 | total = total.saturating_add(meta.len()); |
| 683 | } |
| 684 | } |
| 685 | } |
| 686 | total |
| 687 | } |
| 688 | |
| 689 | |
| 690 | fn entry_name(repo: &str, job_name: &str, key: &str) -> String { |
| 691 | let mut hash = Sha256::new(); |
| 692 | hash.update(repo.as_bytes()); |
| 693 | hash.update([0u8]); |
| 694 | hash.update(job_name.as_bytes()); |
| 695 | hash.update([0u8]); |
| 696 | hash.update(key.as_bytes()); |
| 697 | hex::encode(hash.finalize()) |
| 698 | } |
| 699 | |
| 700 | |
| 701 | fn is_entry_name(name: &str) -> bool { |
| 702 | name.len() == 64 |
| 703 | && name |
| 704 | .bytes() |
| 705 | .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) |
| 706 | } |
| 707 | |
| 708 | fn is_scratch(name: &str) -> bool { |
| 709 | SCRATCH_PREFIXES.iter().any(|p| name.starts_with(p)) |
| 710 | } |
| 711 | |
| 712 | fn is_dir(path: &Path) -> bool { |
| 713 | fs::symlink_metadata(path).is_ok_and(|m| m.is_dir()) |
| 714 | } |
| 715 | |
| 716 | fn exists_no_follow(path: &Path) -> bool { |
| 717 | fs::symlink_metadata(path).is_ok() |
| 718 | } |
| 719 | |
| 720 | fn nanos(d: Duration) -> u64 { |
| 721 | u64::try_from(d.as_nanos()).unwrap_or(u64::MAX) |
| 722 | } |
| 723 | |
| 724 | fn skipped(rel: &Path) -> String { |
| 725 | format!( |
| 726 | "runner: cache skipped {}: already in the checkout", |
| 727 | rel.display() |
| 728 | ) |
| 729 | } |
| 730 | |
| 731 | |
| 732 | fn human(bytes: u64) -> String { |
| 733 | const KIB: f64 = 1024.0; |
| 734 | let b = bytes as f64; |
| 735 | if b >= KIB * KIB * KIB { |
| 736 | format!("{:.1} GiB", b / (KIB * KIB * KIB)) |
| 737 | } else if b >= KIB * KIB { |
| 738 | format!("{:.1} MiB", b / (KIB * KIB)) |
| 739 | } else { |
| 740 | format!("{:.1} KiB", b / KIB) |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | #[cfg(test)] |
| 745 | mod tests { |
| 746 | use std::collections::BTreeMap; |
| 747 | use std::os::unix::fs::symlink; |
| 748 | |
| 749 | use super::*; |
| 750 | |
| 751 | fn job(job_id: &str, key: &str, restore: &[&str], cache: &[&str]) -> JobAssignment { |
| 752 | JobAssignment { |
| 753 | job_id: job_id.to_owned(), |
| 754 | job_token: "tok_secret_value".to_owned(), |
| 755 | repo: "tahinli/forge".to_owned(), |
| 756 | clone_url: "https://forge.example/tahinli/forge.git".to_owned(), |
| 757 | commit: "a".repeat(40), |
| 758 | git_ref: "refs/heads/main".to_owned(), |
| 759 | job_name: "build".to_owned(), |
| 760 | image: "docker.io/library/alpine:3".to_owned(), |
| 761 | run: "true".to_owned(), |
| 762 | env: BTreeMap::new(), |
| 763 | secrets: BTreeMap::new(), |
| 764 | artifacts: Vec::new(), |
| 765 | timeout_minutes: 5, |
| 766 | network: false, |
| 767 | cache: cache.iter().map(|s| (*s).to_owned()).collect(), |
| 768 | cache_key: key.to_owned(), |
| 769 | cache_restore_keys: restore.iter().map(|s| (*s).to_owned()).collect(), |
| 770 | memory_bytes: None, |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | fn store(dir: &Path, max_bytes: u64) -> CacheStore { |
| 775 | CacheStore::new( |
| 776 | dir.join(".cache"), |
| 777 | max_bytes, |
| 778 | IdMap::single(), |
| 779 | PathBuf::from("/unused-helper"), |
| 780 | ) |
| 781 | } |
| 782 | |
| 783 | |
| 784 | fn workspace(dir: &Path, name: &str, body: &str) -> PathBuf { |
| 785 | let ws = dir.join(name); |
| 786 | fs::create_dir_all(ws.join("target")).expect("mkdir"); |
| 787 | fs::write(ws.join("target/a.txt"), body).expect("write"); |
| 788 | ws |
| 789 | } |
| 790 | |
| 791 | fn empty_workspace(dir: &Path, name: &str) -> PathBuf { |
| 792 | let ws = dir.join(name); |
| 793 | fs::create_dir_all(&ws).expect("mkdir"); |
| 794 | ws |
| 795 | } |
| 796 | |
| 797 | fn entry_of(store: &CacheStore, key: &str) -> PathBuf { |
| 798 | store.entry_dir("tahinli/forge", "build", key) |
| 799 | } |
| 800 | |
| 801 | fn read(path: &Path) -> String { |
| 802 | fs::read_to_string(path).expect("read") |
| 803 | } |
| 804 | |
| 805 | #[tokio::test] |
| 806 | async fn hit_moves_the_entry_and_hides_it_while_in_use() { |
| 807 | let dir = tempfile::tempdir().expect("tempdir"); |
| 808 | let store = store(dir.path(), 1 << 30); |
| 809 | let first = job("job_a", "ref:refs/heads/main", &[], &["target"]); |
| 810 | let ws1 = workspace(dir.path(), "ws_a", "one"); |
| 811 | let saved = store.save(&first, Outcome::Success, &ws1).await; |
| 812 | assert!( |
| 813 | saved.iter().any(|l| l.starts_with("runner: cache saved")), |
| 814 | "{saved:?}" |
| 815 | ); |
| 816 | assert!(!ws1.join("target").exists(), "save moves the path out"); |
| 817 | |
| 818 | let second = job("job_b", "ref:refs/heads/main", &[], &["target"]); |
| 819 | let ws2 = empty_workspace(dir.path(), "ws_b"); |
| 820 | let lines = store.restore(&second, &ws2).await; |
| 821 | assert!( |
| 822 | lines |
| 823 | .iter() |
| 824 | .any(|l| l.starts_with("runner: cache hit ref:refs/heads/main")), |
| 825 | "{lines:?}" |
| 826 | ); |
| 827 | assert_eq!(read(&ws2.join("target/a.txt")), "one"); |
| 828 | assert!( |
| 829 | !entry_of(&store, "ref:refs/heads/main").exists(), |
| 830 | "a hit moves the entry" |
| 831 | ); |
| 832 | assert!(store.root.join(".inuse-job_b").is_dir()); |
| 833 | |
| 834 | |
| 835 | let third = job("job_c", "ref:refs/heads/main", &[], &["target"]); |
| 836 | let ws3 = empty_workspace(dir.path(), "ws_c"); |
| 837 | assert_eq!( |
| 838 | store.restore(&third, &ws3).await, |
| 839 | vec!["runner: cache miss".to_owned()] |
| 840 | ); |
| 841 | assert!(!ws3.join("target").exists()); |
| 842 | |
| 843 | |
| 844 | store.save(&second, Outcome::Success, &ws2).await; |
| 845 | assert!(!store.root.join(".inuse-job_b").exists()); |
| 846 | assert!(entry_of(&store, "ref:refs/heads/main").is_dir()); |
| 847 | } |
| 848 | |
| 849 | #[tokio::test] |
| 850 | async fn fallback_copies_and_leaves_the_fallback_entry() { |
| 851 | let dir = tempfile::tempdir().expect("tempdir"); |
| 852 | let store = store(dir.path(), 1 << 30); |
| 853 | let main = job("job_a", "ref:refs/heads/main", &[], &["target"]); |
| 854 | store |
| 855 | .save( |
| 856 | &main, |
| 857 | Outcome::Success, |
| 858 | &workspace(dir.path(), "ws_a", "main"), |
| 859 | ) |
| 860 | .await; |
| 861 | |
| 862 | let pr = job("job_b", "pr:12", &["ref:refs/heads/main"], &["target"]); |
| 863 | let ws = empty_workspace(dir.path(), "ws_b"); |
| 864 | let lines = store.restore(&pr, &ws).await; |
| 865 | assert!( |
| 866 | lines.contains(&"runner: cache restored from fallback ref:refs/heads/main".to_owned()), |
| 867 | "{lines:?}" |
| 868 | ); |
| 869 | assert_eq!(read(&ws.join("target/a.txt")), "main"); |
| 870 | assert_eq!( |
| 871 | read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")), |
| 872 | "main" |
| 873 | ); |
| 874 | } |
| 875 | |
| 876 | #[tokio::test] |
| 877 | async fn save_replaces_the_entry_and_leaves_no_scratch() { |
| 878 | let dir = tempfile::tempdir().expect("tempdir"); |
| 879 | let store = store(dir.path(), 1 << 30); |
| 880 | let first = job("job_1", "ref:refs/heads/main", &[], &["target"]); |
| 881 | store |
| 882 | .save( |
| 883 | &first, |
| 884 | Outcome::Success, |
| 885 | &workspace(dir.path(), "ws1", "v1"), |
| 886 | ) |
| 887 | .await; |
| 888 | let second = job("job_2", "ref:refs/heads/main", &[], &["target"]); |
| 889 | store |
| 890 | .save( |
| 891 | &second, |
| 892 | Outcome::Failure, |
| 893 | &workspace(dir.path(), "ws2", "v2"), |
| 894 | ) |
| 895 | .await; |
| 896 | |
| 897 | let entry = entry_of(&store, "ref:refs/heads/main"); |
| 898 | assert_eq!(read(&entry.join("p0/a.txt")), "v2"); |
| 899 | let names: Vec<String> = fs::read_dir(&store.root) |
| 900 | .expect("read_dir") |
| 901 | .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) |
| 902 | .collect(); |
| 903 | assert_eq!( |
| 904 | names, |
| 905 | vec![ |
| 906 | entry |
| 907 | .file_name() |
| 908 | .expect("name") |
| 909 | .to_string_lossy() |
| 910 | .into_owned() |
| 911 | ] |
| 912 | ); |
| 913 | } |
| 914 | |
| 915 | #[tokio::test] |
| 916 | async fn save_never_writes_restore_keys() { |
| 917 | let dir = tempfile::tempdir().expect("tempdir"); |
| 918 | let store = store(dir.path(), 1 << 30); |
| 919 | let main = job("job_m", "ref:refs/heads/main", &[], &["target"]); |
| 920 | store |
| 921 | .save( |
| 922 | &main, |
| 923 | Outcome::Success, |
| 924 | &workspace(dir.path(), "ws_m", "main"), |
| 925 | ) |
| 926 | .await; |
| 927 | |
| 928 | let pr = job("job_p", "pr:12", &["ref:refs/heads/main"], &["target"]); |
| 929 | store |
| 930 | .save(&pr, Outcome::Success, &workspace(dir.path(), "ws_p", "pr")) |
| 931 | .await; |
| 932 | assert_eq!(read(&entry_of(&store, "pr:12").join("p0/a.txt")), "pr"); |
| 933 | assert_eq!( |
| 934 | read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")), |
| 935 | "main" |
| 936 | ); |
| 937 | |
| 938 | |
| 939 | let none = job("job_n", "", &["ref:refs/heads/main"], &["target"]); |
| 940 | store |
| 941 | .save( |
| 942 | &none, |
| 943 | Outcome::Success, |
| 944 | &workspace(dir.path(), "ws_n", "none"), |
| 945 | ) |
| 946 | .await; |
| 947 | assert_eq!( |
| 948 | read(&entry_of(&store, "ref:refs/heads/main").join("p0/a.txt")), |
| 949 | "main" |
| 950 | ); |
| 951 | } |
| 952 | |
| 953 | #[tokio::test] |
| 954 | async fn cancelled_or_errored_runs_do_not_save() { |
| 955 | let dir = tempfile::tempdir().expect("tempdir"); |
| 956 | let store = store(dir.path(), 1 << 30); |
| 957 | let j = job("job_x", "ref:refs/heads/main", &[], &["target"]); |
| 958 | for outcome in [Outcome::Cancelled, Outcome::Error] { |
| 959 | let ws = workspace(dir.path(), &format!("ws_{outcome:?}"), "x"); |
| 960 | let lines = store.save(&j, outcome, &ws).await; |
| 961 | assert!(lines.is_empty(), "{lines:?}"); |
| 962 | assert!( |
| 963 | ws.join("target/a.txt").exists(), |
| 964 | "the files stay in the workspace" |
| 965 | ); |
| 966 | } |
| 967 | assert!(!entry_of(&store, "ref:refs/heads/main").exists()); |
| 968 | } |
| 969 | |
| 970 | #[tokio::test] |
| 971 | async fn eviction_removes_the_least_recently_saved_entry() { |
| 972 | let dir = tempfile::tempdir().expect("tempdir"); |
| 973 | |
| 974 | let store = store(dir.path(), 2500); |
| 975 | for key in ["k1", "k2", "k3"] { |
| 976 | let ws = dir.path().join(format!("ws_{key}")); |
| 977 | fs::create_dir_all(ws.join("target")).expect("mkdir"); |
| 978 | fs::write(ws.join("target/data.bin"), vec![b'x'; 1000]).expect("write"); |
| 979 | let j = job(&format!("job_{key}"), key, &[], &["target"]); |
| 980 | store.save(&j, Outcome::Success, &ws).await; |
| 981 | } |
| 982 | assert!(!entry_of(&store, "k1").exists(), "the oldest goes first"); |
| 983 | assert!(entry_of(&store, "k2").is_dir()); |
| 984 | assert!(entry_of(&store, "k3").is_dir()); |
| 985 | } |
| 986 | |
| 987 | #[test] |
| 988 | fn cache_paths_are_checked_again_on_the_runner() { |
| 989 | let bad = [ |
| 990 | "../x", |
| 991 | "a/../b", |
| 992 | "/etc", |
| 993 | "", |
| 994 | ".", |
| 995 | "a//b", |
| 996 | "target/", |
| 997 | ".git", |
| 998 | "a/.git/b", |
| 999 | "a/./b", |
| 1000 | "x\\y", |
| 1001 | "a\0b", |
| 1002 | ".GIT/config", |
| 1003 | ]; |
| 1004 | for path in bad { |
| 1005 | assert!(validate_path(path).is_err(), "{path:?} must be refused"); |
| 1006 | } |
| 1007 | assert_eq!( |
| 1008 | validate_path("target").expect("ok"), |
| 1009 | PathBuf::from("target") |
| 1010 | ); |
| 1011 | assert_eq!( |
| 1012 | validate_path("web/node_modules").expect("ok"), |
| 1013 | PathBuf::from("web/node_modules") |
| 1014 | ); |
| 1015 | assert!(validate_paths(&["target".to_owned(), "target/debug".to_owned()]).is_err()); |
| 1016 | } |
| 1017 | |
| 1018 | #[tokio::test] |
| 1019 | async fn a_symlinked_parent_is_refused_and_not_followed() { |
| 1020 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1021 | let store = store(dir.path(), 1 << 30); |
| 1022 | let outside = dir.path().join("outside"); |
| 1023 | fs::create_dir_all(&outside).expect("mkdir"); |
| 1024 | |
| 1025 | let ws1 = dir.path().join("ws1"); |
| 1026 | fs::create_dir_all(ws1.join("build/out")).expect("mkdir"); |
| 1027 | fs::write(ws1.join("build/out/f"), "x").expect("write"); |
| 1028 | let first = job("job_1", "ref:main", &[], &["build/out"]); |
| 1029 | store.save(&first, Outcome::Success, &ws1).await; |
| 1030 | |
| 1031 | |
| 1032 | let ws2 = empty_workspace(dir.path(), "ws2"); |
| 1033 | symlink(&outside, ws2.join("build")).expect("symlink"); |
| 1034 | let second = job("job_2", "ref:main", &[], &["build/out"]); |
| 1035 | let lines = store.restore(&second, &ws2).await; |
| 1036 | assert!( |
| 1037 | lines |
| 1038 | .iter() |
| 1039 | .any(|l| l.contains("build/out") && l.contains("failed")), |
| 1040 | "{lines:?}" |
| 1041 | ); |
| 1042 | assert!( |
| 1043 | !outside.join("out").exists(), |
| 1044 | "restore must not write through the symlink" |
| 1045 | ); |
| 1046 | |
| 1047 | |
| 1048 | fs::create_dir_all(outside.join("out")).expect("mkdir"); |
| 1049 | let ws3 = empty_workspace(dir.path(), "ws3"); |
| 1050 | symlink(&outside, ws3.join("build")).expect("symlink"); |
| 1051 | let third = job("job_3", "pr:9", &[], &["build/out"]); |
| 1052 | let lines = store.save(&third, Outcome::Success, &ws3).await; |
| 1053 | assert!(lines.iter().any(|l| l.contains("skipped")), "{lines:?}"); |
| 1054 | assert!( |
| 1055 | outside.join("out").is_dir(), |
| 1056 | "save must not move through the symlink" |
| 1057 | ); |
| 1058 | } |
| 1059 | |
| 1060 | #[tokio::test] |
| 1061 | async fn stale_scratch_dirs_are_removed_at_startup() { |
| 1062 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1063 | let store = store(dir.path(), 1 << 30); |
| 1064 | for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] { |
| 1065 | let path = store.root.join(name); |
| 1066 | fs::create_dir_all(&path).expect("mkdir"); |
| 1067 | fs::write(path.join("f"), "x").expect("write"); |
| 1068 | } |
| 1069 | let keep = entry_of(&store, "ref:main"); |
| 1070 | fs::create_dir_all(&keep).expect("mkdir"); |
| 1071 | |
| 1072 | store.sweep_stale().await.expect("sweep"); |
| 1073 | for name in [".inuse-crashed", ".new-crashed", ".old-crashed"] { |
| 1074 | assert!(!store.root.join(name).exists(), "{name} must be removed"); |
| 1075 | } |
| 1076 | assert!(keep.is_dir(), "entries are kept"); |
| 1077 | } |
| 1078 | } |