xref: /wasmtime-44.0.1/crates/cache/src/worker.rs (revision 08b7c877)
1 //! Background worker that watches over the cache.
2 //!
3 //! It cleans up old cache, updates statistics and optimizes the cache.
4 //! We allow losing some messages (it doesn't hurt) and some races,
5 //! but we guarantee eventual consistency and fault tolerancy.
6 //! Background tasks can be CPU intensive, but the worker thread has low priority.
7 
8 use super::{fs_write_atomic, CacheConfig};
9 use log::{debug, info, trace, warn};
10 use serde::{Deserialize, Serialize};
11 use std::cmp;
12 use std::collections::HashMap;
13 use std::ffi::OsStr;
14 use std::fmt;
15 use std::fs;
16 use std::path::{Path, PathBuf};
17 use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
18 #[cfg(test)]
19 use std::sync::{Arc, Condvar, Mutex};
20 use std::thread;
21 use std::time::Duration;
22 #[cfg(not(test))]
23 use std::time::SystemTime;
24 #[cfg(test)]
25 use tests::system_time_stub::SystemTimeStub as SystemTime;
26 
27 #[derive(Clone)]
28 pub(super) struct Worker {
29     sender: SyncSender<CacheEvent>,
30     #[cfg(test)]
31     stats: Arc<(Mutex<WorkerStats>, Condvar)>,
32 }
33 
34 struct WorkerThread {
35     receiver: Receiver<CacheEvent>,
36     cache_config: CacheConfig,
37     #[cfg(test)]
38     stats: Arc<(Mutex<WorkerStats>, Condvar)>,
39 }
40 
41 #[cfg(test)]
42 #[derive(Default)]
43 struct WorkerStats {
44     dropped: u32,
45     sent: u32,
46     handled: u32,
47 }
48 
49 #[derive(Debug, Clone)]
50 enum CacheEvent {
51     OnCacheGet(PathBuf),
52     OnCacheUpdate(PathBuf),
53 }
54 
55 impl Worker {
56     pub(super) fn start_new(
57         cache_config: &CacheConfig,
58         init_file_per_thread_logger: Option<&'static str>,
59     ) -> Self {
60         let queue_size = match cache_config.worker_event_queue_size() {
61             num if num <= usize::max_value() as u64 => num as usize,
62             _ => usize::max_value(),
63         };
64         let (tx, rx) = sync_channel(queue_size);
65 
66         #[cfg(test)]
67         let stats = Arc::new((Mutex::new(WorkerStats::default()), Condvar::new()));
68 
69         let worker_thread = WorkerThread {
70             receiver: rx,
71             cache_config: cache_config.clone(),
72             #[cfg(test)]
73             stats: stats.clone(),
74         };
75 
76         // when self is dropped, sender will be dropped, what will cause the channel
77         // to hang, and the worker thread to exit -- it happens in the tests
78         // non-tests binary has only a static worker, so Rust doesn't drop it
79         thread::spawn(move || worker_thread.run(init_file_per_thread_logger));
80 
81         Self {
82             sender: tx,
83             #[cfg(test)]
84             stats,
85         }
86     }
87 
88     pub(super) fn on_cache_get_async(&self, path: impl AsRef<Path>) {
89         let event = CacheEvent::OnCacheGet(path.as_ref().to_path_buf());
90         self.send_cache_event(event);
91     }
92 
93     pub(super) fn on_cache_update_async(&self, path: impl AsRef<Path>) {
94         let event = CacheEvent::OnCacheUpdate(path.as_ref().to_path_buf());
95         self.send_cache_event(event);
96     }
97 
98     #[inline]
99     fn send_cache_event(&self, event: CacheEvent) {
100         let sent_event = self.sender.try_send(event.clone());
101 
102         if let Err(ref err) = sent_event {
103             info!(
104                 "Failed to send asynchronously message to worker thread, \
105                  event: {:?}, error: {}",
106                 event, err
107             );
108         }
109 
110         #[cfg(test)]
111         {
112             let mut stats = self
113                 .stats
114                 .0
115                 .lock()
116                 .expect("Failed to acquire worker stats lock");
117 
118             if sent_event.is_ok() {
119                 stats.sent += 1;
120             } else {
121                 stats.dropped += 1;
122             }
123         }
124     }
125 
126     #[cfg(test)]
127     pub(super) fn events_dropped(&self) -> u32 {
128         let stats = self
129             .stats
130             .0
131             .lock()
132             .expect("Failed to acquire worker stats lock");
133         stats.dropped
134     }
135 
136     #[cfg(test)]
137     pub(super) fn wait_for_all_events_handled(&self) {
138         let (stats, condvar) = &*self.stats;
139         let mut stats = stats.lock().expect("Failed to acquire worker stats lock");
140         while stats.handled != stats.sent {
141             stats = condvar
142                 .wait(stats)
143                 .expect("Failed to reacquire worker stats lock");
144         }
145     }
146 }
147 
148 impl fmt::Debug for Worker {
149     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150         f.debug_struct("Worker").finish()
151     }
152 }
153 
154 #[derive(Serialize, Deserialize)]
155 struct ModuleCacheStatistics {
156     pub usages: u64,
157     #[serde(rename = "optimized-compression")]
158     pub compression_level: i32,
159 }
160 
161 impl ModuleCacheStatistics {
162     fn default(cache_config: &CacheConfig) -> Self {
163         Self {
164             usages: 0,
165             compression_level: cache_config.baseline_compression_level(),
166         }
167     }
168 }
169 
170 enum CacheEntry {
171     Recognized {
172         path: PathBuf,
173         mtime: SystemTime,
174         size: u64,
175     },
176     Unrecognized {
177         path: PathBuf,
178         is_dir: bool,
179     },
180 }
181 
182 macro_rules! unwrap_or_warn {
183     ($result:expr, $cont:stmt, $err_msg:expr, $path:expr) => {
184         match $result {
185             Ok(val) => val,
186             Err(err) => {
187                 warn!("{}, path: {}, msg: {}", $err_msg, $path.display(), err);
188                 $cont
189             }
190         }
191     };
192 }
193 
194 impl WorkerThread {
195     fn run(self, init_file_per_thread_logger: Option<&'static str>) {
196         if let Some(prefix) = init_file_per_thread_logger {
197             file_per_thread_logger::initialize(prefix);
198         }
199 
200         debug!("Cache worker thread started.");
201 
202         Self::lower_thread_priority();
203 
204         #[cfg(test)]
205         let (stats, condvar) = &*self.stats;
206 
207         for event in self.receiver.iter() {
208             match event {
209                 CacheEvent::OnCacheGet(path) => self.handle_on_cache_get(path),
210                 CacheEvent::OnCacheUpdate(path) => self.handle_on_cache_update(path),
211             }
212 
213             #[cfg(test)]
214             {
215                 let mut stats = stats.lock().expect("Failed to acquire worker stats lock");
216                 stats.handled += 1;
217                 condvar.notify_all();
218             }
219         }
220     }
221 
222     #[cfg(target_os = "fuchsia")]
223     fn lower_thread_priority() {
224         // TODO This needs to use Fuchsia thread profiles
225         // https://fuchsia.dev/fuchsia-src/reference/kernel_objects/profile
226         warn!(
227             "Lowering thread priority on Fuchsia is currently a noop. It might affect application performance."
228         );
229     }
230 
231     #[cfg(target_os = "windows")]
232     fn lower_thread_priority() {
233         use winapi::um::processthreadsapi::{GetCurrentThread, SetThreadPriority};
234         use winapi::um::winbase::THREAD_MODE_BACKGROUND_BEGIN;
235 
236         // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadpriority
237         // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
238 
239         if unsafe {
240             SetThreadPriority(
241                 GetCurrentThread(),
242                 THREAD_MODE_BACKGROUND_BEGIN.try_into().unwrap(),
243             )
244         } == 0
245         {
246             warn!(
247                 "Failed to lower worker thread priority. It might affect application performance."
248             );
249         }
250     }
251 
252     #[cfg(not(any(target_os = "windows", target_os = "fuchsia")))]
253     fn lower_thread_priority() {
254         // http://man7.org/linux/man-pages/man7/sched.7.html
255 
256         const NICE_DELTA_FOR_BACKGROUND_TASKS: i32 = 3;
257 
258         match rustix::process::nice(NICE_DELTA_FOR_BACKGROUND_TASKS) {
259             Ok(current_nice) => {
260                 debug!("New nice value of worker thread: {}", current_nice);
261             }
262             Err(err) => {
263                 warn!(
264                     "Failed to lower worker thread priority ({:?}). It might affect application performance.", err);
265             }
266         };
267     }
268 
269     /// Increases the usage counter and recompresses the file
270     /// if the usage counter reached configurable treshold.
271     fn handle_on_cache_get(&self, path: PathBuf) {
272         trace!("handle_on_cache_get() for path: {}", path.display());
273 
274         // construct .stats file path
275         let filename = path.file_name().unwrap().to_str().unwrap();
276         let stats_path = path.with_file_name(format!("{}.stats", filename));
277 
278         // load .stats file (default if none or error)
279         let mut stats = read_stats_file(stats_path.as_ref())
280             .unwrap_or_else(|| ModuleCacheStatistics::default(&self.cache_config));
281 
282         // step 1: update the usage counter & write to the disk
283         //         it's racy, but it's fine (the counter will be just smaller,
284         //         sometimes will retrigger recompression)
285         stats.usages += 1;
286         if !write_stats_file(stats_path.as_ref(), &stats) {
287             return;
288         }
289 
290         // step 2: recompress if there's a need
291         let opt_compr_lvl = self.cache_config.optimized_compression_level();
292         if stats.compression_level >= opt_compr_lvl
293             || stats.usages
294                 < self
295                     .cache_config
296                     .optimized_compression_usage_counter_threshold()
297         {
298             return;
299         }
300 
301         let lock_path = if let Some(p) = acquire_task_fs_lock(
302             path.as_ref(),
303             self.cache_config.optimizing_compression_task_timeout(),
304             self.cache_config
305                 .allowed_clock_drift_for_files_from_future(),
306         ) {
307             p
308         } else {
309             return;
310         };
311 
312         trace!("Trying to recompress file: {}", path.display());
313 
314         // recompress, write to other file, rename (it's atomic file content exchange)
315         // and update the stats file
316         let compressed_cache_bytes = unwrap_or_warn!(
317             fs::read(&path),
318             return,
319             "Failed to read old cache file",
320             path
321         );
322 
323         let cache_bytes = unwrap_or_warn!(
324             zstd::decode_all(&compressed_cache_bytes[..]),
325             return,
326             "Failed to decompress cached code",
327             path
328         );
329 
330         let recompressed_cache_bytes = unwrap_or_warn!(
331             zstd::encode_all(&cache_bytes[..], opt_compr_lvl),
332             return,
333             "Failed to compress cached code",
334             path
335         );
336 
337         unwrap_or_warn!(
338             fs::write(&lock_path, &recompressed_cache_bytes),
339             return,
340             "Failed to write recompressed cache",
341             lock_path
342         );
343 
344         unwrap_or_warn!(
345             fs::rename(&lock_path, &path),
346             {
347                 if let Err(error) = fs::remove_file(&lock_path) {
348                     warn!(
349                         "Failed to clean up (remove) recompressed cache, path {}, err: {}",
350                         lock_path.display(),
351                         error
352                     );
353                 }
354 
355                 return;
356             },
357             "Failed to rename recompressed cache",
358             lock_path
359         );
360 
361         // update stats file (reload it! recompression can take some time)
362         if let Some(mut new_stats) = read_stats_file(stats_path.as_ref()) {
363             if new_stats.compression_level >= opt_compr_lvl {
364                 // Rare race:
365                 //    two instances with different opt_compr_lvl: we don't know in which order they updated
366                 //    the cache file and the stats file (they are not updated together atomically)
367                 // Possible solution is to use directories per cache entry, but it complicates the system
368                 // and is not worth it.
369                 debug!(
370                     "DETECTED task did more than once (or race with new file): \
371                      recompression of {}. Note: if optimized compression level setting \
372                      has changed in the meantine, the stats file might contain \
373                      inconsistent compression level due to race.",
374                     path.display()
375                 );
376             } else {
377                 new_stats.compression_level = opt_compr_lvl;
378                 let _ = write_stats_file(stats_path.as_ref(), &new_stats);
379             }
380 
381             if new_stats.usages < stats.usages {
382                 debug!(
383                     "DETECTED lower usage count (new file or race with counter \
384                      increasing): file {}",
385                     path.display()
386                 );
387             }
388         } else {
389             debug!(
390                 "Can't read stats file again to update compression level (it might got \
391                  cleaned up): file {}",
392                 stats_path.display()
393             );
394         }
395 
396         trace!("Task finished: recompress file: {}", path.display());
397     }
398 
399     fn handle_on_cache_update(&self, path: PathBuf) {
400         trace!("handle_on_cache_update() for path: {}", path.display());
401 
402         // ---------------------- step 1: create .stats file
403 
404         // construct .stats file path
405         let filename = path
406             .file_name()
407             .expect("Expected valid cache file name")
408             .to_str()
409             .expect("Expected valid cache file name");
410         let stats_path = path.with_file_name(format!("{}.stats", filename));
411 
412         // create and write stats file
413         let mut stats = ModuleCacheStatistics::default(&self.cache_config);
414         stats.usages += 1;
415         write_stats_file(&stats_path, &stats);
416 
417         // ---------------------- step 2: perform cleanup task if needed
418 
419         // acquire lock for cleanup task
420         // Lock is a proof of recent cleanup task, so we don't want to delete them.
421         // Expired locks will be deleted by the cleanup task.
422         let cleanup_file = self.cache_config.directory().join(".cleanup"); // some non existing marker file
423         if acquire_task_fs_lock(
424             &cleanup_file,
425             self.cache_config.cleanup_interval(),
426             self.cache_config
427                 .allowed_clock_drift_for_files_from_future(),
428         )
429         .is_none()
430         {
431             return;
432         }
433 
434         trace!("Trying to clean up cache");
435 
436         let mut cache_index = self.list_cache_contents();
437         let future_tolerance = SystemTime::now()
438             .checked_add(
439                 self.cache_config
440                     .allowed_clock_drift_for_files_from_future(),
441             )
442             .expect("Brace your cache, the next Big Bang is coming (time overflow)");
443         cache_index.sort_unstable_by(|lhs, rhs| {
444             // sort by age
445             use CacheEntry::*;
446             match (lhs, rhs) {
447                 (Recognized { mtime: lhs_mt, .. }, Recognized { mtime: rhs_mt, .. }) => {
448                     match (*lhs_mt > future_tolerance, *rhs_mt > future_tolerance) {
449                         // later == younger
450                         (false, false) => rhs_mt.cmp(lhs_mt),
451                         // files from far future are treated as oldest recognized files
452                         // we want to delete them, so the cache keeps track of recent files
453                         // however, we don't delete them uncodintionally,
454                         // because .stats file can be overwritten with a meaningful mtime
455                         (true, false) => cmp::Ordering::Greater,
456                         (false, true) => cmp::Ordering::Less,
457                         (true, true) => cmp::Ordering::Equal,
458                     }
459                 }
460                 // unrecognized is kind of infinity
461                 (Recognized { .. }, Unrecognized { .. }) => cmp::Ordering::Less,
462                 (Unrecognized { .. }, Recognized { .. }) => cmp::Ordering::Greater,
463                 (Unrecognized { .. }, Unrecognized { .. }) => cmp::Ordering::Equal,
464             }
465         });
466 
467         // find "cut" boundary:
468         // - remove unrecognized files anyway,
469         // - remove some cache files if some quota has been exceeded
470         let mut total_size = 0u64;
471         let mut start_delete_idx = None;
472         let mut start_delete_idx_if_deleting_recognized_items: Option<usize> = None;
473 
474         let total_size_limit = self.cache_config.files_total_size_soft_limit();
475         let file_count_limit = self.cache_config.file_count_soft_limit();
476         let tsl_if_deleting = total_size_limit
477             .checked_mul(
478                 self.cache_config
479                     .files_total_size_limit_percent_if_deleting() as u64,
480             )
481             .unwrap()
482             / 100;
483         let fcl_if_deleting = file_count_limit
484             .checked_mul(self.cache_config.file_count_limit_percent_if_deleting() as u64)
485             .unwrap()
486             / 100;
487 
488         for (idx, item) in cache_index.iter().enumerate() {
489             let size = if let CacheEntry::Recognized { size, .. } = item {
490                 size
491             } else {
492                 start_delete_idx = Some(idx);
493                 break;
494             };
495 
496             total_size += size;
497             if start_delete_idx_if_deleting_recognized_items.is_none()
498                 && (total_size > tsl_if_deleting || (idx + 1) as u64 > fcl_if_deleting)
499             {
500                 start_delete_idx_if_deleting_recognized_items = Some(idx);
501             }
502 
503             if total_size > total_size_limit || (idx + 1) as u64 > file_count_limit {
504                 start_delete_idx = start_delete_idx_if_deleting_recognized_items;
505                 break;
506             }
507         }
508 
509         if let Some(idx) = start_delete_idx {
510             for item in &cache_index[idx..] {
511                 let (result, path, entity) = match item {
512                     CacheEntry::Recognized { path, .. }
513                     | CacheEntry::Unrecognized {
514                         path,
515                         is_dir: false,
516                     } => (fs::remove_file(path), path, "file"),
517                     CacheEntry::Unrecognized { path, is_dir: true } => {
518                         (fs::remove_dir_all(path), path, "directory")
519                     }
520                 };
521                 if let Err(err) = result {
522                     warn!(
523                         "Failed to remove {} during cleanup, path: {}, err: {}",
524                         entity,
525                         path.display(),
526                         err
527                     );
528                 }
529             }
530         }
531 
532         trace!("Task finished: clean up cache");
533     }
534 
535     // Be fault tolerant: list as much as you can, and ignore the rest
536     fn list_cache_contents(&self) -> Vec<CacheEntry> {
537         fn enter_dir(
538             vec: &mut Vec<CacheEntry>,
539             dir_path: &Path,
540             level: u8,
541             cache_config: &CacheConfig,
542         ) {
543             macro_rules! add_unrecognized {
544                 (file: $path:expr) => {
545                     add_unrecognized!(false, $path)
546                 };
547                 (dir: $path:expr) => {
548                     add_unrecognized!(true, $path)
549                 };
550                 ($is_dir:expr, $path:expr) => {
551                     vec.push(CacheEntry::Unrecognized {
552                         path: $path.to_path_buf(),
553                         is_dir: $is_dir,
554                     })
555                 };
556             }
557             macro_rules! add_unrecognized_and {
558                 ([ $( $ty:ident: $path:expr ),* ], $cont:stmt) => {{
559                     $( add_unrecognized!($ty: $path); )*
560                         $cont
561                 }};
562             }
563 
564             macro_rules! unwrap_or {
565                 ($result:expr, $cont:stmt, $err_msg:expr) => {
566                     unwrap_or!($result, $cont, $err_msg, dir_path)
567                 };
568                 ($result:expr, $cont:stmt, $err_msg:expr, $path:expr) => {
569                     unwrap_or_warn!(
570                         $result,
571                         $cont,
572                         format!("{}, level: {}", $err_msg, level),
573                         $path
574                     )
575                 };
576             }
577 
578             // If we fail to list a directory, something bad is happening anyway
579             // (something touches our cache or we have disk failure)
580             // Try to delete it, so we can stay within soft limits of the cache size.
581             // This comment applies later in this function, too.
582             let it = unwrap_or!(
583                 fs::read_dir(dir_path),
584                 add_unrecognized_and!([dir: dir_path], return),
585                 "Failed to list cache directory, deleting it"
586             );
587 
588             let mut cache_files = HashMap::new();
589             for entry in it {
590                 // read_dir() returns an iterator over results - in case some of them are errors
591                 // we don't know their names, so we can't delete them. We don't want to delete
592                 // the whole directory with good entries too, so we just ignore the erroneous entries.
593                 let entry = unwrap_or!(
594                     entry,
595                     continue,
596                     "Failed to read a cache dir entry (NOT deleting it, it still occupies space)"
597                 );
598                 let path = entry.path();
599                 match (level, path.is_dir()) {
600                     (0..=1, true) => enter_dir(vec, &path, level + 1, cache_config),
601                     (0..=1, false) => {
602                         if level == 0
603                             && path.file_stem() == Some(OsStr::new(".cleanup"))
604                                 && path.extension().is_some()
605                                 // assume it's cleanup lock
606                                 && !is_fs_lock_expired(
607                                     Some(&entry),
608                                     &path,
609                                     cache_config.cleanup_interval(),
610                                     cache_config.allowed_clock_drift_for_files_from_future(),
611                                 )
612                         {
613                             continue; // skip active lock
614                         }
615                         add_unrecognized!(file: path);
616                     }
617                     (2, false) => {
618                         match path.extension().and_then(OsStr::to_str) {
619                             // mod or stats file
620                             None | Some("stats") => {
621                                 cache_files.insert(path, entry);
622                             }
623 
624                             Some(ext) => {
625                                 // check if valid lock
626                                 let recognized = ext.starts_with("wip-")
627                                     && !is_fs_lock_expired(
628                                         Some(&entry),
629                                         &path,
630                                         cache_config.optimizing_compression_task_timeout(),
631                                         cache_config.allowed_clock_drift_for_files_from_future(),
632                                     );
633 
634                                 if !recognized {
635                                     add_unrecognized!(file: path);
636                                 }
637                             }
638                         }
639                     }
640                     (_, is_dir) => add_unrecognized!(is_dir, path),
641                 }
642             }
643 
644             // associate module with its stats & handle them
645             // assumption: just mods and stats
646             for (path, entry) in cache_files.iter() {
647                 let path_buf: PathBuf;
648                 let (mod_, stats_, is_mod) = match path.extension() {
649                     Some(_) => {
650                         path_buf = path.with_extension("");
651                         (
652                             cache_files.get(&path_buf).map(|v| (&path_buf, v)),
653                             Some((path, entry)),
654                             false,
655                         )
656                     }
657                     None => {
658                         path_buf = path.with_extension("stats");
659                         (
660                             Some((path, entry)),
661                             cache_files.get(&path_buf).map(|v| (&path_buf, v)),
662                             true,
663                         )
664                     }
665                 };
666 
667                 // construct a cache entry
668                 match (mod_, stats_, is_mod) {
669                     (Some((mod_path, mod_entry)), Some((stats_path, stats_entry)), true) => {
670                         let mod_metadata = unwrap_or!(
671                             mod_entry.metadata(),
672                             add_unrecognized_and!([file: stats_path, file: mod_path], continue),
673                             "Failed to get metadata, deleting BOTH module cache and stats files",
674                             mod_path
675                         );
676                         let stats_mtime = unwrap_or!(
677                             stats_entry.metadata().and_then(|m| m.modified()),
678                             add_unrecognized_and!(
679                                 [file: stats_path],
680                                 unwrap_or!(
681                                     mod_metadata.modified(),
682                                     add_unrecognized_and!(
683                                         [file: stats_path, file: mod_path],
684                                         continue
685                                     ),
686                                     "Failed to get mtime, deleting BOTH module cache and stats \
687                                      files",
688                                     mod_path
689                                 )
690                             ),
691                             "Failed to get metadata/mtime, deleting the file",
692                             stats_path
693                         );
694                         // .into() called for the SystemTimeStub if cfg(test)
695                         #[allow(clippy::identity_conversion)]
696                         vec.push(CacheEntry::Recognized {
697                             path: mod_path.to_path_buf(),
698                             mtime: stats_mtime.into(),
699                             size: mod_metadata.len(),
700                         })
701                     }
702                     (Some(_), Some(_), false) => (), // was or will be handled by previous branch
703                     (Some((mod_path, mod_entry)), None, _) => {
704                         let (mod_metadata, mod_mtime) = unwrap_or!(
705                             mod_entry
706                                 .metadata()
707                                 .and_then(|md| md.modified().map(|mt| (md, mt))),
708                             add_unrecognized_and!([file: mod_path], continue),
709                             "Failed to get metadata/mtime, deleting the file",
710                             mod_path
711                         );
712                         // .into() called for the SystemTimeStub if cfg(test)
713                         #[allow(clippy::identity_conversion)]
714                         vec.push(CacheEntry::Recognized {
715                             path: mod_path.to_path_buf(),
716                             mtime: mod_mtime.into(),
717                             size: mod_metadata.len(),
718                         })
719                     }
720                     (None, Some((stats_path, _stats_entry)), _) => {
721                         debug!("Found orphaned stats file: {}", stats_path.display());
722                         add_unrecognized!(file: stats_path);
723                     }
724                     _ => unreachable!(),
725                 }
726             }
727         }
728 
729         let mut vec = Vec::new();
730         enter_dir(
731             &mut vec,
732             self.cache_config.directory(),
733             0,
734             &self.cache_config,
735         );
736         vec
737     }
738 }
739 
740 fn read_stats_file(path: &Path) -> Option<ModuleCacheStatistics> {
741     fs::read(path)
742         .map_err(|err| {
743             trace!(
744                 "Failed to read stats file, path: {}, err: {}",
745                 path.display(),
746                 err
747             )
748         })
749         .and_then(|bytes| {
750             toml::from_slice::<ModuleCacheStatistics>(&bytes[..]).map_err(|err| {
751                 trace!(
752                     "Failed to parse stats file, path: {}, err: {}",
753                     path.display(),
754                     err,
755                 )
756             })
757         })
758         .ok()
759 }
760 
761 fn write_stats_file(path: &Path, stats: &ModuleCacheStatistics) -> bool {
762     toml::to_string_pretty(&stats)
763         .map_err(|err| {
764             warn!(
765                 "Failed to serialize stats file, path: {}, err: {}",
766                 path.display(),
767                 err
768             )
769         })
770         .and_then(|serialized| {
771             if fs_write_atomic(path, "stats", serialized.as_bytes()) {
772                 Ok(())
773             } else {
774                 Err(())
775             }
776         })
777         .is_ok()
778 }
779 
780 /// Tries to acquire a lock for specific task.
781 ///
782 /// Returns Some(path) to the lock if succeeds. The task path must not
783 /// contain any extension and have file stem.
784 ///
785 /// To release a lock you need either manually rename or remove it,
786 /// or wait until it expires and cleanup task removes it.
787 ///
788 /// Note: this function is racy. Main idea is: be fault tolerant and
789 ///       never block some task. The price is that we rarely do some task
790 ///       more than once.
791 fn acquire_task_fs_lock(
792     task_path: &Path,
793     timeout: Duration,
794     allowed_future_drift: Duration,
795 ) -> Option<PathBuf> {
796     assert!(task_path.extension().is_none());
797     assert!(task_path.file_stem().is_some());
798 
799     // list directory
800     let dir_path = task_path.parent()?;
801     let it = fs::read_dir(dir_path)
802         .map_err(|err| {
803             warn!(
804                 "Failed to list cache directory, path: {}, err: {}",
805                 dir_path.display(),
806                 err
807             )
808         })
809         .ok()?;
810 
811     // look for existing locks
812     for entry in it {
813         let entry = entry
814             .map_err(|err| {
815                 warn!(
816                     "Failed to list cache directory, path: {}, err: {}",
817                     dir_path.display(),
818                     err
819                 )
820             })
821             .ok()?;
822 
823         let path = entry.path();
824         if path.is_dir() || path.file_stem() != task_path.file_stem() {
825             continue;
826         }
827 
828         // check extension and mtime
829         match path.extension() {
830             None => continue,
831             Some(ext) => {
832                 if let Some(ext_str) = ext.to_str() {
833                     // if it's None, i.e. not valid UTF-8 string, then that's not our lock for sure
834                     if ext_str.starts_with("wip-")
835                         && !is_fs_lock_expired(Some(&entry), &path, timeout, allowed_future_drift)
836                     {
837                         return None;
838                     }
839                 }
840             }
841         }
842     }
843 
844     // create the lock
845     let lock_path = task_path.with_extension(format!("wip-{}", std::process::id()));
846     let _file = fs::OpenOptions::new()
847         .create_new(true)
848         .write(true)
849         .open(&lock_path)
850         .map_err(|err| {
851             warn!(
852                 "Failed to create lock file (note: it shouldn't exists): path: {}, err: {}",
853                 lock_path.display(),
854                 err
855             )
856         })
857         .ok()?;
858 
859     Some(lock_path)
860 }
861 
862 // we have either both, or just path; dir entry is desirable since on some platforms we can get
863 // metadata without extra syscalls
864 // futhermore: it's better to get a path if we have it instead of allocating a new one from the dir entry
865 fn is_fs_lock_expired(
866     entry: Option<&fs::DirEntry>,
867     path: &PathBuf,
868     threshold: Duration,
869     allowed_future_drift: Duration,
870 ) -> bool {
871     let mtime = match entry
872         .map_or_else(|| path.metadata(), |e| e.metadata())
873         .and_then(|metadata| metadata.modified())
874     {
875         Ok(mt) => mt,
876         Err(err) => {
877             warn!(
878                 "Failed to get metadata/mtime, treating as an expired lock, path: {}, err: {}",
879                 path.display(),
880                 err
881             );
882             return true; // can't read mtime, treat as expired, so this task will not be starved
883         }
884     };
885 
886     // DON'T use: mtime.elapsed() -- we must call SystemTime directly for the tests to be deterministic
887     match SystemTime::now().duration_since(mtime) {
888         Ok(elapsed) => elapsed >= threshold,
889         Err(err) => {
890             trace!(
891                 "Found mtime in the future, treating as a not expired lock, path: {}, err: {}",
892                 path.display(),
893                 err
894             );
895             // the lock is expired if the time is too far in the future
896             // it is fine to have network share and not synchronized clocks,
897             // but it's not good when user changes time in their system clock
898             err.duration() > allowed_future_drift
899         }
900     }
901 }
902 
903 #[cfg(test)]
904 mod tests;
905