1 //===-CachePruning.cpp - LLVM Cache Directory Pruning ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the pruning of a directory based on least recently used.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Support/CachePruning.h"
15 
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 #define DEBUG_TYPE "cache-pruning"
22 
23 #include <set>
24 
25 using namespace llvm;
26 
27 /// Write a new timestamp file with the given path. This is used for the pruning
28 /// interval option.
29 static void writeTimestampFile(StringRef TimestampFile) {
30   std::error_code EC;
31   raw_fd_ostream Out(TimestampFile.str(), EC, sys::fs::F_None);
32 }
33 
34 /// Prune the cache of files that haven't been accessed in a long time.
35 bool CachePruning::prune() {
36   SmallString<128> TimestampFile(Path);
37   sys::path::append(TimestampFile, "llvmcache.timestamp");
38 
39   if (Expiration == 0 && PercentageOfAvailableSpace == 0) {
40     DEBUG(dbgs() << "No pruning settings set, exit early\n");
41     // Nothing will be pruned, early exit
42     return false;
43   }
44 
45   // Try to stat() the timestamp file.
46   sys::fs::file_status FileStatus;
47   sys::TimeValue CurrentTime = sys::TimeValue::now();
48   if (sys::fs::status(TimestampFile, FileStatus)) {
49     if (errno == ENOENT) {
50       // If the timestamp file wasn't there, create one now.
51       writeTimestampFile(TimestampFile);
52     } else {
53       // Unknown error?
54       return false;
55     }
56   } else {
57     if (Interval) {
58       // Check whether the time stamp is older than our pruning interval.
59       // If not, do nothing.
60       sys::TimeValue TimeStampModTime = FileStatus.getLastModificationTime();
61       auto TimeInterval = sys::TimeValue(sys::TimeValue::SecondsType(Interval));
62       auto TimeStampAge = CurrentTime - TimeStampModTime;
63       if (TimeStampAge <= TimeInterval) {
64         DEBUG(dbgs() << "Timestamp file too recent (" << TimeStampAge.seconds()
65                      << "s old), do not prune.\n");
66         return false;
67       }
68     }
69     // Write a new timestamp file so that nobody else attempts to prune.
70     // There is a benign race condition here, if two processes happen to
71     // notice at the same time that the timestamp is out-of-date.
72     writeTimestampFile(TimestampFile);
73   }
74 
75   bool ShouldComputeSize = (PercentageOfAvailableSpace > 0);
76 
77   // Keep track of space
78   std::set<std::pair<uint64_t, std::string>> FileSizes;
79   uint64_t TotalSize = 0;
80   // Helper to add a path to the set of files to consider for size-based
81   // pruning, sorted by last accessed time.
82   auto AddToFileListForSizePruning =
83       [&](StringRef Path, sys::TimeValue FileAccessTime) {
84         if (!ShouldComputeSize)
85           return;
86         TotalSize += FileStatus.getSize();
87         FileSizes.insert(
88             std::make_pair(FileStatus.getSize(), std::string(Path)));
89       };
90 
91   // Walk the entire directory cache, looking for unused files.
92   std::error_code EC;
93   SmallString<128> CachePathNative;
94   sys::path::native(Path, CachePathNative);
95   auto TimeExpiration = sys::TimeValue(sys::TimeValue::SecondsType(Expiration));
96   // Walk all of the files within this directory.
97   for (sys::fs::directory_iterator File(CachePathNative, EC), FileEnd;
98        File != FileEnd && !EC; File.increment(EC)) {
99     // Do not touch the timestamp.
100     if (File->path() == TimestampFile)
101       continue;
102 
103     // Look at this file. If we can't stat it, there's nothing interesting
104     // there.
105     if (sys::fs::status(File->path(), FileStatus)) {
106       DEBUG(dbgs() << "Ignore " << File->path() << " (can't stat)\n");
107       continue;
108     }
109 
110     // If the file hasn't been used recently enough, delete it
111     sys::TimeValue FileAccessTime = FileStatus.getLastAccessedTime();
112     auto FileAge = CurrentTime - FileAccessTime;
113     if (FileAge > TimeExpiration) {
114       DEBUG(dbgs() << "Remove " << File->path() << " (" << FileAge.seconds()
115                    << "s old)\n");
116       sys::fs::remove(File->path());
117       continue;
118     }
119 
120     // Leave it here for now, but add it to the list of size-based pruning.
121     AddToFileListForSizePruning(File->path(), FileAccessTime);
122   }
123 
124   // Prune for size now if needed
125   if (ShouldComputeSize) {
126     auto ErrOrSpaceInfo = sys::fs::disk_space(Path);
127     if (!ErrOrSpaceInfo) {
128       report_fatal_error("Can't get available size");
129     }
130     sys::fs::space_info SpaceInfo = ErrOrSpaceInfo.get();
131     auto AvailableSpace = TotalSize + SpaceInfo.free;
132     auto FileAndSize = FileSizes.rbegin();
133     DEBUG(dbgs() << "Occupancy: " << ((100 * TotalSize) / AvailableSpace)
134                  << "% target is: " << PercentageOfAvailableSpace << "\n");
135     // Remove the oldest accessed files first, till we get below the threshold
136     while (((100 * TotalSize) / AvailableSpace) > PercentageOfAvailableSpace &&
137            FileAndSize != FileSizes.rend()) {
138       // Remove the file.
139       sys::fs::remove(FileAndSize->second);
140       // Update size
141       TotalSize -= FileAndSize->first;
142       DEBUG(dbgs() << " - Remove " << FileAndSize->second << " (size "
143                    << FileAndSize->first << "), new occupancy is " << TotalSize
144                    << "%\n");
145       ++FileAndSize;
146     }
147   }
148   return true;
149 }
150