CachePruning.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //===-CachePruning.cpp - LLVM Cache Directory Pruning ---------------------===//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the pruning of a directory based on least recently used.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/CachePruning.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/Support/Debug.h"
  15. #include "llvm/Support/Errc.h"
  16. #include "llvm/Support/Error.h"
  17. #include "llvm/Support/FileSystem.h"
  18. #include "llvm/Support/Path.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #define DEBUG_TYPE "cache-pruning"
  21. #include <set>
  22. #include <system_error>
  23. using namespace llvm;
  24. namespace {
  25. struct FileInfo {
  26. sys::TimePoint<> Time;
  27. uint64_t Size;
  28. std::string Path;
  29. /// Used to determine which files to prune first. Also used to determine
  30. /// set membership, so must take into account all fields.
  31. bool operator<(const FileInfo &Other) const {
  32. return std::tie(Time, Other.Size, Path) <
  33. std::tie(Other.Time, Size, Other.Path);
  34. }
  35. };
  36. } // anonymous namespace
  37. /// Write a new timestamp file with the given path. This is used for the pruning
  38. /// interval option.
  39. static void writeTimestampFile(StringRef TimestampFile) {
  40. std::error_code EC;
  41. raw_fd_ostream Out(TimestampFile.str(), EC, sys::fs::OF_None);
  42. }
  43. static Expected<std::chrono::seconds> parseDuration(StringRef Duration) {
  44. if (Duration.empty())
  45. return make_error<StringError>("Duration must not be empty",
  46. inconvertibleErrorCode());
  47. StringRef NumStr = Duration.slice(0, Duration.size()-1);
  48. uint64_t Num;
  49. if (NumStr.getAsInteger(0, Num))
  50. return make_error<StringError>("'" + NumStr + "' not an integer",
  51. inconvertibleErrorCode());
  52. switch (Duration.back()) {
  53. case 's':
  54. return std::chrono::seconds(Num);
  55. case 'm':
  56. return std::chrono::minutes(Num);
  57. case 'h':
  58. return std::chrono::hours(Num);
  59. default:
  60. return make_error<StringError>("'" + Duration +
  61. "' must end with one of 's', 'm' or 'h'",
  62. inconvertibleErrorCode());
  63. }
  64. }
  65. Expected<CachePruningPolicy>
  66. llvm::parseCachePruningPolicy(StringRef PolicyStr) {
  67. CachePruningPolicy Policy;
  68. std::pair<StringRef, StringRef> P = {"", PolicyStr};
  69. while (!P.second.empty()) {
  70. P = P.second.split(':');
  71. StringRef Key, Value;
  72. std::tie(Key, Value) = P.first.split('=');
  73. if (Key == "prune_interval") {
  74. auto DurationOrErr = parseDuration(Value);
  75. if (!DurationOrErr)
  76. return DurationOrErr.takeError();
  77. Policy.Interval = *DurationOrErr;
  78. } else if (Key == "prune_after") {
  79. auto DurationOrErr = parseDuration(Value);
  80. if (!DurationOrErr)
  81. return DurationOrErr.takeError();
  82. Policy.Expiration = *DurationOrErr;
  83. } else if (Key == "cache_size") {
  84. if (Value.back() != '%')
  85. return make_error<StringError>("'" + Value + "' must be a percentage",
  86. inconvertibleErrorCode());
  87. StringRef SizeStr = Value.drop_back();
  88. uint64_t Size;
  89. if (SizeStr.getAsInteger(0, Size))
  90. return make_error<StringError>("'" + SizeStr + "' not an integer",
  91. inconvertibleErrorCode());
  92. if (Size > 100)
  93. return make_error<StringError>("'" + SizeStr +
  94. "' must be between 0 and 100",
  95. inconvertibleErrorCode());
  96. Policy.MaxSizePercentageOfAvailableSpace = Size;
  97. } else if (Key == "cache_size_bytes") {
  98. uint64_t Mult = 1;
  99. switch (tolower(Value.back())) {
  100. case 'k':
  101. Mult = 1024;
  102. Value = Value.drop_back();
  103. break;
  104. case 'm':
  105. Mult = 1024 * 1024;
  106. Value = Value.drop_back();
  107. break;
  108. case 'g':
  109. Mult = 1024 * 1024 * 1024;
  110. Value = Value.drop_back();
  111. break;
  112. }
  113. uint64_t Size;
  114. if (Value.getAsInteger(0, Size))
  115. return make_error<StringError>("'" + Value + "' not an integer",
  116. inconvertibleErrorCode());
  117. Policy.MaxSizeBytes = Size * Mult;
  118. } else if (Key == "cache_size_files") {
  119. if (Value.getAsInteger(0, Policy.MaxSizeFiles))
  120. return make_error<StringError>("'" + Value + "' not an integer",
  121. inconvertibleErrorCode());
  122. } else {
  123. return make_error<StringError>("Unknown key: '" + Key + "'",
  124. inconvertibleErrorCode());
  125. }
  126. }
  127. return Policy;
  128. }
  129. /// Prune the cache of files that haven't been accessed in a long time.
  130. bool llvm::pruneCache(StringRef Path, CachePruningPolicy Policy) {
  131. using namespace std::chrono;
  132. if (Path.empty())
  133. return false;
  134. bool isPathDir;
  135. if (sys::fs::is_directory(Path, isPathDir))
  136. return false;
  137. if (!isPathDir)
  138. return false;
  139. Policy.MaxSizePercentageOfAvailableSpace =
  140. std::min(Policy.MaxSizePercentageOfAvailableSpace, 100u);
  141. if (Policy.Expiration == seconds(0) &&
  142. Policy.MaxSizePercentageOfAvailableSpace == 0 &&
  143. Policy.MaxSizeBytes == 0 && Policy.MaxSizeFiles == 0) {
  144. LLVM_DEBUG(dbgs() << "No pruning settings set, exit early\n");
  145. // Nothing will be pruned, early exit
  146. return false;
  147. }
  148. // Try to stat() the timestamp file.
  149. SmallString<128> TimestampFile(Path);
  150. sys::path::append(TimestampFile, "llvmcache.timestamp");
  151. sys::fs::file_status FileStatus;
  152. const auto CurrentTime = system_clock::now();
  153. if (auto EC = sys::fs::status(TimestampFile, FileStatus)) {
  154. if (EC == errc::no_such_file_or_directory) {
  155. // If the timestamp file wasn't there, create one now.
  156. writeTimestampFile(TimestampFile);
  157. } else {
  158. // Unknown error?
  159. return false;
  160. }
  161. } else {
  162. if (!Policy.Interval)
  163. return false;
  164. if (Policy.Interval != seconds(0)) {
  165. // Check whether the time stamp is older than our pruning interval.
  166. // If not, do nothing.
  167. const auto TimeStampModTime = FileStatus.getLastModificationTime();
  168. auto TimeStampAge = CurrentTime - TimeStampModTime;
  169. if (TimeStampAge <= *Policy.Interval) {
  170. LLVM_DEBUG(dbgs() << "Timestamp file too recent ("
  171. << duration_cast<seconds>(TimeStampAge).count()
  172. << "s old), do not prune.\n");
  173. return false;
  174. }
  175. }
  176. // Write a new timestamp file so that nobody else attempts to prune.
  177. // There is a benign race condition here, if two processes happen to
  178. // notice at the same time that the timestamp is out-of-date.
  179. writeTimestampFile(TimestampFile);
  180. }
  181. // Keep track of files to delete to get below the size limit.
  182. // Order by time of last use so that recently used files are preserved.
  183. std::set<FileInfo> FileInfos;
  184. uint64_t TotalSize = 0;
  185. // Walk the entire directory cache, looking for unused files.
  186. std::error_code EC;
  187. SmallString<128> CachePathNative;
  188. sys::path::native(Path, CachePathNative);
  189. // Walk all of the files within this directory.
  190. for (sys::fs::directory_iterator File(CachePathNative, EC), FileEnd;
  191. File != FileEnd && !EC; File.increment(EC)) {
  192. // Ignore filenames not beginning with "llvmcache-" or "Thin-". This
  193. // includes the timestamp file as well as any files created by the user.
  194. // This acts as a safeguard against data loss if the user specifies the
  195. // wrong directory as their cache directory.
  196. StringRef filename = sys::path::filename(File->path());
  197. if (!filename.startswith("llvmcache-") && !filename.startswith("Thin-"))
  198. continue;
  199. // Look at this file. If we can't stat it, there's nothing interesting
  200. // there.
  201. ErrorOr<sys::fs::basic_file_status> StatusOrErr = File->status();
  202. if (!StatusOrErr) {
  203. LLVM_DEBUG(dbgs() << "Ignore " << File->path() << " (can't stat)\n");
  204. continue;
  205. }
  206. // If the file hasn't been used recently enough, delete it
  207. const auto FileAccessTime = StatusOrErr->getLastAccessedTime();
  208. auto FileAge = CurrentTime - FileAccessTime;
  209. if (Policy.Expiration != seconds(0) && FileAge > Policy.Expiration) {
  210. LLVM_DEBUG(dbgs() << "Remove " << File->path() << " ("
  211. << duration_cast<seconds>(FileAge).count()
  212. << "s old)\n");
  213. sys::fs::remove(File->path());
  214. continue;
  215. }
  216. // Leave it here for now, but add it to the list of size-based pruning.
  217. TotalSize += StatusOrErr->getSize();
  218. FileInfos.insert({FileAccessTime, StatusOrErr->getSize(), File->path()});
  219. }
  220. auto FileInfo = FileInfos.begin();
  221. size_t NumFiles = FileInfos.size();
  222. auto RemoveCacheFile = [&]() {
  223. // Remove the file.
  224. sys::fs::remove(FileInfo->Path);
  225. // Update size
  226. TotalSize -= FileInfo->Size;
  227. NumFiles--;
  228. LLVM_DEBUG(dbgs() << " - Remove " << FileInfo->Path << " (size "
  229. << FileInfo->Size << "), new occupancy is " << TotalSize
  230. << "%\n");
  231. ++FileInfo;
  232. };
  233. // Prune for number of files.
  234. if (Policy.MaxSizeFiles)
  235. while (NumFiles > Policy.MaxSizeFiles)
  236. RemoveCacheFile();
  237. // Prune for size now if needed
  238. if (Policy.MaxSizePercentageOfAvailableSpace > 0 || Policy.MaxSizeBytes > 0) {
  239. auto ErrOrSpaceInfo = sys::fs::disk_space(Path);
  240. if (!ErrOrSpaceInfo) {
  241. report_fatal_error("Can't get available size");
  242. }
  243. sys::fs::space_info SpaceInfo = ErrOrSpaceInfo.get();
  244. auto AvailableSpace = TotalSize + SpaceInfo.free;
  245. if (Policy.MaxSizePercentageOfAvailableSpace == 0)
  246. Policy.MaxSizePercentageOfAvailableSpace = 100;
  247. if (Policy.MaxSizeBytes == 0)
  248. Policy.MaxSizeBytes = AvailableSpace;
  249. auto TotalSizeTarget = std::min<uint64_t>(
  250. AvailableSpace * Policy.MaxSizePercentageOfAvailableSpace / 100ull,
  251. Policy.MaxSizeBytes);
  252. LLVM_DEBUG(dbgs() << "Occupancy: " << ((100 * TotalSize) / AvailableSpace)
  253. << "% target is: "
  254. << Policy.MaxSizePercentageOfAvailableSpace << "%, "
  255. << Policy.MaxSizeBytes << " bytes\n");
  256. // Remove the oldest accessed files first, till we get below the threshold.
  257. while (TotalSize > TotalSizeTarget && FileInfo != FileInfos.end())
  258. RemoveCacheFile();
  259. }
  260. return true;
  261. }