runtimes_cache.h 18 KB

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