blob: 7a2f6c53435ad751a6aa30ee9ad4f6c6d527526a [file] [log] [blame]
Mehdi Amini27814982016-04-02 03:28:26 +00001//===-CachePruning.cpp - LLVM Cache Directory Pruning ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Mehdi Amini27814982016-04-02 03:28:26 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the pruning of a directory based on least recently used.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Support/CachePruning.h"
14
Mehdi Amini045d4752016-04-18 21:54:00 +000015#include "llvm/Support/Debug.h"
NAKAMURA Takumif5e36ad2016-05-14 14:21:39 +000016#include "llvm/Support/Errc.h"
Peter Collingbourned1eac7b2017-03-16 03:42:00 +000017#include "llvm/Support/Error.h"
Mehdi Amini27814982016-04-02 03:28:26 +000018#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/Path.h"
20#include "llvm/Support/raw_ostream.h"
21
Mehdi Amini045d4752016-04-18 21:54:00 +000022#define DEBUG_TYPE "cache-pruning"
23
Mehdi Amini27814982016-04-02 03:28:26 +000024#include <set>
Vassil Vassilev2ec8b152016-09-14 08:55:18 +000025#include <system_error>
Mehdi Amini27814982016-04-02 03:28:26 +000026
27using namespace llvm;
28
Bob Haarman481d2242018-08-22 00:52:16 +000029namespace {
30struct FileInfo {
31 sys::TimePoint<> Time;
32 uint64_t Size;
33 std::string Path;
34
35 /// Used to determine which files to prune first. Also used to determine
36 /// set membership, so must take into account all fields.
37 bool operator<(const FileInfo &Other) const {
Fangrui Songa0f9c4f2019-04-21 06:17:40 +000038 return std::tie(Time, Other.Size, Path) <
39 std::tie(Other.Time, Size, Other.Path);
Bob Haarman481d2242018-08-22 00:52:16 +000040 }
41};
42} // anonymous namespace
43
Mehdi Amini27814982016-04-02 03:28:26 +000044/// Write a new timestamp file with the given path. This is used for the pruning
45/// interval option.
46static void writeTimestampFile(StringRef TimestampFile) {
47 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +000048 raw_fd_ostream Out(TimestampFile.str(), EC, sys::fs::OF_None);
Mehdi Amini27814982016-04-02 03:28:26 +000049}
50
Peter Collingbourned1eac7b2017-03-16 03:42:00 +000051static Expected<std::chrono::seconds> parseDuration(StringRef Duration) {
52 if (Duration.empty())
53 return make_error<StringError>("Duration must not be empty",
54 inconvertibleErrorCode());
55
56 StringRef NumStr = Duration.slice(0, Duration.size()-1);
57 uint64_t Num;
58 if (NumStr.getAsInteger(0, Num))
59 return make_error<StringError>("'" + NumStr + "' not an integer",
60 inconvertibleErrorCode());
61
62 switch (Duration.back()) {
63 case 's':
64 return std::chrono::seconds(Num);
65 case 'm':
66 return std::chrono::minutes(Num);
67 case 'h':
68 return std::chrono::hours(Num);
69 default:
70 return make_error<StringError>("'" + Duration +
71 "' must end with one of 's', 'm' or 'h'",
72 inconvertibleErrorCode());
73 }
74}
75
76Expected<CachePruningPolicy>
77llvm::parseCachePruningPolicy(StringRef PolicyStr) {
78 CachePruningPolicy Policy;
79 std::pair<StringRef, StringRef> P = {"", PolicyStr};
80 while (!P.second.empty()) {
81 P = P.second.split(':');
82
83 StringRef Key, Value;
84 std::tie(Key, Value) = P.first.split('=');
85 if (Key == "prune_interval") {
86 auto DurationOrErr = parseDuration(Value);
87 if (!DurationOrErr)
Peter Collingbourne255c6e12017-03-16 03:54:38 +000088 return DurationOrErr.takeError();
Peter Collingbourned1eac7b2017-03-16 03:42:00 +000089 Policy.Interval = *DurationOrErr;
90 } else if (Key == "prune_after") {
91 auto DurationOrErr = parseDuration(Value);
92 if (!DurationOrErr)
Peter Collingbourne255c6e12017-03-16 03:54:38 +000093 return DurationOrErr.takeError();
Peter Collingbourned1eac7b2017-03-16 03:42:00 +000094 Policy.Expiration = *DurationOrErr;
95 } else if (Key == "cache_size") {
Peter Collingbourne15ab17202017-06-23 17:17:47 +000096 if (Value.back() != '%')
97 return make_error<StringError>("'" + Value + "' must be a percentage",
98 inconvertibleErrorCode());
Peter Collingbourne8d292232017-06-23 17:05:03 +000099 StringRef SizeStr = Value.drop_back();
Peter Collingbourned1eac7b2017-03-16 03:42:00 +0000100 uint64_t Size;
101 if (SizeStr.getAsInteger(0, Size))
102 return make_error<StringError>("'" + SizeStr + "' not an integer",
103 inconvertibleErrorCode());
104 if (Size > 100)
105 return make_error<StringError>("'" + SizeStr +
106 "' must be between 0 and 100",
107 inconvertibleErrorCode());
Peter Collingbourne8d292232017-06-23 17:05:03 +0000108 Policy.MaxSizePercentageOfAvailableSpace = Size;
109 } else if (Key == "cache_size_bytes") {
110 uint64_t Mult = 1;
Peter Collingbourne30aaa2f2017-06-23 17:13:51 +0000111 switch (tolower(Value.back())) {
Peter Collingbourne8d292232017-06-23 17:05:03 +0000112 case 'k':
113 Mult = 1024;
114 Value = Value.drop_back();
115 break;
116 case 'm':
117 Mult = 1024 * 1024;
118 Value = Value.drop_back();
119 break;
120 case 'g':
121 Mult = 1024 * 1024 * 1024;
122 Value = Value.drop_back();
123 break;
124 }
125 uint64_t Size;
126 if (Value.getAsInteger(0, Size))
127 return make_error<StringError>("'" + Value + "' not an integer",
128 inconvertibleErrorCode());
129 Policy.MaxSizeBytes = Size * Mult;
Peter Collingbourne048ac832017-11-22 18:27:31 +0000130 } else if (Key == "cache_size_files") {
131 if (Value.getAsInteger(0, Policy.MaxSizeFiles))
132 return make_error<StringError>("'" + Value + "' not an integer",
133 inconvertibleErrorCode());
Peter Collingbourned1eac7b2017-03-16 03:42:00 +0000134 } else {
135 return make_error<StringError>("Unknown key: '" + Key + "'",
136 inconvertibleErrorCode());
137 }
138 }
139
140 return Policy;
141}
142
Mehdi Amini27814982016-04-02 03:28:26 +0000143/// Prune the cache of files that haven't been accessed in a long time.
Peter Collingbournecead56f2017-03-15 22:54:18 +0000144bool llvm::pruneCache(StringRef Path, CachePruningPolicy Policy) {
Pavel Labath757ca882016-10-24 10:59:17 +0000145 using namespace std::chrono;
146
Mehdi Amini721800d2016-04-21 06:43:45 +0000147 if (Path.empty())
148 return false;
149
150 bool isPathDir;
151 if (sys::fs::is_directory(Path, isPathDir))
152 return false;
153
154 if (!isPathDir)
155 return false;
Mehdi Amini27814982016-04-02 03:28:26 +0000156
Peter Collingbourne8d292232017-06-23 17:05:03 +0000157 Policy.MaxSizePercentageOfAvailableSpace =
158 std::min(Policy.MaxSizePercentageOfAvailableSpace, 100u);
Peter Collingbournecead56f2017-03-15 22:54:18 +0000159
160 if (Policy.Expiration == seconds(0) &&
Peter Collingbourne8d292232017-06-23 17:05:03 +0000161 Policy.MaxSizePercentageOfAvailableSpace == 0 &&
Peter Collingbourne048ac832017-11-22 18:27:31 +0000162 Policy.MaxSizeBytes == 0 && Policy.MaxSizeFiles == 0) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000163 LLVM_DEBUG(dbgs() << "No pruning settings set, exit early\n");
Mehdi Amini27814982016-04-02 03:28:26 +0000164 // Nothing will be pruned, early exit
165 return false;
Mehdi Amini045d4752016-04-18 21:54:00 +0000166 }
Mehdi Amini27814982016-04-02 03:28:26 +0000167
168 // Try to stat() the timestamp file.
Mehdi Amini721800d2016-04-21 06:43:45 +0000169 SmallString<128> TimestampFile(Path);
170 sys::path::append(TimestampFile, "llvmcache.timestamp");
Mehdi Amini27814982016-04-02 03:28:26 +0000171 sys::fs::file_status FileStatus;
Ben Dunbobbinbb534b12017-12-22 18:32:15 +0000172 const auto CurrentTime = system_clock::now();
NAKAMURA Takumif5e36ad2016-05-14 14:21:39 +0000173 if (auto EC = sys::fs::status(TimestampFile, FileStatus)) {
174 if (EC == errc::no_such_file_or_directory) {
Mehdi Amini27814982016-04-02 03:28:26 +0000175 // If the timestamp file wasn't there, create one now.
176 writeTimestampFile(TimestampFile);
177 } else {
178 // Unknown error?
179 return false;
180 }
181 } else {
Ben Dunbobbinbb534b12017-12-22 18:32:15 +0000182 if (!Policy.Interval)
183 return false;
Ben Dunbobbincac52142017-11-17 14:42:18 +0000184 if (Policy.Interval != seconds(0)) {
Mehdi Amini27814982016-04-02 03:28:26 +0000185 // Check whether the time stamp is older than our pruning interval.
186 // If not, do nothing.
Ben Dunbobbinbb534b12017-12-22 18:32:15 +0000187 const auto TimeStampModTime = FileStatus.getLastModificationTime();
Mehdi Amini045d4752016-04-18 21:54:00 +0000188 auto TimeStampAge = CurrentTime - TimeStampModTime;
Ben Dunbobbinbb534b12017-12-22 18:32:15 +0000189 if (TimeStampAge <= *Policy.Interval) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000190 LLVM_DEBUG(dbgs() << "Timestamp file too recent ("
191 << duration_cast<seconds>(TimeStampAge).count()
192 << "s old), do not prune.\n");
Mehdi Amini27814982016-04-02 03:28:26 +0000193 return false;
Mehdi Amini045d4752016-04-18 21:54:00 +0000194 }
Mehdi Amini27814982016-04-02 03:28:26 +0000195 }
196 // Write a new timestamp file so that nobody else attempts to prune.
197 // There is a benign race condition here, if two processes happen to
198 // notice at the same time that the timestamp is out-of-date.
199 writeTimestampFile(TimestampFile);
200 }
201
Bob Haarman481d2242018-08-22 00:52:16 +0000202 // Keep track of files to delete to get below the size limit.
203 // Order by time of last use so that recently used files are preserved.
204 std::set<FileInfo> FileInfos;
Mehdi Amini27814982016-04-02 03:28:26 +0000205 uint64_t TotalSize = 0;
Mehdi Amini27814982016-04-02 03:28:26 +0000206
207 // Walk the entire directory cache, looking for unused files.
208 std::error_code EC;
209 SmallString<128> CachePathNative;
210 sys::path::native(Path, CachePathNative);
Mehdi Amini27814982016-04-02 03:28:26 +0000211 // Walk all of the files within this directory.
212 for (sys::fs::directory_iterator File(CachePathNative, EC), FileEnd;
213 File != FileEnd && !EC; File.increment(EC)) {
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000214 // Ignore any files not beginning with the string "llvmcache-". This
215 // includes the timestamp file as well as any files created by the user.
216 // This acts as a safeguard against data loss if the user specifies the
217 // wrong directory as their cache directory.
218 if (!sys::path::filename(File->path()).startswith("llvmcache-"))
Mehdi Amini27814982016-04-02 03:28:26 +0000219 continue;
220
221 // Look at this file. If we can't stat it, there's nothing interesting
222 // there.
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000223 ErrorOr<sys::fs::basic_file_status> StatusOrErr = File->status();
224 if (!StatusOrErr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000225 LLVM_DEBUG(dbgs() << "Ignore " << File->path() << " (can't stat)\n");
Mehdi Amini27814982016-04-02 03:28:26 +0000226 continue;
Mehdi Amini045d4752016-04-18 21:54:00 +0000227 }
Mehdi Amini27814982016-04-02 03:28:26 +0000228
229 // If the file hasn't been used recently enough, delete it
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000230 const auto FileAccessTime = StatusOrErr->getLastAccessedTime();
Mehdi Amini045d4752016-04-18 21:54:00 +0000231 auto FileAge = CurrentTime - FileAccessTime;
Peter Collingbourne048ac832017-11-22 18:27:31 +0000232 if (Policy.Expiration != seconds(0) && FileAge > Policy.Expiration) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000233 LLVM_DEBUG(dbgs() << "Remove " << File->path() << " ("
234 << duration_cast<seconds>(FileAge).count()
235 << "s old)\n");
Mehdi Amini27814982016-04-02 03:28:26 +0000236 sys::fs::remove(File->path());
237 continue;
238 }
239
240 // Leave it here for now, but add it to the list of size-based pruning.
Peter Collingbourne0dfdb442017-10-10 22:19:46 +0000241 TotalSize += StatusOrErr->getSize();
Bob Haarman481d2242018-08-22 00:52:16 +0000242 FileInfos.insert({FileAccessTime, StatusOrErr->getSize(), File->path()});
Mehdi Amini27814982016-04-02 03:28:26 +0000243 }
244
Bob Haarman481d2242018-08-22 00:52:16 +0000245 auto FileInfo = FileInfos.begin();
246 size_t NumFiles = FileInfos.size();
Peter Collingbourne048ac832017-11-22 18:27:31 +0000247
248 auto RemoveCacheFile = [&]() {
249 // Remove the file.
Bob Haarman481d2242018-08-22 00:52:16 +0000250 sys::fs::remove(FileInfo->Path);
Peter Collingbourne048ac832017-11-22 18:27:31 +0000251 // Update size
Bob Haarman481d2242018-08-22 00:52:16 +0000252 TotalSize -= FileInfo->Size;
Peter Collingbourne048ac832017-11-22 18:27:31 +0000253 NumFiles--;
Bob Haarman481d2242018-08-22 00:52:16 +0000254 LLVM_DEBUG(dbgs() << " - Remove " << FileInfo->Path << " (size "
255 << FileInfo->Size << "), new occupancy is " << TotalSize
256 << "%\n");
257 ++FileInfo;
Peter Collingbourne048ac832017-11-22 18:27:31 +0000258 };
259
260 // Prune for number of files.
261 if (Policy.MaxSizeFiles)
262 while (NumFiles > Policy.MaxSizeFiles)
263 RemoveCacheFile();
264
Mehdi Amini27814982016-04-02 03:28:26 +0000265 // Prune for size now if needed
Peter Collingbourne048ac832017-11-22 18:27:31 +0000266 if (Policy.MaxSizePercentageOfAvailableSpace > 0 || Policy.MaxSizeBytes > 0) {
Mehdi Amini27814982016-04-02 03:28:26 +0000267 auto ErrOrSpaceInfo = sys::fs::disk_space(Path);
268 if (!ErrOrSpaceInfo) {
269 report_fatal_error("Can't get available size");
270 }
271 sys::fs::space_info SpaceInfo = ErrOrSpaceInfo.get();
272 auto AvailableSpace = TotalSize + SpaceInfo.free;
Peter Collingbourne8d292232017-06-23 17:05:03 +0000273
274 if (Policy.MaxSizePercentageOfAvailableSpace == 0)
275 Policy.MaxSizePercentageOfAvailableSpace = 100;
276 if (Policy.MaxSizeBytes == 0)
277 Policy.MaxSizeBytes = AvailableSpace;
278 auto TotalSizeTarget = std::min<uint64_t>(
279 AvailableSpace * Policy.MaxSizePercentageOfAvailableSpace / 100ull,
280 Policy.MaxSizeBytes);
281
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000282 LLVM_DEBUG(dbgs() << "Occupancy: " << ((100 * TotalSize) / AvailableSpace)
283 << "% target is: "
284 << Policy.MaxSizePercentageOfAvailableSpace << "%, "
285 << Policy.MaxSizeBytes << " bytes\n");
Peter Collingbourne8d292232017-06-23 17:05:03 +0000286
Peter Collingbourne048ac832017-11-22 18:27:31 +0000287 // Remove the oldest accessed files first, till we get below the threshold.
Bob Haarman481d2242018-08-22 00:52:16 +0000288 while (TotalSize > TotalSizeTarget && FileInfo != FileInfos.end())
Peter Collingbourne048ac832017-11-22 18:27:31 +0000289 RemoveCacheFile();
Mehdi Amini27814982016-04-02 03:28:26 +0000290 }
291 return true;
292}