1 //===-CachePruning.cpp - LLVM Cache Directory Pruning ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the pruning of a directory based on least recently used.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/CachePruning.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/Errc.h"
18 #include "llvm/Support/Error.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/raw_ostream.h"
23 #define DEBUG_TYPE "cache-pruning"
26 #include <system_error>
32 sys::TimePoint
<> Time
;
36 /// Used to determine which files to prune first. Also used to determine
37 /// set membership, so must take into account all fields.
38 bool operator<(const FileInfo
&Other
) const {
39 if (Time
< Other
.Time
)
41 else if (Other
.Time
< Time
)
43 if (Other
.Size
< Size
)
45 else if (Size
< Other
.Size
)
47 return Path
< Other
.Path
;
50 } // anonymous namespace
52 /// Write a new timestamp file with the given path. This is used for the pruning
54 static void writeTimestampFile(StringRef TimestampFile
) {
56 raw_fd_ostream
Out(TimestampFile
.str(), EC
, sys::fs::F_None
);
59 static Expected
<std::chrono::seconds
> parseDuration(StringRef Duration
) {
61 return make_error
<StringError
>("Duration must not be empty",
62 inconvertibleErrorCode());
64 StringRef NumStr
= Duration
.slice(0, Duration
.size()-1);
66 if (NumStr
.getAsInteger(0, Num
))
67 return make_error
<StringError
>("'" + NumStr
+ "' not an integer",
68 inconvertibleErrorCode());
70 switch (Duration
.back()) {
72 return std::chrono::seconds(Num
);
74 return std::chrono::minutes(Num
);
76 return std::chrono::hours(Num
);
78 return make_error
<StringError
>("'" + Duration
+
79 "' must end with one of 's', 'm' or 'h'",
80 inconvertibleErrorCode());
84 Expected
<CachePruningPolicy
>
85 llvm::parseCachePruningPolicy(StringRef PolicyStr
) {
86 CachePruningPolicy Policy
;
87 std::pair
<StringRef
, StringRef
> P
= {"", PolicyStr
};
88 while (!P
.second
.empty()) {
89 P
= P
.second
.split(':');
92 std::tie(Key
, Value
) = P
.first
.split('=');
93 if (Key
== "prune_interval") {
94 auto DurationOrErr
= parseDuration(Value
);
96 return DurationOrErr
.takeError();
97 Policy
.Interval
= *DurationOrErr
;
98 } else if (Key
== "prune_after") {
99 auto DurationOrErr
= parseDuration(Value
);
101 return DurationOrErr
.takeError();
102 Policy
.Expiration
= *DurationOrErr
;
103 } else if (Key
== "cache_size") {
104 if (Value
.back() != '%')
105 return make_error
<StringError
>("'" + Value
+ "' must be a percentage",
106 inconvertibleErrorCode());
107 StringRef SizeStr
= Value
.drop_back();
109 if (SizeStr
.getAsInteger(0, Size
))
110 return make_error
<StringError
>("'" + SizeStr
+ "' not an integer",
111 inconvertibleErrorCode());
113 return make_error
<StringError
>("'" + SizeStr
+
114 "' must be between 0 and 100",
115 inconvertibleErrorCode());
116 Policy
.MaxSizePercentageOfAvailableSpace
= Size
;
117 } else if (Key
== "cache_size_bytes") {
119 switch (tolower(Value
.back())) {
122 Value
= Value
.drop_back();
126 Value
= Value
.drop_back();
129 Mult
= 1024 * 1024 * 1024;
130 Value
= Value
.drop_back();
134 if (Value
.getAsInteger(0, Size
))
135 return make_error
<StringError
>("'" + Value
+ "' not an integer",
136 inconvertibleErrorCode());
137 Policy
.MaxSizeBytes
= Size
* Mult
;
138 } else if (Key
== "cache_size_files") {
139 if (Value
.getAsInteger(0, Policy
.MaxSizeFiles
))
140 return make_error
<StringError
>("'" + Value
+ "' not an integer",
141 inconvertibleErrorCode());
143 return make_error
<StringError
>("Unknown key: '" + Key
+ "'",
144 inconvertibleErrorCode());
151 /// Prune the cache of files that haven't been accessed in a long time.
152 bool llvm::pruneCache(StringRef Path
, CachePruningPolicy Policy
) {
153 using namespace std::chrono
;
159 if (sys::fs::is_directory(Path
, isPathDir
))
165 Policy
.MaxSizePercentageOfAvailableSpace
=
166 std::min(Policy
.MaxSizePercentageOfAvailableSpace
, 100u);
168 if (Policy
.Expiration
== seconds(0) &&
169 Policy
.MaxSizePercentageOfAvailableSpace
== 0 &&
170 Policy
.MaxSizeBytes
== 0 && Policy
.MaxSizeFiles
== 0) {
171 LLVM_DEBUG(dbgs() << "No pruning settings set, exit early\n");
172 // Nothing will be pruned, early exit
176 // Try to stat() the timestamp file.
177 SmallString
<128> TimestampFile(Path
);
178 sys::path::append(TimestampFile
, "llvmcache.timestamp");
179 sys::fs::file_status FileStatus
;
180 const auto CurrentTime
= system_clock::now();
181 if (auto EC
= sys::fs::status(TimestampFile
, FileStatus
)) {
182 if (EC
== errc::no_such_file_or_directory
) {
183 // If the timestamp file wasn't there, create one now.
184 writeTimestampFile(TimestampFile
);
190 if (!Policy
.Interval
)
192 if (Policy
.Interval
!= seconds(0)) {
193 // Check whether the time stamp is older than our pruning interval.
194 // If not, do nothing.
195 const auto TimeStampModTime
= FileStatus
.getLastModificationTime();
196 auto TimeStampAge
= CurrentTime
- TimeStampModTime
;
197 if (TimeStampAge
<= *Policy
.Interval
) {
198 LLVM_DEBUG(dbgs() << "Timestamp file too recent ("
199 << duration_cast
<seconds
>(TimeStampAge
).count()
200 << "s old), do not prune.\n");
204 // Write a new timestamp file so that nobody else attempts to prune.
205 // There is a benign race condition here, if two processes happen to
206 // notice at the same time that the timestamp is out-of-date.
207 writeTimestampFile(TimestampFile
);
210 // Keep track of files to delete to get below the size limit.
211 // Order by time of last use so that recently used files are preserved.
212 std::set
<FileInfo
> FileInfos
;
213 uint64_t TotalSize
= 0;
215 // Walk the entire directory cache, looking for unused files.
217 SmallString
<128> CachePathNative
;
218 sys::path::native(Path
, CachePathNative
);
219 // Walk all of the files within this directory.
220 for (sys::fs::directory_iterator
File(CachePathNative
, EC
), FileEnd
;
221 File
!= FileEnd
&& !EC
; File
.increment(EC
)) {
222 // Ignore any files not beginning with the string "llvmcache-". This
223 // includes the timestamp file as well as any files created by the user.
224 // This acts as a safeguard against data loss if the user specifies the
225 // wrong directory as their cache directory.
226 if (!sys::path::filename(File
->path()).startswith("llvmcache-"))
229 // Look at this file. If we can't stat it, there's nothing interesting
231 ErrorOr
<sys::fs::basic_file_status
> StatusOrErr
= File
->status();
233 LLVM_DEBUG(dbgs() << "Ignore " << File
->path() << " (can't stat)\n");
237 // If the file hasn't been used recently enough, delete it
238 const auto FileAccessTime
= StatusOrErr
->getLastAccessedTime();
239 auto FileAge
= CurrentTime
- FileAccessTime
;
240 if (Policy
.Expiration
!= seconds(0) && FileAge
> Policy
.Expiration
) {
241 LLVM_DEBUG(dbgs() << "Remove " << File
->path() << " ("
242 << duration_cast
<seconds
>(FileAge
).count()
244 sys::fs::remove(File
->path());
248 // Leave it here for now, but add it to the list of size-based pruning.
249 TotalSize
+= StatusOrErr
->getSize();
250 FileInfos
.insert({FileAccessTime
, StatusOrErr
->getSize(), File
->path()});
253 auto FileInfo
= FileInfos
.begin();
254 size_t NumFiles
= FileInfos
.size();
256 auto RemoveCacheFile
= [&]() {
258 sys::fs::remove(FileInfo
->Path
);
260 TotalSize
-= FileInfo
->Size
;
262 LLVM_DEBUG(dbgs() << " - Remove " << FileInfo
->Path
<< " (size "
263 << FileInfo
->Size
<< "), new occupancy is " << TotalSize
268 // Prune for number of files.
269 if (Policy
.MaxSizeFiles
)
270 while (NumFiles
> Policy
.MaxSizeFiles
)
273 // Prune for size now if needed
274 if (Policy
.MaxSizePercentageOfAvailableSpace
> 0 || Policy
.MaxSizeBytes
> 0) {
275 auto ErrOrSpaceInfo
= sys::fs::disk_space(Path
);
276 if (!ErrOrSpaceInfo
) {
277 report_fatal_error("Can't get available size");
279 sys::fs::space_info SpaceInfo
= ErrOrSpaceInfo
.get();
280 auto AvailableSpace
= TotalSize
+ SpaceInfo
.free
;
282 if (Policy
.MaxSizePercentageOfAvailableSpace
== 0)
283 Policy
.MaxSizePercentageOfAvailableSpace
= 100;
284 if (Policy
.MaxSizeBytes
== 0)
285 Policy
.MaxSizeBytes
= AvailableSpace
;
286 auto TotalSizeTarget
= std::min
<uint64_t>(
287 AvailableSpace
* Policy
.MaxSizePercentageOfAvailableSpace
/ 100ull,
288 Policy
.MaxSizeBytes
);
290 LLVM_DEBUG(dbgs() << "Occupancy: " << ((100 * TotalSize
) / AvailableSpace
)
292 << Policy
.MaxSizePercentageOfAvailableSpace
<< "%, "
293 << Policy
.MaxSizeBytes
<< " bytes\n");
295 // Remove the oldest accessed files first, till we get below the threshold.
296 while (TotalSize
> TotalSizeTarget
&& FileInfo
!= FileInfos
.end())