gc.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. #include "globals.hh"
  2. #include "misc.hh"
  3. #include "local-store.hh"
  4. #include <functional>
  5. #include <queue>
  6. #include <algorithm>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <errno.h>
  10. #include <fcntl.h>
  11. #include <unistd.h>
  12. #include <climits>
  13. namespace nix {
  14. static string gcLockName = "gc.lock";
  15. static string tempRootsDir = "temproots";
  16. static string gcRootsDir = "gcroots";
  17. /* Acquire the global GC lock. This is used to prevent new build
  18. processes from starting after the temporary root files have been
  19. read. To be precise: when they try to create a new temporary root
  20. file, they will block until the garbage collector has finished /
  21. yielded the GC lock. */
  22. int LocalStore::openGCLock(LockType lockType)
  23. {
  24. Path fnGCLock = (format("%1%/%2%")
  25. % settings.nixStateDir % gcLockName).str();
  26. debug(format("acquiring global GC lock `%1%'") % fnGCLock);
  27. AutoCloseFD fdGCLock = open(fnGCLock.c_str(), O_RDWR | O_CREAT, 0600);
  28. if (fdGCLock == -1)
  29. throw SysError(format("opening global GC lock `%1%'") % fnGCLock);
  30. closeOnExec(fdGCLock);
  31. if (!lockFile(fdGCLock, lockType, false)) {
  32. printMsg(lvlError, format("waiting for the big garbage collector lock..."));
  33. lockFile(fdGCLock, lockType, true);
  34. }
  35. /* !!! Restrict read permission on the GC root. Otherwise any
  36. process that can open the file for reading can DoS the
  37. collector. */
  38. return fdGCLock.borrow();
  39. }
  40. static void makeSymlink(const Path & link, const Path & target)
  41. {
  42. /* Create directories up to `gcRoot'. */
  43. createDirs(dirOf(link));
  44. /* Create the new symlink. */
  45. Path tempLink = (format("%1%.tmp-%2%-%3%")
  46. % link % getpid() % rand()).str();
  47. createSymlink(target, tempLink);
  48. /* Atomically replace the old one. */
  49. if (rename(tempLink.c_str(), link.c_str()) == -1)
  50. throw SysError(format("cannot rename `%1%' to `%2%'")
  51. % tempLink % link);
  52. }
  53. void LocalStore::syncWithGC()
  54. {
  55. AutoCloseFD fdGCLock = openGCLock(ltRead);
  56. }
  57. void LocalStore::addIndirectRoot(const Path & path)
  58. {
  59. string hash = printHash32(hashString(htSHA1, path));
  60. Path realRoot = canonPath((format("%1%/%2%/auto/%3%")
  61. % settings.nixStateDir % gcRootsDir % hash).str());
  62. makeSymlink(realRoot, path);
  63. }
  64. Path addPermRoot(StoreAPI & store, const Path & _storePath,
  65. const Path & _gcRoot, bool indirect, bool allowOutsideRootsDir)
  66. {
  67. Path storePath(canonPath(_storePath));
  68. Path gcRoot(canonPath(_gcRoot));
  69. assertStorePath(storePath);
  70. if (isInStore(gcRoot))
  71. throw Error(format(
  72. "creating a garbage collector root (%1%) in the store is forbidden "
  73. "(are you running nix-build inside the store?)") % gcRoot);
  74. if (indirect) {
  75. /* Don't clobber the link if it already exists and doesn't
  76. point to the store. */
  77. if (pathExists(gcRoot) && (!isLink(gcRoot) || !isInStore(readLink(gcRoot))))
  78. throw Error(format("cannot create symlink `%1%'; already exists") % gcRoot);
  79. makeSymlink(gcRoot, storePath);
  80. store.addIndirectRoot(gcRoot);
  81. }
  82. else {
  83. if (!allowOutsideRootsDir) {
  84. Path rootsDir = canonPath((format("%1%/%2%") % settings.nixStateDir % gcRootsDir).str());
  85. if (string(gcRoot, 0, rootsDir.size() + 1) != rootsDir + "/")
  86. throw Error(format(
  87. "path `%1%' is not a valid garbage collector root; "
  88. "it's not in the directory `%2%'")
  89. % gcRoot % rootsDir);
  90. }
  91. if (baseNameOf(gcRoot) == baseNameOf(storePath))
  92. writeFile(gcRoot, "");
  93. else
  94. makeSymlink(gcRoot, storePath);
  95. }
  96. /* Check that the root can be found by the garbage collector.
  97. !!! This can be very slow on machines that have many roots.
  98. Instead of reading all the roots, it would be more efficient to
  99. check if the root is in a directory in or linked from the
  100. gcroots directory. */
  101. if (settings.checkRootReachability) {
  102. Roots roots = store.findRoots();
  103. if (roots.find(gcRoot) == roots.end())
  104. printMsg(lvlError,
  105. format(
  106. "warning: `%1%' is not in a directory where the garbage collector looks for roots; "
  107. "therefore, `%2%' might be removed by the garbage collector")
  108. % gcRoot % storePath);
  109. }
  110. /* Grab the global GC root, causing us to block while a GC is in
  111. progress. This prevents the set of permanent roots from
  112. increasing while a GC is in progress. */
  113. store.syncWithGC();
  114. return gcRoot;
  115. }
  116. void LocalStore::addTempRoot(const Path & path)
  117. {
  118. /* Create the temporary roots file for this process. */
  119. if (fdTempRoots == -1) {
  120. while (1) {
  121. Path dir = (format("%1%/%2%") % settings.nixStateDir % tempRootsDir).str();
  122. createDirs(dir);
  123. fnTempRoots = (format("%1%/%2%")
  124. % dir % getpid()).str();
  125. AutoCloseFD fdGCLock = openGCLock(ltRead);
  126. if (pathExists(fnTempRoots))
  127. /* It *must* be stale, since there can be no two
  128. processes with the same pid. */
  129. unlink(fnTempRoots.c_str());
  130. fdTempRoots = openLockFile(fnTempRoots, true);
  131. fdGCLock.close();
  132. debug(format("acquiring read lock on `%1%'") % fnTempRoots);
  133. lockFile(fdTempRoots, ltRead, true);
  134. /* Check whether the garbage collector didn't get in our
  135. way. */
  136. struct stat st;
  137. if (fstat(fdTempRoots, &st) == -1)
  138. throw SysError(format("statting `%1%'") % fnTempRoots);
  139. if (st.st_size == 0) break;
  140. /* The garbage collector deleted this file before we could
  141. get a lock. (It won't delete the file after we get a
  142. lock.) Try again. */
  143. }
  144. }
  145. /* Upgrade the lock to a write lock. This will cause us to block
  146. if the garbage collector is holding our lock. */
  147. debug(format("acquiring write lock on `%1%'") % fnTempRoots);
  148. lockFile(fdTempRoots, ltWrite, true);
  149. string s = path + '\0';
  150. writeFull(fdTempRoots, s);
  151. /* Downgrade to a read lock. */
  152. debug(format("downgrading to read lock on `%1%'") % fnTempRoots);
  153. lockFile(fdTempRoots, ltRead, true);
  154. }
  155. typedef std::shared_ptr<AutoCloseFD> FDPtr;
  156. typedef list<FDPtr> FDs;
  157. static void readTempRoots(PathSet & tempRoots, FDs & fds)
  158. {
  159. /* Read the `temproots' directory for per-process temporary root
  160. files. */
  161. DirEntries tempRootFiles = readDirectory(
  162. (format("%1%/%2%") % settings.nixStateDir % tempRootsDir).str());
  163. for (auto & i : tempRootFiles) {
  164. Path path = (format("%1%/%2%/%3%") % settings.nixStateDir % tempRootsDir % i.name).str();
  165. debug(format("reading temporary root file `%1%'") % path);
  166. FDPtr fd(new AutoCloseFD(open(path.c_str(), O_RDWR, 0666)));
  167. if (*fd == -1) {
  168. /* It's okay if the file has disappeared. */
  169. if (errno == ENOENT) continue;
  170. throw SysError(format("opening temporary roots file `%1%'") % path);
  171. }
  172. /* This should work, but doesn't, for some reason. */
  173. //FDPtr fd(new AutoCloseFD(openLockFile(path, false)));
  174. //if (*fd == -1) continue;
  175. /* Try to acquire a write lock without blocking. This can
  176. only succeed if the owning process has died. In that case
  177. we don't care about its temporary roots. */
  178. if (lockFile(*fd, ltWrite, false)) {
  179. printMsg(lvlError, format("removing stale temporary roots file `%1%'") % path);
  180. unlink(path.c_str());
  181. writeFull(*fd, "d");
  182. continue;
  183. }
  184. /* Acquire a read lock. This will prevent the owning process
  185. from upgrading to a write lock, therefore it will block in
  186. addTempRoot(). */
  187. debug(format("waiting for read lock on `%1%'") % path);
  188. lockFile(*fd, ltRead, true);
  189. /* Read the entire file. */
  190. string contents = readFile(*fd);
  191. /* Extract the roots. */
  192. string::size_type pos = 0, end;
  193. while ((end = contents.find((char) 0, pos)) != string::npos) {
  194. Path root(contents, pos, end - pos);
  195. debug(format("got temporary root `%1%'") % root);
  196. assertStorePath(root);
  197. tempRoots.insert(root);
  198. pos = end + 1;
  199. }
  200. fds.push_back(fd); /* keep open */
  201. }
  202. }
  203. static void foundRoot(StoreAPI & store,
  204. const Path & path, const Path & target, Roots & roots)
  205. {
  206. Path storePath = toStorePath(target);
  207. if (store.isValidPath(storePath))
  208. roots[path] = storePath;
  209. else
  210. printMsg(lvlInfo, format("skipping invalid root from `%1%' to `%2%'") % path % storePath);
  211. }
  212. static void findRoots(StoreAPI & store, const Path & path, unsigned char type, Roots & roots)
  213. {
  214. try {
  215. if (type == DT_UNKNOWN)
  216. type = getFileType(path);
  217. if (type == DT_DIR) {
  218. for (auto & i : readDirectory(path))
  219. findRoots(store, path + "/" + i.name, i.type, roots);
  220. }
  221. else if (type == DT_LNK) {
  222. Path target = readLink(path);
  223. if (isInStore(target))
  224. foundRoot(store, path, target, roots);
  225. /* Handle indirect roots. */
  226. else {
  227. target = absPath(target, dirOf(path));
  228. if (!pathExists(target)) {
  229. if (isInDir(path, settings.nixStateDir + "/" + gcRootsDir + "/auto")) {
  230. printMsg(lvlInfo, format("removing stale link from `%1%' to `%2%'") % path % target);
  231. unlink(path.c_str());
  232. }
  233. } else {
  234. struct stat st2 = lstat(target);
  235. if (!S_ISLNK(st2.st_mode)) return;
  236. Path target2 = readLink(target);
  237. if (isInStore(target2)) foundRoot(store, target, target2, roots);
  238. }
  239. }
  240. }
  241. else if (type == DT_REG) {
  242. Path storePath = settings.nixStore + "/" + baseNameOf(path);
  243. if (store.isValidPath(storePath))
  244. roots[path] = storePath;
  245. }
  246. }
  247. catch (SysError & e) {
  248. /* We only ignore permanent failures. */
  249. if (e.errNo == EACCES || e.errNo == ENOENT || e.errNo == ENOTDIR)
  250. printMsg(lvlInfo, format("cannot read potential root `%1%'") % path);
  251. else
  252. throw;
  253. }
  254. }
  255. Roots LocalStore::findRoots()
  256. {
  257. Roots roots;
  258. /* Process direct roots in {gcroots,manifests,profiles}. */
  259. nix::findRoots(*this, settings.nixStateDir + "/" + gcRootsDir, DT_UNKNOWN, roots);
  260. if (pathExists(settings.nixStateDir + "/manifests"))
  261. nix::findRoots(*this, settings.nixStateDir + "/manifests", DT_UNKNOWN, roots);
  262. nix::findRoots(*this, settings.nixStateDir + "/profiles", DT_UNKNOWN, roots);
  263. return roots;
  264. }
  265. static void addAdditionalRoots(StoreAPI & store, PathSet & roots)
  266. {
  267. debug(format("executing `%1% gc --list-busy' to find additional roots")
  268. % settings.guixProgram);
  269. const Strings args = { "gc", "--list-busy" };
  270. string result = runProgram(settings.guixProgram, false, args);
  271. StringSet paths = tokenizeString<StringSet>(result, "\n");
  272. foreach (StringSet::iterator, i, paths) {
  273. if (isInStore(*i)) {
  274. Path path = toStorePath(*i);
  275. if (roots.find(path) == roots.end() && store.isValidPath(path)) {
  276. debug(format("got additional root `%1%'") % path);
  277. roots.insert(path);
  278. }
  279. }
  280. }
  281. }
  282. struct GCLimitReached { };
  283. struct LocalStore::GCState
  284. {
  285. GCOptions options;
  286. GCResults & results;
  287. PathSet roots;
  288. PathSet tempRoots;
  289. PathSet dead;
  290. PathSet alive;
  291. bool gcKeepOutputs;
  292. bool gcKeepDerivations;
  293. unsigned long long bytesInvalidated;
  294. bool moveToTrash = true;
  295. Path trashDir;
  296. bool shouldDelete;
  297. GCState(GCResults & results_) : results(results_), bytesInvalidated(0) { }
  298. };
  299. bool LocalStore::isActiveTempFile(const GCState & state,
  300. const Path & path, const string & suffix)
  301. {
  302. return hasSuffix(path, suffix)
  303. && state.tempRoots.find(string(path, 0, path.size() - suffix.size())) != state.tempRoots.end();
  304. }
  305. void LocalStore::deleteGarbage(GCState & state, const Path & path)
  306. {
  307. unsigned long long bytesFreed;
  308. /* When deduplication is on, store items always have at least two links:
  309. the one at PATH, and one in /gnu/store/.links. In that case, increase
  310. bytesFreed when PATH has two or fewer links. */
  311. size_t linkThreshold =
  312. (settings.autoOptimiseStore && isStorePath(path)) ? 2 : 1;
  313. deletePath(path, bytesFreed, linkThreshold);
  314. state.results.bytesFreed += bytesFreed;
  315. }
  316. void LocalStore::deletePathRecursive(GCState & state, const Path & path)
  317. {
  318. checkInterrupt();
  319. unsigned long long size = 0;
  320. if (isValidPath(path)) {
  321. PathSet referrers;
  322. queryReferrers(path, referrers);
  323. foreach (PathSet::iterator, i, referrers)
  324. if (*i != path) deletePathRecursive(state, *i);
  325. size = queryPathInfo(path).narSize;
  326. invalidatePathChecked(path);
  327. }
  328. struct stat st;
  329. if (lstat(path.c_str(), &st)) {
  330. if (errno == ENOENT) return;
  331. throw SysError(format("getting status of %1%") % path);
  332. }
  333. if (state.options.maxFreed != ULLONG_MAX) {
  334. auto freed = state.results.bytesFreed + state.bytesInvalidated;
  335. double fraction = ((double) freed) / (double) state.options.maxFreed;
  336. unsigned int percentage = (fraction > 1. ? 1. : fraction) * 100.;
  337. printMsg(lvlInfo, format("[%1%%%] deleting '%2%'") % percentage % path);
  338. } else {
  339. auto freed = state.results.bytesFreed + state.bytesInvalidated;
  340. freed /= 1024ULL * 1024ULL;
  341. printMsg(lvlInfo, format("[%1% MiB] deleting '%2%'") % freed % path);
  342. }
  343. state.results.paths.insert(path);
  344. /* If the path is not a regular file or symlink, move it to the
  345. trash directory. The move is to ensure that later (when we're
  346. not holding the global GC lock) we can delete the path without
  347. being afraid that the path has become alive again. Otherwise
  348. delete it right away. */
  349. if (state.moveToTrash && S_ISDIR(st.st_mode)) {
  350. // Estimate the amount freed using the narSize field. FIXME:
  351. // if the path was not valid, need to determine the actual
  352. // size.
  353. try {
  354. if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
  355. throw SysError(format("making `%1%' writable") % path);
  356. Path tmp = state.trashDir + "/" + baseNameOf(path);
  357. if (rename(path.c_str(), tmp.c_str()))
  358. throw SysError(format("unable to rename `%1%' to `%2%'") % path % tmp);
  359. state.bytesInvalidated += size;
  360. } catch (SysError & e) {
  361. /* In a Docker container, rename(2) returns EXDEV when the source
  362. and destination are not both on the "top layer". See:
  363. https://bugs.gnu.org/41607 */
  364. if (e.errNo == ENOSPC || e.errNo == EXDEV) {
  365. printMsg(lvlInfo, format("note: can't create move `%1%': %2%") % path % e.msg());
  366. deleteGarbage(state, path);
  367. }
  368. }
  369. } else
  370. deleteGarbage(state, path);
  371. if (state.results.bytesFreed + state.bytesInvalidated > state.options.maxFreed) {
  372. printMsg(lvlInfo, format("deleted or invalidated more than %1% bytes; stopping") % state.options.maxFreed);
  373. throw GCLimitReached();
  374. }
  375. }
  376. bool LocalStore::canReachRoot(GCState & state, PathSet & visited, const Path & path)
  377. {
  378. if (visited.find(path) != visited.end()) return false;
  379. if (state.alive.find(path) != state.alive.end()) {
  380. return true;
  381. }
  382. if (state.dead.find(path) != state.dead.end()) {
  383. return false;
  384. }
  385. if (state.roots.find(path) != state.roots.end()) {
  386. printMsg(lvlDebug, format("cannot delete `%1%' because it's a root") % path);
  387. state.alive.insert(path);
  388. return true;
  389. }
  390. visited.insert(path);
  391. if (!isValidPath(path)) return false;
  392. PathSet incoming;
  393. /* Don't delete this path if any of its referrers are alive. */
  394. queryReferrers(path, incoming);
  395. /* If gc-keep-derivations is set and this is a derivation, then
  396. don't delete the derivation if any of the outputs are alive. */
  397. if (state.gcKeepDerivations && isDerivation(path)) {
  398. PathSet outputs = queryDerivationOutputs(path);
  399. foreach (PathSet::iterator, i, outputs)
  400. if (isValidPath(*i) && queryDeriver(*i) == path)
  401. incoming.insert(*i);
  402. }
  403. /* If gc-keep-outputs is set, then don't delete this path if there
  404. are derivers of this path that are not garbage. */
  405. if (state.gcKeepOutputs) {
  406. PathSet derivers = queryValidDerivers(path);
  407. foreach (PathSet::iterator, i, derivers)
  408. incoming.insert(*i);
  409. }
  410. foreach (PathSet::iterator, i, incoming)
  411. if (*i != path)
  412. if (canReachRoot(state, visited, *i)) {
  413. state.alive.insert(path);
  414. return true;
  415. }
  416. return false;
  417. }
  418. void LocalStore::tryToDelete(GCState & state, const Path & path)
  419. {
  420. checkInterrupt();
  421. if (path == linksDir || path == state.trashDir) return;
  422. startNest(nest, lvlDebug, format("considering whether to delete `%1%'") % path);
  423. if (!isValidPath(path)) {
  424. /* A lock file belonging to a path that we're building right
  425. now isn't garbage. */
  426. if (isActiveTempFile(state, path, ".lock")) return;
  427. /* Don't delete .chroot directories for derivations that are
  428. currently being built. */
  429. if (isActiveTempFile(state, path, ".chroot")) return;
  430. }
  431. PathSet visited;
  432. if (canReachRoot(state, visited, path)) {
  433. printMsg(lvlDebug, format("cannot delete `%1%' because it's still reachable") % path);
  434. } else {
  435. /* No path we visited was a root, so everything is garbage.
  436. But we only delete ‘path’ and its referrers here so that
  437. ‘nix-store --delete’ doesn't have the unexpected effect of
  438. recursing into derivations and outputs. */
  439. state.dead.insert(visited.begin(), visited.end());
  440. if (state.shouldDelete)
  441. deletePathRecursive(state, path);
  442. }
  443. }
  444. /* Unlink all files in /nix/store/.links that have a link count of 1,
  445. which indicates that there are no other links and so they can be
  446. safely deleted. FIXME: race condition with optimisePath(): we
  447. might see a link count of 1 just before optimisePath() increases
  448. the link count. */
  449. void LocalStore::removeUnusedLinks(const GCState & state)
  450. {
  451. AutoCloseDir dir = opendir(linksDir.c_str());
  452. if (!dir) throw SysError(format("opening directory `%1%'") % linksDir);
  453. long long actualSize = 0, unsharedSize = 0;
  454. struct dirent * dirent;
  455. while (errno = 0, dirent = readdir(dir)) {
  456. checkInterrupt();
  457. string name = dirent->d_name;
  458. if (name == "." || name == "..") continue;
  459. Path path = linksDir + "/" + name;
  460. #ifdef HAVE_STATX
  461. # define st_size stx_size
  462. # define st_nlink stx_nlink
  463. static int statx_flags = AT_SYMLINK_NOFOLLOW | AT_STATX_DONT_SYNC;
  464. struct statx st;
  465. if (statx(AT_FDCWD, path.c_str(), statx_flags,
  466. STATX_SIZE | STATX_NLINK, &st) == -1) {
  467. if (errno == EINVAL) {
  468. /* Old 3.10 kernels (CentOS 7) don't support
  469. AT_STATX_DONT_SYNC, so try again without it. */
  470. statx_flags &= ~AT_STATX_DONT_SYNC;
  471. if (statx(AT_FDCWD, path.c_str(), statx_flags,
  472. STATX_SIZE | STATX_NLINK, &st) == -1)
  473. throw SysError(format("statting `%1%'") % path);
  474. } else {
  475. throw SysError(format("statting `%1%'") % path);
  476. }
  477. }
  478. #else
  479. struct stat st;
  480. if (lstat(path.c_str(), &st) == -1)
  481. throw SysError(format("statting `%1%'") % path);
  482. #endif
  483. /* Drop links for files smaller than 'deduplicationMinSize', even if
  484. they have more than one hard link. */
  485. if (st.st_nlink != 1 && st.st_size >= deduplicationMinSize) {
  486. actualSize += st.st_size;
  487. unsharedSize += (st.st_nlink - 1) * st.st_size;
  488. continue;
  489. }
  490. printMsg(lvlTalkative, format("deleting unused link `%1%'") % path);
  491. if (unlink(path.c_str()) == -1)
  492. throw SysError(format("deleting `%1%'") % path);
  493. state.results.bytesFreed += st.st_size;
  494. #undef st_size
  495. #undef st_nlink
  496. }
  497. struct stat st;
  498. if (stat(linksDir.c_str(), &st) == -1)
  499. throw SysError(format("statting `%1%'") % linksDir);
  500. long long overhead = st.st_size;
  501. printMsg(lvlInfo, format("note: currently hard linking saves %.2f MiB")
  502. % ((unsharedSize - actualSize - overhead) / (1024.0 * 1024.0)));
  503. }
  504. void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
  505. {
  506. GCState state(results);
  507. state.options = options;
  508. state.trashDir = settings.nixStore + "/trash";
  509. state.gcKeepOutputs = settings.gcKeepOutputs;
  510. state.gcKeepDerivations = settings.gcKeepDerivations;
  511. /* Using `--ignore-liveness' with `--delete' can have unintended
  512. consequences if `gc-keep-outputs' or `gc-keep-derivations' are
  513. true (the garbage collector will recurse into deleting the
  514. outputs or derivers, respectively). So disable them. */
  515. if (options.action == GCOptions::gcDeleteSpecific && options.ignoreLiveness) {
  516. state.gcKeepOutputs = false;
  517. state.gcKeepDerivations = false;
  518. }
  519. state.shouldDelete = options.action == GCOptions::gcDeleteDead || options.action == GCOptions::gcDeleteSpecific;
  520. /* Acquire the global GC root. This prevents
  521. a) New roots from being added.
  522. b) Processes from creating new temporary root files. */
  523. AutoCloseFD fdGCLock = openGCLock(ltWrite);
  524. /* Find the roots. Since we've grabbed the GC lock, the set of
  525. permanent roots cannot increase now. */
  526. printMsg(lvlError, format("finding garbage collector roots..."));
  527. Roots rootMap = options.ignoreLiveness ? Roots() : findRoots();
  528. foreach (Roots::iterator, i, rootMap) state.roots.insert(i->second);
  529. /* Add additional roots returned by 'guix gc --list-busy'. This is
  530. typically used to add running programs to the set of roots (to prevent
  531. them from being garbage collected). */
  532. if (!options.ignoreLiveness)
  533. addAdditionalRoots(*this, state.roots);
  534. /* Read the temporary roots. This acquires read locks on all
  535. per-process temporary root files. So after this point no paths
  536. can be added to the set of temporary roots. */
  537. FDs fds;
  538. readTempRoots(state.tempRoots, fds);
  539. state.roots.insert(state.tempRoots.begin(), state.tempRoots.end());
  540. /* After this point the set of roots or temporary roots cannot
  541. increase, since we hold locks on everything. So everything
  542. that is not reachable from `roots' is garbage. */
  543. if (state.shouldDelete) {
  544. if (pathExists(state.trashDir)) deleteGarbage(state, state.trashDir);
  545. try {
  546. createDirs(state.trashDir);
  547. } catch (SysError & e) {
  548. if (e.errNo == ENOSPC) {
  549. printMsg(lvlInfo, format("note: can't create trash directory: %1%") % e.msg());
  550. state.moveToTrash = false;
  551. }
  552. }
  553. }
  554. /* Now either delete all garbage paths, or just the specified
  555. paths (for gcDeleteSpecific). */
  556. if (options.action == GCOptions::gcDeleteSpecific) {
  557. foreach (PathSet::iterator, i, options.pathsToDelete) {
  558. assertStorePath(*i);
  559. tryToDelete(state, *i);
  560. if (state.dead.find(*i) == state.dead.end())
  561. throw Error(format("cannot delete path `%1%' since it is still alive") % *i);
  562. }
  563. } else if (options.maxFreed > 0) {
  564. if (state.shouldDelete)
  565. printMsg(lvlError, format("deleting garbage..."));
  566. else
  567. printMsg(lvlError, format("determining live/dead paths..."));
  568. try {
  569. AutoCloseDir dir = opendir(settings.nixStore.c_str());
  570. if (!dir) throw SysError(format("opening directory `%1%'") % settings.nixStore);
  571. /* Read the store and immediately delete all paths that
  572. aren't valid. When using --max-freed etc., deleting
  573. invalid paths is preferred over deleting unreachable
  574. paths, since unreachable paths could become reachable
  575. again. We don't use readDirectory() here so that GCing
  576. can start faster. */
  577. Paths entries;
  578. struct dirent * dirent;
  579. while (errno = 0, dirent = readdir(dir)) {
  580. checkInterrupt();
  581. string name = dirent->d_name;
  582. if (name == "." || name == "..") continue;
  583. Path path = settings.nixStore + "/" + name;
  584. if (isValidPath(path))
  585. entries.push_back(path);
  586. else
  587. tryToDelete(state, path);
  588. }
  589. dir.close();
  590. /* Now delete the unreachable valid paths. Randomise the
  591. order in which we delete entries to make the collector
  592. less biased towards deleting paths that come
  593. alphabetically first (e.g. /nix/store/000...). This
  594. matters when using --max-freed etc. */
  595. vector<Path> entries_(entries.begin(), entries.end());
  596. random_shuffle(entries_.begin(), entries_.end());
  597. foreach (vector<Path>::iterator, i, entries_)
  598. tryToDelete(state, *i);
  599. } catch (GCLimitReached & e) {
  600. }
  601. }
  602. if (state.options.action == GCOptions::gcReturnLive) {
  603. state.results.paths = state.alive;
  604. return;
  605. }
  606. if (state.options.action == GCOptions::gcReturnDead) {
  607. state.results.paths = state.dead;
  608. return;
  609. }
  610. /* Allow other processes to add to the store from here on. */
  611. fdGCLock.close();
  612. fds.clear();
  613. /* Delete the trash directory. */
  614. printMsg(lvlInfo, format("deleting `%1%'") % state.trashDir);
  615. deleteGarbage(state, state.trashDir);
  616. /* Clean up the links directory. */
  617. if (options.action == GCOptions::gcDeleteDead || options.action == GCOptions::gcDeleteSpecific) {
  618. printMsg(lvlError, format("deleting unused links..."));
  619. removeUnusedLinks(state);
  620. }
  621. /* While we're at it, vacuum the database. */
  622. //if (options.action == GCOptions::gcDeleteDead) vacuumDB();
  623. }
  624. }