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