runtimes_cache.h 17 KB

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