runtimes_cache.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_DRIVER_RUNTIMES_CACHE_H_
  5. #define CARBON_TOOLCHAIN_DRIVER_RUNTIMES_CACHE_H_
  6. #include <chrono>
  7. #include <filesystem>
  8. #include <utility>
  9. #include "common/check.h"
  10. #include "common/error.h"
  11. #include "common/filesystem.h"
  12. #include "common/ostream.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "toolchain/base/install_paths.h"
  16. namespace Carbon {
  17. // Manages a runtimes directory.
  18. //
  19. // Carbon (including Clang) relies on a set of runtime libraries and data files.
  20. // These are organized into a directory modeled by a `Runtimes` object, with
  21. // different components of those runtimes built into subdirectories. The
  22. // `Runtimes` object in turn provides access to each of these subdirectories.
  23. //
  24. // Different components are managed in separate directories based on how they
  25. // are _built_, and each one may contain a mixture of one or more runtime
  26. // libraries or data files. The separation of each component is so that we don't
  27. // force building all of them in a configuration where only one makes sense or
  28. // is typically needed.
  29. //
  30. // Beyond providing access, a `Runtimes` object also supports orchestrating the
  31. // build of these components into their designated subdirectories, including
  32. // synchronizing between different threads or processes trying to build the same
  33. // component.
  34. //
  35. // TODO: Add libc++ to the runtimes tree.
  36. // TODO: Add the Core library to the runtimes tree.
  37. class Runtimes {
  38. public:
  39. class Builder;
  40. class Cache;
  41. enum Component {
  42. ClangResourceDir,
  43. LibUnwind,
  44. Libcxx,
  45. NumComponents,
  46. };
  47. // Creates a `Runtimes` object for a specific existing directory.
  48. //
  49. // Requires that the `path` is an absolute path that is an existing directory.
  50. static auto Make(std::filesystem::path path,
  51. llvm::raw_ostream* vlog_stream = nullptr)
  52. -> ErrorOr<Runtimes>;
  53. // Default construction produces an unformed runtimes that can only be
  54. // assigned to or destroyed.
  55. Runtimes() = default;
  56. // A specific runtimes object is move-only as it owns the relevant filesystem
  57. // resources.
  58. Runtimes(Runtimes&& arg) noexcept
  59. : base_path_(std::move(arg.base_path_)),
  60. base_dir_(std::exchange(arg.base_dir_, {})),
  61. lock_file_(std::exchange(arg.lock_file_, {})),
  62. flock_(std::exchange(arg.flock_, {})),
  63. vlog_stream_(arg.vlog_stream_) {}
  64. auto operator=(Runtimes&& arg) noexcept -> Runtimes& {
  65. Destroy();
  66. base_path_ = std::move(arg.base_path_);
  67. base_dir_ = std::exchange(arg.base_dir_, {});
  68. lock_file_ = std::exchange(arg.lock_file_, {});
  69. flock_ = std::exchange(arg.flock_, {});
  70. vlog_stream_ = arg.vlog_stream_;
  71. return *this;
  72. }
  73. ~Runtimes() { Destroy(); }
  74. // The base path for the runtimes.
  75. auto base_path() const -> const std::filesystem::path& { return base_path_; }
  76. // The base directory for the runtimes.
  77. auto base_dir() const -> Filesystem::DirRef { return base_dir_; }
  78. // Gets the path to an _existing_ Clang resource directory.
  79. //
  80. // Clang's resource directory contains all of the compiler-builtin runtime
  81. // libraries, headers, and data files.
  82. //
  83. // This will return the path to the Clang resource directory if it exists in
  84. // the runtimes tree. Otherwise, it will return an error.
  85. auto Get(Component component) -> ErrorOr<std::filesystem::path>;
  86. // Builds or returns a Clang resource directory.
  87. //
  88. // If there is an existing, built Clang resource directory, this will return
  89. // its path, the same as `GetExistingClangResourceDir` would. However, if
  90. // there is not yet a Clang resource directory in this runtimes tree, returns
  91. // a `Builder` object that can be used to build and commit a Clang resource
  92. // directory to this runtimes tree.
  93. auto Build(Component component)
  94. -> ErrorOr<std::variant<std::filesystem::path, Builder>>;
  95. private:
  96. friend Builder;
  97. friend Cache;
  98. friend class RuntimesTestPeer;
  99. // The deadline for acquiring a lock to build a new component of the runtimes.
  100. // This needs to be quite large as this is how long racing processes or
  101. // threads will wait to allow some other process to complete building the
  102. // component. The result is that this should be significantly longer than the
  103. // expected slowest-to-build component.
  104. //
  105. // Note, nothing goes _wrong_ if this deadline is exceeded, but multiple
  106. // copies of the component may end up being built and all but one thrown away.
  107. static constexpr Filesystem::Duration BuildLockDeadline =
  108. std::chrono::seconds(200);
  109. // The interval at which to poll for a build lock. This needs to be small
  110. // enough that we don't waste an excessive amount of time if a build of the
  111. // component completes *just* after a poll. Typically, that means we want this
  112. // to be significant lower than the expected time it would take to build the
  113. // component. Note that we don't poll if the component has been completely
  114. // built prior to the query coming in, so this doesn't form the _minimum_ time
  115. // to find a component of the runtimes tree.
  116. static constexpr Filesystem::Duration BuildLockPollInterval =
  117. std::chrono::milliseconds(200);
  118. // The path to the clang resource directory within the runtimes tree.
  119. //
  120. // This uses `std::string_view` to simply using with paths.
  121. static constexpr auto ComponentPath(Component component) -> std::string_view {
  122. switch (component) {
  123. case ClangResourceDir:
  124. return "clang_resource_dir";
  125. case LibUnwind:
  126. return "libunwind";
  127. case Libcxx:
  128. return "libcxx";
  129. case NumComponents:
  130. CARBON_FATAL("Invalid component");
  131. }
  132. }
  133. // A format string used to form the lock file for a given directory in the
  134. // runtimes tree. This needs to be C-string, so directly expose the character
  135. // array.
  136. static constexpr char LockFileFormat[] = ".{0}.lock";
  137. explicit Runtimes(std::filesystem::path base_path, Filesystem::Dir base_dir,
  138. Filesystem::WriteFile lock_file, Filesystem::FileLock flock,
  139. llvm::raw_ostream* vlog_stream = nullptr)
  140. : base_path_(std::move(base_path)),
  141. base_dir_(std::move(base_dir)),
  142. lock_file_(std::move(lock_file)),
  143. flock_(std::move(flock)),
  144. vlog_stream_(vlog_stream) {
  145. CARBON_CHECK(base_path_.is_absolute(),
  146. "The base path must be absolute: {0}", base_path_);
  147. }
  148. // Implementation of building the Clang resource directory. This exposes the
  149. // deadline and poll interval to allow testing with artificial values.
  150. auto BuildImpl(Component component, Filesystem::Duration deadline,
  151. Filesystem::Duration poll_interval)
  152. -> ErrorOr<std::variant<std::filesystem::path, Builder>>;
  153. auto Destroy() -> void;
  154. std::filesystem::path base_path_;
  155. Filesystem::Dir base_dir_;
  156. Filesystem::WriteFile lock_file_;
  157. Filesystem::FileLock flock_;
  158. llvm::raw_ostream* vlog_stream_ = nullptr;
  159. };
  160. // A managed cache of `Runtimes` directories.
  161. //
  162. // This class manages and provides access to a cache of runtimes. Each entry in
  163. // the cache is a runtimes directory for a specific set of `Feature`s,
  164. // represented by an object of the `Runtimes` type. An entry is sometimes
  165. // referred to simply as the "runtimes" in a specific context. Each of these
  166. // entries can consist of one or more components that together make up a
  167. // collection of runtime libraries, runtime data files, or other runtime
  168. // resources. However, entries are never combined -- each entry represents a
  169. // distinct target environment, potentially ABI, and set of runtimes that could
  170. // be used.
  171. //
  172. // The cache looks up entries based on the set of `Feature`s and the input
  173. // sources used to build them (including the compiler itself). Whenever looking
  174. // up an entry not already present in the cache, the cache will evict old
  175. // entries before creating the new one. The eviction strategy is to remove any
  176. // entries more than a year old, as well as the least-recently used entries
  177. // until there will only be a maximum of 50 entries in the cache. The goal is to
  178. // allow multiple versions and build features to stay resident in the cache
  179. // while providing a stable upper bound on the disk space used.
  180. //
  181. // The cache can be formed around a specific directory, or it can search for a
  182. // system-default directory. The system default directory follows the guidance
  183. // of the XDG Base Directory Specification:
  184. // https://specifications.freedesktop.org/basedir-spec/latest/
  185. //
  186. // This tries to place the system cache in
  187. // `$XDG_CACHE_HOME/carbon_runtimes_cache`, followed by
  188. // `$HOME/.cache/carbon_runtimes_cache`. A fallback if neither works is to
  189. // create a temporary directory for the cache. This temporary directory is owned
  190. // by the `Cache` object and will be removed when it is destroyed.
  191. //
  192. // These system-wide paths are only used if the installation contains a digest
  193. // file that can be used to ensure different builds and installs of Carbon don't
  194. // incorrectly share cache entries built from different sources. When missing, a
  195. // temporary directory is used.
  196. class Runtimes::Cache {
  197. public:
  198. // The features of a cached runtimes directory.
  199. //
  200. // TODO: Add support for more build flags that we want to enable when building
  201. // runtimes such as sanitizers and CPU-specific optimizations.
  202. struct Features {
  203. std::string target;
  204. };
  205. Cache() = default;
  206. // The cache is move-only as it owns open resources for the cache directory.
  207. Cache(Cache&& arg) noexcept
  208. : vlog_stream_(arg.vlog_stream_),
  209. cache_key_(std::move(arg.cache_key_)),
  210. path_(std::move(arg.path_)),
  211. dir_owner_(std::exchange(arg.dir_owner_, {})),
  212. dir_(arg.dir_) {}
  213. auto operator=(Cache&& arg) noexcept -> Cache& {
  214. vlog_stream_ = arg.vlog_stream_;
  215. cache_key_ = std::move(arg.cache_key_);
  216. path_ = std::move(arg.path_);
  217. dir_owner_ = std::exchange(arg.dir_owner_, {});
  218. dir_ = arg.dir_;
  219. return *this;
  220. }
  221. // Creates a cache object for the current system.
  222. //
  223. // This will try to locate and use a persistent cache on the system if it can,
  224. // and otherwise fall back to creating a temporary cache. If either of these
  225. // hit unrecoverable errors, that error is returned instead. See the class
  226. // comment for more details about the overall strategy.
  227. static auto MakeSystem(const InstallPaths& install,
  228. llvm::raw_ostream* vlog_stream = nullptr)
  229. -> ErrorOr<Cache> {
  230. Cache cache(vlog_stream);
  231. CARBON_RETURN_IF_ERROR(cache.InitSystemCache(install));
  232. return cache;
  233. }
  234. // Creates a cache object referencing an explicit cache path.
  235. //
  236. // The path must be an existing, writable directory.
  237. static auto MakeCustom(const InstallPaths& install,
  238. std::filesystem::path cache_path,
  239. llvm::raw_ostream* vlog_stream = nullptr)
  240. -> ErrorOr<Cache> {
  241. Cache cache(vlog_stream);
  242. CARBON_RETURN_IF_ERROR(cache.InitCachePath(install, cache_path));
  243. return cache;
  244. }
  245. // The path to the cache directory.
  246. auto path() const -> const std::filesystem::path& { return path_; }
  247. // Looks up a runtimes directory in the cache.
  248. //
  249. // This will return a `Runtimes` object for the given features. If an entry
  250. // for these features does not exist in the cache, any stale cache entries
  251. // will be pruned if needed, and then a new entry will be created and
  252. // returned.
  253. auto Lookup(const Features& features) -> ErrorOr<Runtimes>;
  254. private:
  255. friend class RuntimesTestPeer;
  256. static constexpr int MinNumEntries = 10;
  257. static constexpr int MaxNumEntries = 50;
  258. // The maximum age of a cache entry. Cache entries older than this will always
  259. // evicted if there are more than the minimum number of entries.
  260. static constexpr auto MaxEntryAge = std::chrono::years(1);
  261. // The maximum age of a locked cache entry. Cache entries older than this will
  262. // be evicted if needed without regard to any held lock from a process
  263. // currently using that entry.
  264. static constexpr auto MaxLockedEntryAge = std::chrono::days(10);
  265. // Entries are locked while in use to avoid them being removed concurrently,
  266. // but the lock will be disregarded for entries older than
  267. // `MaxLockedEntryAge`. We use a relatively short deadline and fast poll
  268. // interval here as this is on the critical path even for an existing, built
  269. // runtimes entry.
  270. static constexpr auto RuntimesLockDeadline = std::chrono::milliseconds(100);
  271. static constexpr auto RuntimesLockPollInterval = std::chrono::milliseconds(1);
  272. struct Entry {
  273. std::filesystem::path path;
  274. Filesystem::Duration age;
  275. };
  276. explicit Cache(llvm::raw_ostream* vlog_stream) : vlog_stream_(vlog_stream) {}
  277. // Tries to find a viable cache root.
  278. //
  279. // This must be an existing directory, not one we create. We use the XDG base
  280. // directory specification as the basis for these directories:
  281. // https://specifications.freedesktop.org/basedir-spec/
  282. //
  283. // Note that there is a concept of a "runtimes" directory in this spec, but it
  284. // uses a different meaning of the term "runtimes" than ours. Runtimes for
  285. // Carbon are cached, persistent built library data, not something that only
  286. // exists during the running of the Carbon tool like a socket.
  287. auto FindXdgCachePath() -> std::optional<std::filesystem::path>;
  288. // Initializes a system cache in a temporary directory.
  289. //
  290. // The cache will create and own a temporary directory, removing it on
  291. // destruction. This limits the caching lifetime but is used as a fallback
  292. // when unable to create a persistent cache.
  293. auto InitTmpSystemCache() -> ErrorOr<Success>;
  294. // Helper function implementing the logic for `MakeSystem`.
  295. auto InitSystemCache(const InstallPaths& install) -> ErrorOr<Success>;
  296. // Helper function implementing the logic for `MakeCustom`.
  297. auto InitCachePath(const InstallPaths& install,
  298. std::filesystem::path cache_path) -> ErrorOr<Success>;
  299. // Computes the ages for each input path, and combines the path and age into
  300. // the returned vector of `Entry` objects. This consumes the input paths when
  301. // building the output `Entry` structs, and so accepts the vector of paths by
  302. // value.
  303. auto ComputeEntryAges(llvm::SmallVector<std::filesystem::path> entry_paths)
  304. -> llvm::SmallVector<Entry>;
  305. // Prunes stale cache entries sufficiently to insert the provided new entry
  306. // path into the cache without growing it beyond the thresholds for the cache
  307. // size.
  308. //
  309. // Errors during pruning are logged rather than returned as this is expected
  310. // to be a background operation and not something we can always recover from.
  311. auto PruneStaleRuntimes(const std::filesystem::path& new_entry_path) -> void;
  312. llvm::raw_ostream* vlog_stream_ = nullptr;
  313. std::string cache_key_;
  314. std::filesystem::path path_;
  315. std::variant<Filesystem::Dir, Filesystem::RemovingDir> dir_owner_;
  316. // A reference to whichever form of `dir_owner_` is in use.
  317. Filesystem::DirRef dir_;
  318. };
  319. // Builder for a new directory in a runtimes tree.
  320. //
  321. // This manages a staging directory for the build that will then be committed
  322. // into the destination once fully built.
  323. class Runtimes::Builder : public Printable<Builder> {
  324. public:
  325. Builder(Builder&& arg) noexcept
  326. : runtimes_(std::exchange(arg.runtimes_, nullptr)),
  327. lock_file_(std::exchange(arg.lock_file_, {})),
  328. flock_(std::exchange(arg.flock_, {})),
  329. dir_(std::exchange(arg.dir_, {})),
  330. dest_(arg.dest_) {}
  331. auto operator=(Builder&& arg) noexcept -> Builder& {
  332. Destroy();
  333. runtimes_ = std::exchange(arg.runtimes_, nullptr);
  334. lock_file_ = std::exchange(arg.lock_file_, {});
  335. flock_ = std::exchange(arg.flock_, {});
  336. dir_ = std::exchange(arg.dir_, {});
  337. dest_ = arg.dest_;
  338. return *this;
  339. }
  340. ~Builder() { Destroy(); }
  341. // The build's staging directory.
  342. auto dir() const -> Filesystem::DirRef { return dir_; }
  343. // The build's staging directory path.
  344. auto path() const -> const std::filesystem::path& { return dir_.abs_path(); }
  345. // Commits the new runtime to the cache.
  346. //
  347. // This will move the contents of the temporary directory to the final
  348. // destination in the cache.
  349. auto Commit() && -> ErrorOr<std::filesystem::path>;
  350. auto Print(llvm::raw_ostream& out) const -> void {
  351. out << "Runtimes::Builder{.path = '" << path() << "'}";
  352. }
  353. private:
  354. friend Runtimes;
  355. friend class RuntimesTestPeer;
  356. Builder() = default;
  357. explicit Builder(Runtimes& runtimes, Filesystem::ReadWriteFile lock_file,
  358. Filesystem::FileLock flock, Filesystem::RemovingDir tmp_dir,
  359. std::string_view dest)
  360. : runtimes_(&runtimes),
  361. vlog_stream_(runtimes.vlog_stream_),
  362. lock_file_(std::move(lock_file)),
  363. flock_(std::move(flock)),
  364. dir_(std::move(tmp_dir)),
  365. dest_(dest) {}
  366. auto ReleaseFileLock() -> void;
  367. auto Destroy() -> void;
  368. Runtimes* runtimes_ = nullptr;
  369. llvm::raw_ostream* vlog_stream_ = nullptr;
  370. Filesystem::ReadWriteFile lock_file_;
  371. Filesystem::FileLock flock_;
  372. Filesystem::RemovingDir dir_;
  373. std::string_view dest_;
  374. };
  375. } // namespace Carbon
  376. #endif // CARBON_TOOLCHAIN_DRIVER_RUNTIMES_CACHE_H_