runtimes_cache.h 17 KB

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