1use fs2::FileExt as _;
2use std::{
3 fs::{self, File},
4 io::{self, Read as _},
5 path::{Path, PathBuf},
6 sync::Arc,
7 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
8};
9
10use super::digest::read_stamp_with_limit;
11
12pub(super) fn canonicalize_allow_missing(path: &Path) -> io::Result<PathBuf> {
15 let base = if path.is_absolute() {
16 PathBuf::new()
17 } else {
18 std::env::current_dir()?
19 };
20 ic_host_fs::path::canonicalize_allow_missing(path, &base)
21}
22
23const CACHE_DIRECTORY_TAG: &str = "Signature: 8a477f597d28d172789f06886806bc55\n\
24# This file is a cache directory tag created by ic-testkit.\n\
25# For information about cache directory tags see https://bford.info/cachedir/\n";
26pub(super) const CACHE_DIRECTORY_TAG_SIGNATURE: &str =
27 "Signature: 8a477f597d28d172789f06886806bc55";
28pub(super) const LAST_USED_FILE: &str = ".ic-testkit-last-used";
29const LAST_MAINTENANCE_FILE: &str = ".ic-testkit-last-maintenance";
30const MAX_TIMESTAMP_BYTES: usize = 39;
32pub(super) const RETENTION_LOCK_FILE: &str = ".ic-testkit-retention-v1";
33
34#[derive(Clone, Debug)]
37pub(super) struct RetainedCacheEntry {
38 path: PathBuf,
39 _lock: Arc<RetentionLock>,
40}
41
42#[derive(Debug)]
43struct RetentionLock(File);
44
45impl Drop for RetentionLock {
46 fn drop(&mut self) {
47 let _ = fs2::FileExt::unlock(&self.0);
52 }
53}
54
55impl PartialEq for RetainedCacheEntry {
56 fn eq(&self, other: &Self) -> bool {
57 self.path == other.path
58 }
59}
60
61impl Eq for RetainedCacheEntry {}
62
63impl RetainedCacheEntry {
64 pub(super) fn path(&self) -> &Path {
65 &self.path
66 }
67
68 pub(super) fn acquire(path: &Path) -> Result<Self, CacheFsError> {
69 let file = open_cache_lock_file(&path.join(RETENTION_LOCK_FILE))?;
70 fs2::FileExt::lock_shared(&file).map_err(|source| CacheFsError {
71 operation: "retain cache entry",
72 path: path.to_owned(),
73 source,
74 })?;
75 Ok(Self {
76 path: path.to_owned(),
77 _lock: Arc::new(RetentionLock(file)),
78 })
79 }
80}
81
82pub(super) fn remove_unretained_entry(path: &Path) -> Result<(), CacheFsError> {
84 let metadata = match fs::symlink_metadata(path) {
85 Ok(metadata) => metadata,
86 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
87 Err(source) => {
88 return Err(CacheFsError {
89 operation: "inspect cache entry",
90 path: path.to_owned(),
91 source,
92 });
93 }
94 };
95 if !metadata.is_dir() {
96 return remove_path_if_present(path).map_err(|source| CacheFsError {
97 operation: "remove invalid cache entry",
98 path: path.to_owned(),
99 source,
100 });
101 }
102 let _lock =
103 try_lock_cache_file(&path.join(RETENTION_LOCK_FILE))?.ok_or_else(|| CacheFsError {
104 operation: "replace retained cache entry",
105 path: path.to_owned(),
106 source: io::Error::new(
107 io::ErrorKind::WouldBlock,
108 "cache entry is retained by a consumer",
109 ),
110 })?;
111 remove_path_if_present(path).map_err(|source| CacheFsError {
112 operation: "remove cache entry",
113 path: path.to_owned(),
114 source,
115 })
116}
117
118#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
126pub struct ArtifactCachePrunePolicy {
127 max_age: Option<Duration>,
128 max_size_bytes: Option<u64>,
129}
130
131#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
133pub struct ArtifactCachePruneReport {
134 entries_scanned: usize,
135 entries_removed: usize,
136 bytes_before: u64,
137 bytes_removed: u64,
138 uncommitted_directories_removed: usize,
139 uncommitted_bytes_removed: u64,
140}
141
142#[non_exhaustive]
144#[derive(Clone, Debug, Eq, PartialEq)]
145pub enum ArtifactCacheMaintenance {
146 Pruned(ArtifactCachePruneReport),
148 PruneFailed {
150 message: String,
152 },
153}
154
155impl ArtifactCachePrunePolicy {
156 #[must_use]
158 pub const fn new() -> Self {
159 Self {
160 max_age: None,
161 max_size_bytes: None,
162 }
163 }
164
165 #[must_use]
167 pub const fn with_max_age(mut self, max_age: Duration) -> Self {
168 self.max_age = Some(max_age);
169 self
170 }
171
172 #[must_use]
174 pub const fn with_max_size_bytes(mut self, bytes: u64) -> Self {
175 self.max_size_bytes = Some(bytes);
176 self
177 }
178
179 #[must_use]
181 pub const fn max_age(self) -> Option<Duration> {
182 self.max_age
183 }
184
185 #[must_use]
187 pub const fn max_size_bytes(self) -> Option<u64> {
188 self.max_size_bytes
189 }
190
191 pub(super) fn maintenance_identity(self) -> String {
192 format!(
193 "age={:?};size={:?}",
194 self.max_age.map(|duration| duration.as_nanos()),
195 self.max_size_bytes
196 )
197 }
198}
199
200impl ArtifactCachePruneReport {
201 #[must_use]
203 pub const fn entries_scanned(self) -> usize {
204 self.entries_scanned
205 }
206
207 #[must_use]
209 pub const fn entries_removed(self) -> usize {
210 self.entries_removed
211 }
212
213 #[must_use]
215 pub const fn entries_retained(self) -> usize {
216 self.entries_scanned.saturating_sub(self.entries_removed)
217 }
218
219 #[must_use]
221 pub const fn bytes_before(self) -> u64 {
222 self.bytes_before
223 }
224
225 #[must_use]
227 pub const fn bytes_removed(self) -> u64 {
228 self.bytes_removed
229 }
230
231 #[must_use]
233 pub const fn bytes_retained(self) -> u64 {
234 self.bytes_before.saturating_sub(self.bytes_removed)
235 }
236
237 #[must_use]
239 pub const fn uncommitted_directories_removed(self) -> usize {
240 self.uncommitted_directories_removed
241 }
242
243 #[must_use]
245 pub const fn uncommitted_bytes_removed(self) -> u64 {
246 self.uncommitted_bytes_removed
247 }
248
249 pub(super) const fn record_uncommitted_removal(&mut self, bytes: u64) {
250 self.uncommitted_directories_removed += 1;
251 self.uncommitted_bytes_removed = self.uncommitted_bytes_removed.saturating_add(bytes);
252 }
253}
254
255impl ArtifactCacheMaintenance {
256 #[must_use]
258 pub const fn prune_report(&self) -> Option<ArtifactCachePruneReport> {
259 match self {
260 Self::Pruned(report) => Some(*report),
261 Self::PruneFailed { .. } => None,
262 }
263 }
264
265 #[must_use]
267 pub fn failure_message(&self) -> Option<&str> {
268 match self {
269 Self::Pruned(_) => None,
270 Self::PruneFailed { message } => Some(message),
271 }
272 }
273}
274
275#[derive(Debug)]
276pub(super) struct CacheFsError {
277 pub(super) operation: &'static str,
278 pub(super) path: PathBuf,
279 pub(super) source: io::Error,
280}
281
282pub(super) fn ensure_cache_directory_tag(cache_root: &Path) -> Result<(), CacheFsError> {
283 let path = cache_root.join("CACHEDIR.TAG");
284 let mut signature = [0_u8; CACHE_DIRECTORY_TAG_SIGNATURE.len()];
287 if fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.file_type().is_file())
288 && File::open(&path)
289 .and_then(|mut file| file.read_exact(&mut signature))
290 .is_ok()
291 && signature == CACHE_DIRECTORY_TAG_SIGNATURE.as_bytes()
292 {
293 return Ok(());
294 }
295 ic_host_fs::durable::write_bytes(&path, CACHE_DIRECTORY_TAG.as_bytes()).map_err(|source| {
296 CacheFsError {
297 operation: "write cache directory tag",
298 path,
299 source: io::Error::other(source),
300 }
301 })
302}
303
304pub(super) fn lock_cache_file(path: &Path) -> Result<(File, Duration), CacheFsError> {
305 let file = open_cache_lock_file(path)?;
306 let started = Instant::now();
307 file.lock_exclusive().map_err(|source| CacheFsError {
308 operation: "lock cache",
309 path: path.to_owned(),
310 source,
311 })?;
312 Ok((file, started.elapsed()))
313}
314
315pub(super) fn lock_cache_file_with_wait_observer(
316 path: &Path,
317 poll_interval: Duration,
318 mut observer: impl FnMut(Duration),
319) -> Result<(File, Duration), CacheFsError> {
320 let file = open_cache_lock_file(path)?;
321 let wait = ic_host_fs::durable::lock_exclusive_with_wait(
322 &file,
323 poll_interval.min(Duration::from_millis(25)),
324 |elapsed| {
325 observer(elapsed);
326 Ok(())
327 },
328 )
329 .map_err(|source| CacheFsError {
330 operation: "try lock cache",
331 path: path.to_owned(),
332 source,
333 })?;
334 Ok((file, wait))
335}
336
337pub(super) fn try_lock_cache_file(path: &Path) -> Result<Option<File>, CacheFsError> {
338 match ic_host_fs::durable::try_lock_regular_file_with_parents(path).map_err(io::Error::from) {
339 Ok(file) => Ok(Some(file)),
340 Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None),
341 Err(source) => Err(CacheFsError {
342 operation: "try lock cache",
343 path: path.to_owned(),
344 source,
345 }),
346 }
347}
348
349fn open_cache_lock_file(path: &Path) -> Result<File, CacheFsError> {
350 ic_host_fs::durable::open_regular_lock_file_with_parents(path)
351 .map_err(io::Error::from)
352 .map_err(|source| CacheFsError {
353 operation: "open cache lock",
354 path: path.to_owned(),
355 source,
356 })
357}
358
359pub(super) fn record_cache_entry_use(path: &Path) -> Result<(), CacheFsError> {
360 write_last_used(path, SystemTime::now())
361}
362
363pub(super) fn cache_maintenance_due(
364 path: &Path,
365 minimum_interval: Option<Duration>,
366 maintenance_identity: &str,
367) -> Result<bool, CacheFsError> {
368 let Some(minimum_interval) = minimum_interval else {
369 return Ok(true);
370 };
371 let marker = path.join(LAST_MAINTENANCE_FILE);
372 let maximum_len = MAX_TIMESTAMP_BYTES + maintenance_identity.len() + 4;
374 let contents = match read_stamp_with_limit(&marker, maximum_len) {
375 Ok(Some(contents)) => contents,
376 Ok(None) => return Ok(true),
377 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(true),
378 Err(source) => {
379 return Err(CacheFsError {
380 operation: "read cache maintenance time",
381 path: marker,
382 source,
383 });
384 }
385 };
386 let mut lines = contents.lines();
387 let Some(last_maintenance) = lines.next().and_then(decode_system_time) else {
388 return Ok(true);
389 };
390 if lines.next() != Some(maintenance_identity) {
391 return Ok(true);
392 }
393 Ok(match SystemTime::now().duration_since(last_maintenance) {
394 Ok(elapsed) => elapsed >= minimum_interval,
395 Err(_) => true,
396 })
397}
398
399pub(super) fn record_cache_maintenance(
400 path: &Path,
401 maintenance_identity: &str,
402) -> Result<(), CacheFsError> {
403 let marker = path.join(LAST_MAINTENANCE_FILE);
404 let elapsed = encode_system_time(&marker, SystemTime::now())?;
405 let contents = format!("{}\n{maintenance_identity}\n", elapsed.as_nanos());
406 ic_host_fs::durable::write_bytes(&marker, contents.as_bytes()).map_err(|source| CacheFsError {
407 operation: "record cache maintenance time",
408 path: marker,
409 source: io::Error::other(source),
410 })
411}
412
413pub(super) fn perform_scheduled_cache_maintenance(
414 path: &Path,
415 minimum_interval: Option<Duration>,
416 maintenance_identity: &str,
417 maintenance: impl FnOnce() -> Result<ArtifactCachePruneReport, String>,
418) -> (Option<ArtifactCacheMaintenance>, Option<Duration>) {
419 let started = Instant::now();
420 match cache_maintenance_due(path, minimum_interval, maintenance_identity) {
421 Ok(false) => return (None, Some(started.elapsed())),
422 Ok(true) => {}
423 Err(error) => {
424 return (
425 Some(ArtifactCacheMaintenance::PruneFailed {
426 message: error.to_string(),
427 }),
428 Some(started.elapsed()),
429 );
430 }
431 }
432
433 let result = maintenance();
434 let marker = record_cache_maintenance(path, maintenance_identity);
435 let outcome = match (result, marker) {
436 (Ok(report), Ok(())) => ArtifactCacheMaintenance::Pruned(report),
437 (Err(message), Ok(())) => ArtifactCacheMaintenance::PruneFailed { message },
438 (Ok(_), Err(error)) => ArtifactCacheMaintenance::PruneFailed {
439 message: error.to_string(),
440 },
441 (Err(message), Err(marker)) => ArtifactCacheMaintenance::PruneFailed {
442 message: format!(
443 "{message}; additionally failed to record the maintenance attempt: {marker}"
444 ),
445 },
446 };
447 (Some(outcome), Some(started.elapsed()))
448}
449
450pub(super) fn write_last_used(path: &Path, last_used: SystemTime) -> Result<(), CacheFsError> {
451 let marker = path.join(LAST_USED_FILE);
452 write_system_time(&marker, last_used, "record cache use time")
453}
454
455fn write_system_time(
456 path: &Path,
457 timestamp: SystemTime,
458 operation: &'static str,
459) -> Result<(), CacheFsError> {
460 let elapsed = encode_system_time(path, timestamp)?;
461 ic_host_fs::durable::write_bytes(path, elapsed.as_nanos().to_string().as_bytes()).map_err(
462 |source| CacheFsError {
463 operation,
464 path: path.to_owned(),
465 source: io::Error::other(source),
466 },
467 )
468}
469
470fn encode_system_time(path: &Path, timestamp: SystemTime) -> Result<Duration, CacheFsError> {
471 timestamp
472 .duration_since(UNIX_EPOCH)
473 .map_err(|source| CacheFsError {
474 operation: "encode cache time",
475 path: path.to_owned(),
476 source: io::Error::new(io::ErrorKind::InvalidInput, source),
477 })
478}
479
480fn decode_system_time(contents: &str) -> Option<SystemTime> {
481 let nanoseconds = contents.parse::<u128>().ok()?;
482 let seconds = u64::try_from(nanoseconds / 1_000_000_000).ok()?;
483 let subsecond_nanos = (nanoseconds % 1_000_000_000) as u32;
484 UNIX_EPOCH.checked_add(Duration::new(seconds, subsecond_nanos))
485}
486
487pub(super) fn prune_direct_child_directories(
488 cache_root: &Path,
489 policy: ArtifactCachePrunePolicy,
490 protected_entry: Option<&Path>,
491 is_eligible: impl Fn(&Path) -> bool,
492) -> Result<ArtifactCachePruneReport, CacheFsError> {
493 let mut entries = cache_entries(cache_root, is_eligible)?;
494 let bytes_before = entries
495 .iter()
496 .fold(0_u64, |total, entry| total.saturating_add(entry.bytes));
497 let mut report = ArtifactCachePruneReport {
498 entries_scanned: entries.len(),
499 entries_removed: 0,
500 bytes_before,
501 bytes_removed: 0,
502 uncommitted_directories_removed: 0,
503 uncommitted_bytes_removed: 0,
504 };
505 let now = SystemTime::now();
506
507 if let Some(max_age) = policy.max_age() {
508 for entry in &mut entries {
509 let age = now.duration_since(entry.last_used).unwrap_or_default();
510 if protected_entry != Some(entry.path.as_path()) && age > max_age {
511 remove_cache_entry(entry, &mut report)?;
512 }
513 }
514 }
515
516 if let Some(max_size_bytes) = policy.max_size_bytes()
517 && report.bytes_retained() > max_size_bytes
518 {
519 entries.sort_by(|left, right| {
520 left.last_used
521 .cmp(&right.last_used)
522 .then_with(|| left.path.cmp(&right.path))
523 });
524 for entry in &mut entries {
525 if report.bytes_retained() <= max_size_bytes {
526 break;
527 }
528 if protected_entry == Some(entry.path.as_path()) {
529 continue;
530 }
531 remove_cache_entry(entry, &mut report)?;
532 }
533 }
534
535 Ok(report)
536}
537
538pub(super) fn directory_logical_size(path: &Path) -> io::Result<u64> {
539 let mut total = 0_u64;
540 let mut pending = vec![path.to_owned()];
541 while let Some(current) = pending.pop() {
542 let metadata = fs::symlink_metadata(¤t)?;
543 if metadata.is_dir() {
544 for entry in fs::read_dir(¤t)? {
545 let path = entry?.path();
546 let metadata = fs::symlink_metadata(&path)?;
547 if metadata.is_dir() {
548 pending.push(path);
549 } else {
550 total = total.saturating_add(metadata.len());
551 }
552 }
553 } else {
554 total = total.saturating_add(metadata.len());
555 }
556 }
557 Ok(total)
558}
559
560pub(super) fn is_sha256_directory(path: &Path) -> bool {
561 path.file_name().is_some_and(|name| {
562 let bytes = name.as_encoded_bytes();
563 bytes.len() == 64 && bytes.iter().all(u8::is_ascii_hexdigit)
564 })
565}
566
567pub(super) fn remove_path_if_present(path: &Path) -> io::Result<()> {
568 let metadata = match fs::symlink_metadata(path) {
569 Ok(metadata) => metadata,
570 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
571 Err(error) => return Err(error),
572 };
573 if metadata.file_type().is_dir() {
574 fs::remove_dir_all(path)
575 } else {
576 fs::remove_file(path)
577 }
578}
579
580struct CacheEntry {
581 path: PathBuf,
582 bytes: u64,
583 last_used: SystemTime,
584 removed: bool,
585}
586
587impl std::fmt::Display for CacheFsError {
588 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
589 write!(
590 formatter,
591 "failed to {} at {}: {}",
592 self.operation,
593 self.path.display(),
594 self.source
595 )
596 }
597}
598
599impl std::error::Error for CacheFsError {
600 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
601 Some(&self.source)
602 }
603}
604
605fn cache_entries(
606 cache_root: &Path,
607 is_eligible: impl Fn(&Path) -> bool,
608) -> Result<Vec<CacheEntry>, CacheFsError> {
609 let read_dir = match fs::read_dir(cache_root) {
610 Ok(read_dir) => read_dir,
611 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
612 Err(source) => {
613 return Err(CacheFsError {
614 operation: "read cache directory",
615 path: cache_root.to_owned(),
616 source,
617 });
618 }
619 };
620 let mut entries = Vec::new();
621 for directory_entry in read_dir {
622 let directory_entry = directory_entry.map_err(|source| CacheFsError {
623 operation: "read cache entry",
624 path: cache_root.to_owned(),
625 source,
626 })?;
627 let path = directory_entry.path();
628 let file_type = directory_entry.file_type().map_err(|source| CacheFsError {
629 operation: "inspect cache entry",
630 path: path.clone(),
631 source,
632 })?;
633 if !file_type.is_dir() || !is_eligible(&path) {
634 continue;
635 }
636 let bytes = directory_logical_size(&path).map_err(|source| CacheFsError {
637 operation: "measure cache entry",
638 path: path.clone(),
639 source,
640 })?;
641 let last_used = cache_entry_last_used(&path).map_err(|source| CacheFsError {
642 operation: "read cache use time",
643 path: path.clone(),
644 source,
645 })?;
646 entries.push(CacheEntry {
647 path,
648 bytes,
649 last_used,
650 removed: false,
651 });
652 }
653 Ok(entries)
654}
655
656pub(super) fn cache_entry_last_used(path: &Path) -> io::Result<SystemTime> {
657 let marker = path.join(LAST_USED_FILE);
658 if let Ok(Some(contents)) = read_stamp_with_limit(&marker, MAX_TIMESTAMP_BYTES)
659 && let Some(timestamp) = decode_system_time(&contents)
660 {
661 return Ok(timestamp);
662 }
663 fs::metadata(path)?.modified()
664}
665
666fn remove_cache_entry(
667 entry: &mut CacheEntry,
668 report: &mut ArtifactCachePruneReport,
669) -> Result<(), CacheFsError> {
670 if entry.removed {
671 return Ok(());
672 }
673 let Some(_retention_lock) = try_lock_cache_file(&entry.path.join(RETENTION_LOCK_FILE))? else {
674 return Ok(());
675 };
676 remove_path_if_present(&entry.path).map_err(|source| CacheFsError {
677 operation: "prune cache entry",
678 path: entry.path.clone(),
679 source,
680 })?;
681 entry.removed = true;
682 report.entries_removed += 1;
683 report.bytes_removed = report.bytes_removed.saturating_add(entry.bytes);
684 Ok(())
685}
686
687#[cfg(test)]
688mod tests {
689 use super::directory_logical_size;
690 use crate::artifacts::test_support::unique_temp_directory;
691 use std::{
692 fs,
693 time::{Duration, SystemTime, UNIX_EPOCH},
694 };
695
696 #[cfg(unix)]
697 #[test]
698 fn cache_lock_admission_preserves_bytes_and_returns_an_unlocked_close_on_exec_file() {
699 use std::os::fd::AsRawFd as _;
700
701 let root = unique_temp_directory("cache-lock-admission");
702 let path = root.join("nested/lock");
703 let file = super::open_cache_lock_file(&path).unwrap();
704 assert!(super::try_lock_cache_file(&path).unwrap().is_some());
705 let flags = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFD) };
707 assert!(flags >= 0);
708 assert_ne!(flags & libc::FD_CLOEXEC, 0);
709 drop(file);
710 fs::write(&path, b"retained lock bytes").unwrap();
711 drop(super::lock_cache_file(&path).unwrap());
712 assert_eq!(fs::read(&path).unwrap(), b"retained lock bytes");
713 fs::remove_dir_all(root).unwrap();
714 }
715
716 #[cfg(unix)]
717 #[test]
718 fn cache_lock_callers_refuse_redirected_final_entries() {
719 use std::os::unix::fs::symlink;
720
721 let root = unique_temp_directory("cache-lock-redirected");
722 let target = root.join("target");
723 fs::write(&target, b"target bytes").unwrap();
724 let redirected = root.join("redirected");
725 symlink(&target, &redirected).unwrap();
726 for result in [
727 super::open_cache_lock_file(&redirected),
728 super::lock_cache_file(&redirected).map(|(file, _)| file),
729 super::lock_cache_file_with_wait_observer(
730 &redirected,
731 Duration::from_millis(5),
732 |_| panic!("redirected lock reached acquisition"),
733 )
734 .map(|(file, _)| file),
735 ] {
736 let error = result.unwrap_err();
737 assert_eq!(error.path, redirected);
738 assert!(matches!(
739 error.source.get_ref().and_then(|cause| cause
740 .downcast_ref::<ic_host_fs::durable::RegularFileLockError>(
741 )),
742 Some(ic_host_fs::durable::RegularFileLockError::NotRegular)
743 ));
744 }
745 symlink(&target, root.join(super::RETENTION_LOCK_FILE)).unwrap();
746 assert!(super::RetainedCacheEntry::acquire(&root).is_err());
747 assert_eq!(fs::read(&target).unwrap(), b"target bytes");
748 fs::remove_dir_all(root).unwrap();
749 }
750
751 #[cfg(unix)]
752 #[test]
753 fn nonblocking_cache_locks_preserve_contention_and_reject_redirected_files() {
754 use std::{os::unix::fs::symlink, process::Command};
755 const CHILD_ENV: &str = "IC_TESTKIT_NONBLOCKING_CACHE_LOCK_CHILD";
756
757 if std::env::var_os(CHILD_ENV).is_none() {
758 let thread = std::thread::current();
762 let test_name = thread.name().expect("libtest names each test thread");
763 let output = Command::new(std::env::current_exe().unwrap())
764 .args(["--exact", test_name, "--test-threads=1"])
765 .env(CHILD_ENV, "1")
766 .output()
767 .unwrap();
768 assert!(
769 output.status.success(),
770 "isolated nonblocking cache lock test failed: {}{}",
771 String::from_utf8_lossy(&output.stdout),
772 String::from_utf8_lossy(&output.stderr)
773 );
774 return;
775 }
776
777 let root = unique_temp_directory("nonblocking-cache-lock-admission");
778 let lock_path = root.join("lock");
779 fs::write(&lock_path, b"existing lock bytes").unwrap();
780 let held = super::try_lock_cache_file(&lock_path).unwrap().unwrap();
781 assert!(super::try_lock_cache_file(&lock_path).unwrap().is_none());
782 assert_eq!(fs::read(&lock_path).unwrap(), b"existing lock bytes");
783 drop(held);
784 assert!(super::try_lock_cache_file(&lock_path).unwrap().is_some());
785
786 let redirected = root.join("redirected-lock");
787 symlink(&lock_path, &redirected).unwrap();
788 let error = super::try_lock_cache_file(&redirected).unwrap_err();
789 assert_eq!(error.path, redirected);
790 assert!(matches!(
791 error.source.get_ref().and_then(|cause| cause
792 .downcast_ref::<ic_host_fs::durable::RegularFileLockError>(
793 )),
794 Some(ic_host_fs::durable::RegularFileLockError::NotRegular)
795 ));
796 assert_eq!(fs::read(&lock_path).unwrap(), b"existing lock bytes");
797 fs::remove_dir_all(root).unwrap();
798 }
799
800 #[cfg(unix)]
801 #[test]
802 fn final_retention_owner_releases_lock_with_a_duplicate_descriptor_open() {
803 let root = unique_temp_directory("retention-duplicate-descriptor");
804 let retained = super::RetainedCacheEntry::acquire(&root).unwrap();
805 let inherited = retained._lock.0.try_clone().unwrap();
807 let clone = retained.clone();
808 let independently_retained = super::RetainedCacheEntry::acquire(&root).unwrap();
809 let lock_path = root.join(super::RETENTION_LOCK_FILE);
810 let available = || super::try_lock_cache_file(&lock_path).unwrap().is_some();
811 drop(retained);
812 assert!(!available(), "a record clone still retains the entry");
813 drop(clone);
814 assert!(
815 !available(),
816 "an independent acquisition still retains the entry"
817 );
818 drop(independently_retained);
819 assert!(
820 available(),
821 "descriptor duplication must not extend record ownership"
822 );
823 drop(inherited);
824 fs::remove_dir_all(root).unwrap();
825 }
826
827 #[test]
828 fn last_use_markers_preserve_timestamps_and_bounded_fallbacks() {
829 let root = unique_temp_directory("bounded-last-use-marker");
830 let marker = root.join(super::LAST_USED_FILE);
831 let modified = || fs::metadata(&root).unwrap().modified().unwrap();
832 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
833 for timestamp in [
834 UNIX_EPOCH + Duration::from_nanos(123),
835 SystemTime::now() + Duration::from_secs(3600),
836 ] {
837 super::write_last_used(&root, timestamp).unwrap();
838 assert_eq!(super::cache_entry_last_used(&root).unwrap(), timestamp);
839 }
840 let overflowing_timestamp = u128::MAX.to_string();
841 for invalid in [
842 b"invalid".as_slice(),
843 overflowing_timestamp.as_bytes(),
844 &[0xff],
845 ] {
846 fs::write(&marker, invalid).unwrap();
847 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
848 }
849 fs::File::create(&marker)
850 .unwrap()
851 .set_len(1024 * 1024 * 1024)
852 .unwrap();
853 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
854 fs::remove_file(&marker).unwrap();
855 fs::create_dir(&marker).unwrap();
856 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
857 fs::remove_dir_all(root).unwrap();
858 }
859
860 #[test]
861 fn maintenance_markers_preserve_policy_intervals_and_read_errors() {
862 let root = unique_temp_directory("bounded-maintenance-marker");
863 let marker = root.join(super::LAST_MAINTENANCE_FILE);
864 let identity = super::ArtifactCachePrunePolicy::new().maintenance_identity();
865 let interval = Some(Duration::from_secs(3600));
866 let due = || super::cache_maintenance_due(&root, interval, &identity).unwrap();
867 assert!(due());
868 super::record_cache_maintenance(&root, &identity).unwrap();
869 assert!(!due());
870 assert!(super::cache_maintenance_due(&root, interval, "other-policy").unwrap());
871 assert!(super::cache_maintenance_due(&root, Some(Duration::ZERO), &identity).unwrap());
872
873 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
874 for suffix in ["", "\r\n"] {
875 fs::write(&marker, format!("{}\r\n{identity}{suffix}", now.as_nanos())).unwrap();
876 assert!(!due());
877 }
878 for timestamp in [
879 "invalid".to_owned(),
880 "0".to_owned(),
881 (now + Duration::from_secs(3600)).as_nanos().to_string(),
882 ] {
883 fs::write(&marker, format!("{timestamp}\n{identity}\n")).unwrap();
884 assert!(due());
885 }
886 super::record_cache_maintenance(&root, &identity).unwrap();
887 fs::OpenOptions::new()
888 .write(true)
889 .open(&marker)
890 .unwrap()
891 .set_len(1024 * 1024 * 1024)
892 .unwrap();
893 assert!(due());
894
895 fs::write(&marker, [0xff]).unwrap();
896 let error = super::cache_maintenance_due(&root, interval, &identity).unwrap_err();
897 assert_eq!(error.operation, "read cache maintenance time");
898 assert_eq!(error.path, marker);
899 assert_eq!(error.source.kind(), std::io::ErrorKind::InvalidData);
900 fs::remove_file(&marker).unwrap();
901 fs::create_dir(&marker).unwrap();
902 assert!(super::cache_maintenance_due(&root, interval, &identity).is_err());
903 assert!(super::cache_maintenance_due(&root, None, &identity).unwrap());
904 fs::remove_dir_all(root).unwrap();
905 }
906
907 #[test]
908 fn cache_directory_tags_preserve_valid_standard_signatures() {
909 let root = unique_temp_directory("cache-tag-signatures");
910 let tag = root.join("CACHEDIR.TAG");
911 let signature = "Signature: 8a477f597d28d172789f06886806bc55";
912 for contents in [
913 signature.to_owned(),
914 format!("{signature}\r\n# Created by another application\r\n"),
915 format!("{signature}\n# {}\n", "comment".repeat(100_000)),
916 ] {
917 fs::write(&tag, &contents).unwrap();
918 super::ensure_cache_directory_tag(&root).unwrap();
919 assert_eq!(fs::read_to_string(&tag).unwrap(), contents);
920 }
921 for invalid in ["", &signature[..42], "Signature: incorrect"] {
922 fs::write(&tag, invalid).unwrap();
923 super::ensure_cache_directory_tag(&root).unwrap();
924 assert_eq!(
925 fs::read_to_string(&tag).unwrap(),
926 super::CACHE_DIRECTORY_TAG
927 );
928 }
929 fs::remove_dir_all(root).unwrap();
930 }
931
932 #[test]
933 #[cfg(unix)]
934 fn cache_directory_tag_replaces_symlinks_without_changing_referents() {
935 let root = unique_temp_directory("cache-tag-symlink");
936 let referent = root.join("other-application-tag");
937 let contents = "Signature: 8a477f597d28d172789f06886806bc55\n# Preserve this file\n";
938 fs::write(&referent, contents).unwrap();
939 let tag = root.join("CACHEDIR.TAG");
940 std::os::unix::fs::symlink(&referent, &tag).unwrap();
941 super::ensure_cache_directory_tag(&root).unwrap();
942 assert!(fs::symlink_metadata(&tag).unwrap().file_type().is_file());
943 assert_eq!(fs::read_to_string(&referent).unwrap(), contents);
944 assert_eq!(
945 fs::read_to_string(&tag).unwrap(),
946 super::CACHE_DIRECTORY_TAG
947 );
948
949 fs::remove_file(&tag).unwrap();
950 fs::create_dir(&tag).unwrap();
951 let error = super::ensure_cache_directory_tag(&root).unwrap_err();
952 assert!(matches!(
953 error
954 .source
955 .get_ref()
956 .unwrap()
957 .downcast_ref::<ic_host_fs::durable::NamedWriteError<std::io::Error>>()
958 .unwrap(),
959 ic_host_fs::durable::NamedWriteError::BeforePublication {
960 cleanup_error: None,
961 ..
962 }
963 ));
964 assert_eq!(error.operation, "write cache directory tag");
965 assert!(tag.is_dir());
966 fs::remove_dir_all(root).unwrap();
967 }
968
969 #[test]
970 fn directory_size_sums_wide_and_nested_files() {
971 let root = unique_temp_directory("directory-logical-size");
972 assert_eq!(directory_logical_size(&root).unwrap(), 0);
973 fs::create_dir_all(root.join("wide")).unwrap();
974 fs::create_dir_all(root.join("nested/deep/empty")).unwrap();
975 let mut expected = 0;
976 for index in 0..128 {
977 let bytes = vec![42; index % 13];
978 fs::write(root.join("wide").join(index.to_string()), &bytes).unwrap();
979 expected += bytes.len() as u64;
980 }
981 let sparse = root.join("nested/deep/sparse");
982 fs::File::create(&sparse)
983 .unwrap()
984 .set_len(1024 * 1024)
985 .unwrap();
986 assert_eq!(directory_logical_size(&sparse).unwrap(), 1024 * 1024);
987 assert_eq!(
988 directory_logical_size(&root).unwrap(),
989 expected + 1024 * 1024
990 );
991 assert_eq!(
992 directory_logical_size(&root.join("missing"))
993 .unwrap_err()
994 .kind(),
995 std::io::ErrorKind::NotFound,
996 );
997 fs::remove_dir_all(root).unwrap();
998 }
999
1000 #[test]
1001 #[cfg(unix)]
1002 fn directory_size_counts_symlinks_without_following_them() {
1003 let root = unique_temp_directory("directory-size-symlinks");
1004 let walked = root.join("walked");
1005 fs::create_dir_all(&walked).unwrap();
1006 fs::create_dir_all(root.join("external")).unwrap();
1007 fs::write(root.join("external/payload"), vec![42; 4096]).unwrap();
1008 fs::write(root.join("outside-file"), vec![42; 4096]).unwrap();
1009 fs::write(walked.join("payload"), b"abc").unwrap();
1010 let targets = ["../external", "../outside-file", "missing", "."];
1011 for (index, target) in targets.iter().enumerate() {
1012 std::os::unix::fs::symlink(target, walked.join(index.to_string())).unwrap();
1013 }
1014 let expected = 3 + targets
1015 .iter()
1016 .map(|target| target.len() as u64)
1017 .sum::<u64>();
1018 assert_eq!(directory_logical_size(&walked).unwrap(), expected);
1019 assert_eq!(
1020 directory_logical_size(&walked.join("0")).unwrap(),
1021 targets[0].len() as u64,
1022 );
1023 fs::remove_dir_all(root).unwrap();
1024 }
1025}