]> git.lizzy.rs Git - rust.git/blob - src/librustc_incremental/persist/fs.rs
d53ee5c804f601d5190be2d5444568217e71bcc3
[rust.git] / src / librustc_incremental / persist / fs.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 //! This module manages how the incremental compilation cache is represented in
13 //! the file system.
14 //!
15 //! Incremental compilation caches are managed according to a copy-on-write
16 //! strategy: Once a complete, consistent cache version is finalized, it is
17 //! never modified. Instead, when a subsequent compilation session is started,
18 //! the compiler will allocate a new version of the cache that starts out as
19 //! a copy of the previous version. Then only this new copy is modified and it
20 //! will not be visible to other processes until it is finalized. This ensures
21 //! that multiple compiler processes can be executed concurrently for the same
22 //! crate without interfering with each other or blocking each other.
23 //!
24 //! More concretely this is implemented via the following protocol:
25 //!
26 //! 1. For a newly started compilation session, the compiler allocates a
27 //!    new `session` directory within the incremental compilation directory.
28 //!    This session directory will have a unique name that ends with the suffix
29 //!    "-working" and that contains a creation timestamp.
30 //! 2. Next, the compiler looks for the newest finalized session directory,
31 //!    that is, a session directory from a previous compilation session that
32 //!    has been marked as valid and consistent. A session directory is
33 //!    considered finalized if the "-working" suffix in the directory name has
34 //!    been replaced by the SVH of the crate.
35 //! 3. Once the compiler has found a valid, finalized session directory, it will
36 //!    hard-link/copy its contents into the new "-working" directory. If all
37 //!    goes well, it will have its own, private copy of the source directory and
38 //!    subsequently not have to worry about synchronizing with other compiler
39 //!    processes.
40 //! 4. Now the compiler can do its normal compilation process, which involves
41 //!    reading and updating its private session directory.
42 //! 5. When compilation finishes without errors, the private session directory
43 //!    will be in a state where it can be used as input for other compilation
44 //!    sessions. That is, it will contain a dependency graph and cache artifacts
45 //!    that are consistent with the state of the source code it was compiled
46 //!    from, with no need to change them ever again. At this point, the compiler
47 //!    finalizes and "publishes" its private session directory by renaming it
48 //!    from "s-{timestamp}-{random}-working" to "s-{timestamp}-{SVH}".
49 //! 6. At this point the "old" session directory that we copied our data from
50 //!    at the beginning of the session has become obsolete because we have just
51 //!    published a more current version. Thus the compiler will delete it.
52 //!
53 //! ## Garbage Collection
54 //!
55 //! Naively following the above protocol might lead to old session directories
56 //! piling up if a compiler instance crashes for some reason before its able to
57 //! remove its private session directory. In order to avoid wasting disk space,
58 //! the compiler also does some garbage collection each time it is started in
59 //! incremental compilation mode. Specifically, it will scan the incremental
60 //! compilation directory for private session directories that are not in use
61 //! any more and will delete those. It will also delete any finalized session
62 //! directories for a given crate except for the most recent one.
63 //!
64 //! ## Synchronization
65 //!
66 //! There is some synchronization needed in order for the compiler to be able to
67 //! determine whether a given private session directory is not in used any more.
68 //! This is done by creating a lock file for each session directory and
69 //! locking it while the directory is still being used. Since file locks have
70 //! operating system support, we can rely on the lock being released if the
71 //! compiler process dies for some unexpected reason. Thus, when garbage
72 //! collecting private session directories, the collecting process can determine
73 //! whether the directory is still in use by trying to acquire a lock on the
74 //! file. If locking the file fails, the original process must still be alive.
75 //! If locking the file succeeds, we know that the owning process is not alive
76 //! any more and we can safely delete the directory.
77 //! There is still a small time window between the original process creating the
78 //! lock file and actually locking it. In order to minimize the chance that
79 //! another process tries to acquire the lock in just that instance, only
80 //! session directories that are older than a few seconds are considered for
81 //! garbage collection.
82 //!
83 //! Another case that has to be considered is what happens if one process
84 //! deletes a finalized session directory that another process is currently
85 //! trying to copy from. This case is also handled via the lock file. Before
86 //! a process starts copying a finalized session directory, it will acquire a
87 //! shared lock on the directory's lock file. Any garbage collecting process,
88 //! on the other hand, will acquire an exclusive lock on the lock file.
89 //! Thus, if a directory is being collected, any reader process will fail
90 //! acquiring the shared lock and will leave the directory alone. Conversely,
91 //! if a collecting process can't acquire the exclusive lock because the
92 //! directory is currently being read from, it will leave collecting that
93 //! directory to another process at a later point in time.
94 //! The exact same scheme is also used when reading the metadata hashes file
95 //! from an extern crate. When a crate is compiled, the hash values of its
96 //! metadata are stored in a file in its session directory. When the
97 //! compilation session of another crate imports the first crate's metadata,
98 //! it also has to read in the accompanying metadata hashes. It thus will access
99 //! the finalized session directory of all crates it links to and while doing
100 //! so, it will also place a read lock on that the respective session directory
101 //! so that it won't be deleted while the metadata hashes are loaded.
102 //!
103 //! ## Preconditions
104 //!
105 //! This system relies on two features being available in the file system in
106 //! order to work really well: file locking and hard linking.
107 //! If hard linking is not available (like on FAT) the data in the cache
108 //! actually has to be copied at the beginning of each session.
109 //! If file locking does not work reliably (like on NFS), some of the
110 //! synchronization will go haywire.
111 //! In both cases we recommend to locate the incremental compilation directory
112 //! on a file system that supports these things.
113 //! It might be a good idea though to try and detect whether we are on an
114 //! unsupported file system and emit a warning in that case. This is not yet
115 //! implemented.
116
117 use rustc::hir::svh::Svh;
118 use rustc::session::Session;
119 use rustc::util::fs as fs_util;
120 use rustc_data_structures::{flock, base_n};
121 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
122
123 use std::fs as std_fs;
124 use std::io;
125 use std::mem;
126 use std::path::{Path, PathBuf};
127 use std::time::{UNIX_EPOCH, SystemTime, Duration};
128 use std::__rand::{thread_rng, Rng};
129
130 const LOCK_FILE_EXT: &'static str = ".lock";
131 const DEP_GRAPH_FILENAME: &'static str = "dep-graph.bin";
132 const WORK_PRODUCTS_FILENAME: &'static str = "work-products.bin";
133 const METADATA_HASHES_FILENAME: &'static str = "metadata.bin";
134
135 // We encode integers using the following base, so they are shorter than decimal
136 // or hexadecimal numbers (we want short file and directory names). Since these
137 // numbers will be used in file names, we choose an encoding that is not
138 // case-sensitive (as opposed to base64, for example).
139 const INT_ENCODE_BASE: u64 = 36;
140
141 pub fn dep_graph_path(sess: &Session) -> PathBuf {
142     in_incr_comp_dir_sess(sess, DEP_GRAPH_FILENAME)
143 }
144
145 pub fn work_products_path(sess: &Session) -> PathBuf {
146     in_incr_comp_dir_sess(sess, WORK_PRODUCTS_FILENAME)
147 }
148
149 pub fn metadata_hash_export_path(sess: &Session) -> PathBuf {
150     in_incr_comp_dir_sess(sess, METADATA_HASHES_FILENAME)
151 }
152
153 pub fn lock_file_path(session_dir: &Path) -> PathBuf {
154     let crate_dir = session_dir.parent().unwrap();
155
156     let directory_name = session_dir.file_name().unwrap().to_string_lossy();
157     assert_no_characters_lost(&directory_name);
158
159     let dash_indices: Vec<_> = directory_name.match_indices("-")
160                                              .map(|(idx, _)| idx)
161                                              .collect();
162     if dash_indices.len() != 3 {
163         bug!("Encountered incremental compilation session directory with \
164               malformed name: {}",
165              session_dir.display())
166     }
167
168     crate_dir.join(&directory_name[0 .. dash_indices[2]])
169              .with_extension(&LOCK_FILE_EXT[1..])
170 }
171
172 pub fn in_incr_comp_dir_sess(sess: &Session, file_name: &str) -> PathBuf {
173     in_incr_comp_dir(&sess.incr_comp_session_dir(), file_name)
174 }
175
176 pub fn in_incr_comp_dir(incr_comp_session_dir: &Path, file_name: &str) -> PathBuf {
177     incr_comp_session_dir.join(file_name)
178 }
179
180 /// Allocates the private session directory. The boolean in the Ok() result
181 /// indicates whether we should try loading a dep graph from the successfully
182 /// initialized directory, or not.
183 /// The post-condition of this fn is that we have a valid incremental
184 /// compilation session directory, if the result is `Ok`. A valid session
185 /// directory is one that contains a locked lock file. It may or may not contain
186 /// a dep-graph and work products from a previous session.
187 /// If the call fails, the fn may leave behind an invalid session directory.
188 /// The garbage collection will take care of it.
189 pub fn prepare_session_directory(sess: &Session,
190                                  crate_name: &str,
191                                  crate_disambiguator: &str) {
192     if sess.opts.incremental.is_none() {
193         return
194     }
195
196     debug!("prepare_session_directory");
197
198     // {incr-comp-dir}/{crate-name-and-disambiguator}
199     let crate_dir = crate_path(sess, crate_name, crate_disambiguator);
200     debug!("crate-dir: {}", crate_dir.display());
201     if create_dir(sess, &crate_dir, "crate").is_err() {
202         return
203     }
204
205     // Hack: canonicalize the path *after creating the directory*
206     // because, on windows, long paths can cause problems;
207     // canonicalization inserts this weird prefix that makes windows
208     // tolerate long paths.
209     let crate_dir = match crate_dir.canonicalize() {
210         Ok(v) => v,
211         Err(err) => {
212             sess.err(&format!("incremental compilation: error canonicalizing path `{}`: {}",
213                               crate_dir.display(), err));
214             return
215         }
216     };
217
218     let mut source_directories_already_tried = FxHashSet();
219
220     loop {
221         // Generate a session directory of the form:
222         //
223         // {incr-comp-dir}/{crate-name-and-disambiguator}/s-{timestamp}-{random}-working
224         let session_dir = generate_session_dir_path(&crate_dir);
225         debug!("session-dir: {}", session_dir.display());
226
227         // Lock the new session directory. If this fails, return an
228         // error without retrying
229         let (directory_lock, lock_file_path) = match lock_directory(sess, &session_dir) {
230             Ok(e) => e,
231             Err(_) => return,
232         };
233
234         // Now that we have the lock, we can actually create the session
235         // directory
236         if create_dir(sess, &session_dir, "session").is_err() {
237             return
238         }
239
240         // Find a suitable source directory to copy from. Ignore those that we
241         // have already tried before.
242         let source_directory = find_source_directory(&crate_dir,
243                                                      &source_directories_already_tried);
244
245         let source_directory = if let Some(dir) = source_directory {
246             dir
247         } else {
248             // There's nowhere to copy from, we're done
249             debug!("no source directory found. Continuing with empty session \
250                     directory.");
251
252             sess.init_incr_comp_session(session_dir, directory_lock, false);
253             return
254         };
255
256         debug!("attempting to copy data from source: {}",
257                source_directory.display());
258
259
260
261         // Try copying over all files from the source directory
262         if let Ok(allows_links) = copy_files(sess,
263                                              &session_dir,
264                                              &source_directory) {
265             debug!("successfully copied data from: {}",
266                    source_directory.display());
267
268             if !allows_links {
269                 sess.warn(&format!("Hard linking files in the incremental \
270                                         compilation cache failed. Copying files \
271                                         instead. Consider moving the cache \
272                                         directory to a file system which supports \
273                                         hard linking in session dir `{}`",
274                                         session_dir.display())
275                     );
276             }
277
278             sess.init_incr_comp_session(session_dir, directory_lock, true);
279             return
280         } else {
281              debug!("copying failed - trying next directory");
282
283             // Something went wrong while trying to copy/link files from the
284             // source directory. Try again with a different one.
285             source_directories_already_tried.insert(source_directory);
286
287             // Try to remove the session directory we just allocated. We don't
288             // know if there's any garbage in it from the failed copy action.
289             if let Err(err) = safe_remove_dir_all(&session_dir) {
290                 sess.warn(&format!("Failed to delete partly initialized \
291                                     session dir `{}`: {}",
292                                    session_dir.display(),
293                                    err));
294             }
295
296             delete_session_dir_lock_file(sess, &lock_file_path);
297             mem::drop(directory_lock);
298         }
299     }
300 }
301
302
303 /// This function finalizes and thus 'publishes' the session directory by
304 /// renaming it to `s-{timestamp}-{svh}` and releasing the file lock.
305 /// If there have been compilation errors, however, this function will just
306 /// delete the presumably invalid session directory.
307 pub fn finalize_session_directory(sess: &Session, svh: Svh) {
308     if sess.opts.incremental.is_none() {
309         return;
310     }
311
312     let incr_comp_session_dir: PathBuf = sess.incr_comp_session_dir().clone();
313
314     if sess.has_errors() {
315         // If there have been any errors during compilation, we don't want to
316         // publish this session directory. Rather, we'll just delete it.
317
318         debug!("finalize_session_directory() - invalidating session directory: {}",
319                 incr_comp_session_dir.display());
320
321         if let Err(err) = safe_remove_dir_all(&*incr_comp_session_dir) {
322             sess.warn(&format!("Error deleting incremental compilation \
323                                 session directory `{}`: {}",
324                                incr_comp_session_dir.display(),
325                                err));
326         }
327
328         let lock_file_path = lock_file_path(&*incr_comp_session_dir);
329         delete_session_dir_lock_file(sess, &lock_file_path);
330         sess.mark_incr_comp_session_as_invalid();
331     }
332
333     debug!("finalize_session_directory() - session directory: {}",
334             incr_comp_session_dir.display());
335
336     let old_sub_dir_name = incr_comp_session_dir.file_name()
337                                                 .unwrap()
338                                                 .to_string_lossy();
339     assert_no_characters_lost(&old_sub_dir_name);
340
341     // Keep the 's-{timestamp}-{random-number}' prefix, but replace the
342     // '-working' part with the SVH of the crate
343     let dash_indices: Vec<_> = old_sub_dir_name.match_indices("-")
344                                                .map(|(idx, _)| idx)
345                                                .collect();
346     if dash_indices.len() != 3 {
347         bug!("Encountered incremental compilation session directory with \
348               malformed name: {}",
349              incr_comp_session_dir.display())
350     }
351
352     // State: "s-{timestamp}-{random-number}-"
353     let mut new_sub_dir_name = String::from(&old_sub_dir_name[.. dash_indices[2] + 1]);
354
355     // Append the svh
356     base_n::push_str(svh.as_u64(), INT_ENCODE_BASE, &mut new_sub_dir_name);
357
358     // Create the full path
359     let new_path = incr_comp_session_dir.parent().unwrap().join(new_sub_dir_name);
360     debug!("finalize_session_directory() - new path: {}", new_path.display());
361
362     match std_fs::rename(&*incr_comp_session_dir, &new_path) {
363         Ok(_) => {
364             debug!("finalize_session_directory() - directory renamed successfully");
365
366             // This unlocks the directory
367             sess.finalize_incr_comp_session(new_path);
368         }
369         Err(e) => {
370             // Warn about the error. However, no need to abort compilation now.
371             sess.warn(&format!("Error finalizing incremental compilation \
372                                session directory `{}`: {}",
373                                incr_comp_session_dir.display(),
374                                e));
375
376             debug!("finalize_session_directory() - error, marking as invalid");
377             // Drop the file lock, so we can garage collect
378             sess.mark_incr_comp_session_as_invalid();
379         }
380     }
381
382     let _ = garbage_collect_session_directories(sess);
383 }
384
385 pub fn delete_all_session_dir_contents(sess: &Session) -> io::Result<()> {
386     let sess_dir_iterator = sess.incr_comp_session_dir().read_dir()?;
387     for entry in sess_dir_iterator {
388         let entry = entry?;
389         safe_remove_file(&entry.path())?
390     }
391     Ok(())
392 }
393
394 fn copy_files(sess: &Session,
395               target_dir: &Path,
396               source_dir: &Path)
397               -> Result<bool, ()> {
398     // We acquire a shared lock on the lock file of the directory, so that
399     // nobody deletes it out from under us while we are reading from it.
400     let lock_file_path = lock_file_path(source_dir);
401     let _lock = if let Ok(lock) = flock::Lock::new(&lock_file_path,
402                                                    false,   // don't wait,
403                                                    false,   // don't create
404                                                    false) { // not exclusive
405         lock
406     } else {
407         // Could not acquire the lock, don't try to copy from here
408         return Err(())
409     };
410
411     let source_dir_iterator = match source_dir.read_dir() {
412         Ok(it) => it,
413         Err(_) => return Err(())
414     };
415
416     let mut files_linked = 0;
417     let mut files_copied = 0;
418
419     for entry in source_dir_iterator {
420         match entry {
421             Ok(entry) => {
422                 let file_name = entry.file_name();
423
424                 let target_file_path = target_dir.join(file_name);
425                 let source_path = entry.path();
426
427                 debug!("copying into session dir: {}", source_path.display());
428                 match fs_util::link_or_copy(source_path, target_file_path) {
429                     Ok(fs_util::LinkOrCopy::Link) => {
430                         files_linked += 1
431                     }
432                     Ok(fs_util::LinkOrCopy::Copy) => {
433                         files_copied += 1
434                     }
435                     Err(_) => return Err(())
436                 }
437             }
438             Err(_) => {
439                 return Err(())
440             }
441         }
442     }
443
444     if sess.opts.debugging_opts.incremental_info {
445         println!("[incremental] session directory: \
446                   {} files hard-linked", files_linked);
447         println!("[incremental] session directory: \
448                  {} files copied", files_copied);
449     }
450
451     Ok(files_linked > 0 || files_copied == 0)
452 }
453
454 /// Generate unique directory path of the form:
455 /// {crate_dir}/s-{timestamp}-{random-number}-working
456 fn generate_session_dir_path(crate_dir: &Path) -> PathBuf {
457     let timestamp = timestamp_to_string(SystemTime::now());
458     debug!("generate_session_dir_path: timestamp = {}", timestamp);
459     let random_number = thread_rng().next_u32();
460     debug!("generate_session_dir_path: random_number = {}", random_number);
461
462     let directory_name = format!("s-{}-{}-working",
463                                   timestamp,
464                                   base_n::encode(random_number as u64,
465                                                  INT_ENCODE_BASE));
466     debug!("generate_session_dir_path: directory_name = {}", directory_name);
467     let directory_path = crate_dir.join(directory_name);
468     debug!("generate_session_dir_path: directory_path = {}", directory_path.display());
469     directory_path
470 }
471
472 fn create_dir(sess: &Session, path: &Path, dir_tag: &str) -> Result<(),()> {
473     match std_fs::create_dir_all(path) {
474         Ok(()) => {
475             debug!("{} directory created successfully", dir_tag);
476             Ok(())
477         }
478         Err(err) => {
479             sess.err(&format!("Could not create incremental compilation {} \
480                                directory `{}`: {}",
481                               dir_tag,
482                               path.display(),
483                               err));
484             Err(())
485         }
486     }
487 }
488
489 /// Allocate a the lock-file and lock it.
490 fn lock_directory(sess: &Session,
491                   session_dir: &Path)
492                   -> Result<(flock::Lock, PathBuf), ()> {
493     let lock_file_path = lock_file_path(session_dir);
494     debug!("lock_directory() - lock_file: {}", lock_file_path.display());
495
496     match flock::Lock::new(&lock_file_path,
497                            false, // don't wait
498                            true,  // create the lock file
499                            true) { // the lock should be exclusive
500         Ok(lock) => Ok((lock, lock_file_path)),
501         Err(err) => {
502             sess.err(&format!("incremental compilation: could not create \
503                                session directory lock file: {}", err));
504             Err(())
505         }
506     }
507 }
508
509 fn delete_session_dir_lock_file(sess: &Session,
510                                 lock_file_path: &Path) {
511     if let Err(err) = safe_remove_file(&lock_file_path) {
512         sess.warn(&format!("Error deleting lock file for incremental \
513                             compilation session directory `{}`: {}",
514                            lock_file_path.display(),
515                            err));
516     }
517 }
518
519 /// Find the most recent published session directory that is not in the
520 /// ignore-list.
521 fn find_source_directory(crate_dir: &Path,
522                          source_directories_already_tried: &FxHashSet<PathBuf>)
523                          -> Option<PathBuf> {
524     let iter = crate_dir.read_dir()
525                         .unwrap() // FIXME
526                         .filter_map(|e| e.ok().map(|e| e.path()));
527
528     find_source_directory_in_iter(iter, source_directories_already_tried)
529 }
530
531 fn find_source_directory_in_iter<I>(iter: I,
532                                     source_directories_already_tried: &FxHashSet<PathBuf>)
533                                     -> Option<PathBuf>
534     where I: Iterator<Item=PathBuf>
535 {
536     let mut best_candidate = (UNIX_EPOCH, None);
537
538     for session_dir in iter {
539         debug!("find_source_directory_in_iter - inspecting `{}`",
540                session_dir.display());
541
542         let directory_name = session_dir.file_name().unwrap().to_string_lossy();
543         assert_no_characters_lost(&directory_name);
544
545         if source_directories_already_tried.contains(&session_dir) ||
546            !is_session_directory(&directory_name) ||
547            !is_finalized(&directory_name) {
548             debug!("find_source_directory_in_iter - ignoring.");
549             continue
550         }
551
552         let timestamp = extract_timestamp_from_session_dir(&directory_name)
553             .unwrap_or_else(|_| {
554                 bug!("unexpected incr-comp session dir: {}", session_dir.display())
555             });
556
557         if timestamp > best_candidate.0 {
558             best_candidate = (timestamp, Some(session_dir.clone()));
559         }
560     }
561
562     best_candidate.1
563 }
564
565 fn is_finalized(directory_name: &str) -> bool {
566     !directory_name.ends_with("-working")
567 }
568
569 fn is_session_directory(directory_name: &str) -> bool {
570     directory_name.starts_with("s-") &&
571     !directory_name.ends_with(LOCK_FILE_EXT)
572 }
573
574 fn is_session_directory_lock_file(file_name: &str) -> bool {
575     file_name.starts_with("s-") && file_name.ends_with(LOCK_FILE_EXT)
576 }
577
578 fn extract_timestamp_from_session_dir(directory_name: &str)
579                                       -> Result<SystemTime, ()> {
580     if !is_session_directory(directory_name) {
581         return Err(())
582     }
583
584     let dash_indices: Vec<_> = directory_name.match_indices("-")
585                                              .map(|(idx, _)| idx)
586                                              .collect();
587     if dash_indices.len() != 3 {
588         return Err(())
589     }
590
591     string_to_timestamp(&directory_name[dash_indices[0]+1 .. dash_indices[1]])
592 }
593
594 fn timestamp_to_string(timestamp: SystemTime) -> String {
595     let duration = timestamp.duration_since(UNIX_EPOCH).unwrap();
596     let micros = duration.as_secs() * 1_000_000 +
597                 (duration.subsec_nanos() as u64) / 1000;
598     base_n::encode(micros, INT_ENCODE_BASE)
599 }
600
601 fn string_to_timestamp(s: &str) -> Result<SystemTime, ()> {
602     let micros_since_unix_epoch = u64::from_str_radix(s, 36);
603
604     if micros_since_unix_epoch.is_err() {
605         return Err(())
606     }
607
608     let micros_since_unix_epoch = micros_since_unix_epoch.unwrap();
609
610     let duration = Duration::new(micros_since_unix_epoch / 1_000_000,
611                                  1000 * (micros_since_unix_epoch % 1_000_000) as u32);
612     Ok(UNIX_EPOCH + duration)
613 }
614
615 fn crate_path(sess: &Session,
616               crate_name: &str,
617               crate_disambiguator: &str)
618               -> PathBuf {
619     use std::hash::{Hasher, Hash};
620     use std::collections::hash_map::DefaultHasher;
621
622     let incr_dir = sess.opts.incremental.as_ref().unwrap().clone();
623
624     // The full crate disambiguator is really long. A hash of it should be
625     // sufficient.
626     let mut hasher = DefaultHasher::new();
627     crate_disambiguator.hash(&mut hasher);
628
629     let crate_name = format!("{}-{}",
630                              crate_name,
631                              base_n::encode(hasher.finish(), INT_ENCODE_BASE));
632     incr_dir.join(crate_name)
633 }
634
635 fn assert_no_characters_lost(s: &str) {
636     if s.contains('\u{FFFD}') {
637         bug!("Could not losslessly convert '{}'.", s)
638     }
639 }
640
641 fn is_old_enough_to_be_collected(timestamp: SystemTime) -> bool {
642     timestamp < SystemTime::now() - Duration::from_secs(10)
643 }
644
645 pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> {
646     debug!("garbage_collect_session_directories() - begin");
647
648     let session_directory = sess.incr_comp_session_dir();
649     debug!("garbage_collect_session_directories() - session directory: {}",
650         session_directory.display());
651
652     let crate_directory = session_directory.parent().unwrap();
653     debug!("garbage_collect_session_directories() - crate directory: {}",
654         crate_directory.display());
655
656     // First do a pass over the crate directory, collecting lock files and
657     // session directories
658     let mut session_directories = FxHashSet();
659     let mut lock_files = FxHashSet();
660
661     for dir_entry in try!(crate_directory.read_dir()) {
662         let dir_entry = match dir_entry {
663             Ok(dir_entry) => dir_entry,
664             _ => {
665                 // Ignore any errors
666                 continue
667             }
668         };
669
670         let entry_name = dir_entry.file_name();
671         let entry_name = entry_name.to_string_lossy();
672
673         if is_session_directory_lock_file(&entry_name) {
674             assert_no_characters_lost(&entry_name);
675             lock_files.insert(entry_name.into_owned());
676         } else if is_session_directory(&entry_name) {
677             assert_no_characters_lost(&entry_name);
678             session_directories.insert(entry_name.into_owned());
679         } else {
680             // This is something we don't know, leave it alone
681         }
682     }
683
684     // Now map from lock files to session directories
685     let lock_file_to_session_dir: FxHashMap<String, Option<String>> =
686         lock_files.into_iter()
687                   .map(|lock_file_name| {
688                         assert!(lock_file_name.ends_with(LOCK_FILE_EXT));
689                         let dir_prefix_end = lock_file_name.len() - LOCK_FILE_EXT.len();
690                         let session_dir = {
691                             let dir_prefix = &lock_file_name[0 .. dir_prefix_end];
692                             session_directories.iter()
693                                                .find(|dir_name| dir_name.starts_with(dir_prefix))
694                         };
695                         (lock_file_name, session_dir.map(String::clone))
696                     })
697                   .collect();
698
699     // Delete all lock files, that don't have an associated directory. They must
700     // be some kind of leftover
701     for (lock_file_name, directory_name) in &lock_file_to_session_dir {
702         if directory_name.is_none() {
703             let timestamp = match extract_timestamp_from_session_dir(lock_file_name) {
704                 Ok(timestamp) => timestamp,
705                 Err(()) => {
706                     debug!("Found lock-file with malformed timestamp: {}",
707                         crate_directory.join(&lock_file_name).display());
708                     // Ignore it
709                     continue
710                 }
711             };
712
713             let lock_file_path = crate_directory.join(&**lock_file_name);
714
715             if is_old_enough_to_be_collected(timestamp) {
716                 debug!("garbage_collect_session_directories() - deleting \
717                         garbage lock file: {}", lock_file_path.display());
718                 delete_session_dir_lock_file(sess, &lock_file_path);
719             } else {
720                 debug!("garbage_collect_session_directories() - lock file with \
721                         no session dir not old enough to be collected: {}",
722                        lock_file_path.display());
723             }
724         }
725     }
726
727     // Filter out `None` directories
728     let lock_file_to_session_dir: FxHashMap<String, String> =
729         lock_file_to_session_dir.into_iter()
730                                 .filter_map(|(lock_file_name, directory_name)| {
731                                     directory_name.map(|n| (lock_file_name, n))
732                                 })
733                                 .collect();
734
735     let mut deletion_candidates = vec![];
736     let mut definitely_delete = vec![];
737
738     for (lock_file_name, directory_name) in &lock_file_to_session_dir {
739         debug!("garbage_collect_session_directories() - inspecting: {}",
740                 directory_name);
741
742         let timestamp = match extract_timestamp_from_session_dir(directory_name) {
743             Ok(timestamp) => timestamp,
744             Err(()) => {
745                 debug!("Found session-dir with malformed timestamp: {}",
746                         crate_directory.join(directory_name).display());
747                 // Ignore it
748                 continue
749             }
750         };
751
752         if is_finalized(directory_name) {
753             let lock_file_path = crate_directory.join(lock_file_name);
754             match flock::Lock::new(&lock_file_path,
755                                    false,  // don't wait
756                                    false,  // don't create the lock-file
757                                    true) { // get an exclusive lock
758                 Ok(lock) => {
759                     debug!("garbage_collect_session_directories() - \
760                             successfully acquired lock");
761                     debug!("garbage_collect_session_directories() - adding \
762                             deletion candidate: {}", directory_name);
763
764                     // Note that we are holding on to the lock
765                     deletion_candidates.push((timestamp,
766                                               crate_directory.join(directory_name),
767                                               Some(lock)));
768                 }
769                 Err(_) => {
770                     debug!("garbage_collect_session_directories() - \
771                             not collecting, still in use");
772                 }
773             }
774         } else if is_old_enough_to_be_collected(timestamp) {
775             // When cleaning out "-working" session directories, i.e.
776             // session directories that might still be in use by another
777             // compiler instance, we only look a directories that are
778             // at least ten seconds old. This is supposed to reduce the
779             // chance of deleting a directory in the time window where
780             // the process has allocated the directory but has not yet
781             // acquired the file-lock on it.
782
783             // Try to acquire the directory lock. If we can't, it
784             // means that the owning process is still alive and we
785             // leave this directory alone.
786             let lock_file_path = crate_directory.join(lock_file_name);
787             match flock::Lock::new(&lock_file_path,
788                                    false,  // don't wait
789                                    false,  // don't create the lock-file
790                                    true) { // get an exclusive lock
791                 Ok(lock) => {
792                     debug!("garbage_collect_session_directories() - \
793                             successfully acquired lock");
794
795                     // Note that we are holding on to the lock
796                     definitely_delete.push((crate_directory.join(directory_name),
797                                             Some(lock)));
798                 }
799                 Err(_) => {
800                     debug!("garbage_collect_session_directories() - \
801                             not collecting, still in use");
802                 }
803             }
804         } else {
805             debug!("garbage_collect_session_directories() - not finalized, not \
806                     old enough");
807         }
808     }
809
810     // Delete all but the most recent of the candidates
811     for (path, lock) in all_except_most_recent(deletion_candidates) {
812         debug!("garbage_collect_session_directories() - deleting `{}`",
813                 path.display());
814
815         if let Err(err) = safe_remove_dir_all(&path) {
816             sess.warn(&format!("Failed to garbage collect finalized incremental \
817                                 compilation session directory `{}`: {}",
818                                path.display(),
819                                err));
820         } else {
821             delete_session_dir_lock_file(sess, &lock_file_path(&path));
822         }
823
824
825         // Let's make it explicit that the file lock is released at this point,
826         // or rather, that we held on to it until here
827         mem::drop(lock);
828     }
829
830     for (path, lock) in definitely_delete {
831         debug!("garbage_collect_session_directories() - deleting `{}`",
832                 path.display());
833
834         if let Err(err) = safe_remove_dir_all(&path) {
835             sess.warn(&format!("Failed to garbage collect incremental \
836                                 compilation session directory `{}`: {}",
837                                path.display(),
838                                err));
839         } else {
840             delete_session_dir_lock_file(sess, &lock_file_path(&path));
841         }
842
843         // Let's make it explicit that the file lock is released at this point,
844         // or rather, that we held on to it until here
845         mem::drop(lock);
846     }
847
848     Ok(())
849 }
850
851 fn all_except_most_recent(deletion_candidates: Vec<(SystemTime, PathBuf, Option<flock::Lock>)>)
852                           -> FxHashMap<PathBuf, Option<flock::Lock>> {
853     let most_recent = deletion_candidates.iter()
854                                          .map(|&(timestamp, ..)| timestamp)
855                                          .max();
856
857     if let Some(most_recent) = most_recent {
858         deletion_candidates.into_iter()
859                            .filter(|&(timestamp, ..)| timestamp != most_recent)
860                            .map(|(_, path, lock)| (path, lock))
861                            .collect()
862     } else {
863         FxHashMap()
864     }
865 }
866
867 /// Since paths of artifacts within session directories can get quite long, we
868 /// need to support deleting files with very long paths. The regular
869 /// WinApi functions only support paths up to 260 characters, however. In order
870 /// to circumvent this limitation, we canonicalize the path of the directory
871 /// before passing it to std::fs::remove_dir_all(). This will convert the path
872 /// into the '\\?\' format, which supports much longer paths.
873 fn safe_remove_dir_all(p: &Path) -> io::Result<()> {
874     if p.exists() {
875         let canonicalized = try!(p.canonicalize());
876         std_fs::remove_dir_all(canonicalized)
877     } else {
878         Ok(())
879     }
880 }
881
882 fn safe_remove_file(p: &Path) -> io::Result<()> {
883     if p.exists() {
884         let canonicalized = try!(p.canonicalize());
885         std_fs::remove_file(canonicalized)
886     } else {
887         Ok(())
888     }
889 }
890
891 #[test]
892 fn test_all_except_most_recent() {
893     assert_eq!(all_except_most_recent(
894         vec![
895             (UNIX_EPOCH + Duration::new(4, 0), PathBuf::from("4"), None),
896             (UNIX_EPOCH + Duration::new(1, 0), PathBuf::from("1"), None),
897             (UNIX_EPOCH + Duration::new(5, 0), PathBuf::from("5"), None),
898             (UNIX_EPOCH + Duration::new(3, 0), PathBuf::from("3"), None),
899             (UNIX_EPOCH + Duration::new(2, 0), PathBuf::from("2"), None),
900         ]).keys().cloned().collect::<FxHashSet<PathBuf>>(),
901         vec![
902             PathBuf::from("1"),
903             PathBuf::from("2"),
904             PathBuf::from("3"),
905             PathBuf::from("4"),
906         ].into_iter().collect::<FxHashSet<PathBuf>>()
907     );
908
909     assert_eq!(all_except_most_recent(
910         vec![
911         ]).keys().cloned().collect::<FxHashSet<PathBuf>>(),
912         FxHashSet()
913     );
914 }
915
916 #[test]
917 fn test_timestamp_serialization() {
918     for i in 0 .. 1_000u64 {
919         let time = UNIX_EPOCH + Duration::new(i * 1_434_578, (i as u32) * 239_000);
920         let s = timestamp_to_string(time);
921         assert_eq!(Ok(time), string_to_timestamp(&s));
922     }
923 }
924
925 #[test]
926 fn test_find_source_directory_in_iter() {
927     let already_visited = FxHashSet();
928
929     // Find newest
930     assert_eq!(find_source_directory_in_iter(
931         vec![PathBuf::from("crate-dir/s-3234-0000-svh"),
932              PathBuf::from("crate-dir/s-2234-0000-svh"),
933              PathBuf::from("crate-dir/s-1234-0000-svh")].into_iter(), &already_visited),
934         Some(PathBuf::from("crate-dir/s-3234-0000-svh")));
935
936     // Filter out "-working"
937     assert_eq!(find_source_directory_in_iter(
938         vec![PathBuf::from("crate-dir/s-3234-0000-working"),
939              PathBuf::from("crate-dir/s-2234-0000-svh"),
940              PathBuf::from("crate-dir/s-1234-0000-svh")].into_iter(), &already_visited),
941         Some(PathBuf::from("crate-dir/s-2234-0000-svh")));
942
943     // Handle empty
944     assert_eq!(find_source_directory_in_iter(vec![].into_iter(), &already_visited),
945                None);
946
947     // Handle only working
948     assert_eq!(find_source_directory_in_iter(
949         vec![PathBuf::from("crate-dir/s-3234-0000-working"),
950              PathBuf::from("crate-dir/s-2234-0000-working"),
951              PathBuf::from("crate-dir/s-1234-0000-working")].into_iter(), &already_visited),
952         None);
953 }