gc.cc 25 KB

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