optimise-store.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #include "config.h"
  2. #include "util.hh"
  3. #include "local-store.hh"
  4. #include "globals.hh"
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <unistd.h>
  10. #include <errno.h>
  11. #include <stdio.h>
  12. namespace nix {
  13. /* Any file smaller than this is not considered for deduplication.
  14. Keep in sync with (guix store deduplication). */
  15. const size_t deduplicationMinSize = 8192;
  16. static void makeWritable(const Path & path)
  17. {
  18. struct stat st;
  19. if (lstat(path.c_str(), &st))
  20. throw SysError(format("getting attributes of path `%1%'") % path);
  21. if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
  22. throw SysError(format("changing writability of `%1%'") % path);
  23. }
  24. struct MakeReadOnly
  25. {
  26. Path path;
  27. MakeReadOnly(const Path & path) : path(path) { }
  28. ~MakeReadOnly()
  29. {
  30. try {
  31. /* This will make the path read-only. */
  32. if (path != "") canonicaliseTimestampAndPermissions(path);
  33. } catch (...) {
  34. ignoreException();
  35. }
  36. }
  37. };
  38. LocalStore::InodeHash LocalStore::loadInodeHash()
  39. {
  40. printMsg(lvlDebug, "loading hash inodes in memory");
  41. InodeHash inodeHash;
  42. AutoCloseDir dir = opendir(linksDir.c_str());
  43. if (!dir) throw SysError(format("opening directory `%1%'") % linksDir);
  44. struct dirent * dirent;
  45. while (errno = 0, dirent = readdir(dir)) { /* sic */
  46. checkInterrupt();
  47. // We don't care if we hit non-hash files, anything goes
  48. inodeHash.insert(dirent->d_ino);
  49. }
  50. if (errno) throw SysError(format("reading directory `%1%'") % linksDir);
  51. printMsg(lvlTalkative, format("loaded %1% hash inodes") % inodeHash.size());
  52. return inodeHash;
  53. }
  54. Strings LocalStore::readDirectoryIgnoringInodes(const Path & path, const InodeHash & inodeHash)
  55. {
  56. Strings names;
  57. AutoCloseDir dir = opendir(path.c_str());
  58. if (!dir) throw SysError(format("opening directory `%1%'") % path);
  59. struct dirent * dirent;
  60. while (errno = 0, dirent = readdir(dir)) { /* sic */
  61. checkInterrupt();
  62. if (inodeHash.count(dirent->d_ino)) {
  63. printMsg(lvlDebug, format("`%1%' is already linked") % dirent->d_name);
  64. continue;
  65. }
  66. string name = dirent->d_name;
  67. if (name == "." || name == "..") continue;
  68. names.push_back(name);
  69. }
  70. if (errno) throw SysError(format("reading directory `%1%'") % path);
  71. return names;
  72. }
  73. void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHash & inodeHash)
  74. {
  75. checkInterrupt();
  76. struct stat st;
  77. if (lstat(path.c_str(), &st))
  78. throw SysError(format("getting attributes of path `%1%'") % path);
  79. if (S_ISDIR(st.st_mode)) {
  80. Strings names = readDirectoryIgnoringInodes(path, inodeHash);
  81. foreach (Strings::iterator, i, names)
  82. optimisePath_(stats, path + "/" + *i, inodeHash);
  83. return;
  84. }
  85. /* We can hard link regular files (and maybe symlinks), but do that only
  86. for files larger than some threshold. This avoids adding too many
  87. entries to '.links', which would slow down 'removeUnusedLinks' while
  88. saving little space. */
  89. if (!S_ISREG(st.st_mode) || ((size_t) st.st_size) < deduplicationMinSize)
  90. return;
  91. /* Sometimes SNAFUs can cause files in the store to be
  92. modified, in particular when running programs as root under
  93. Guix System (example: $fontconfig/var/cache being modified). Skip
  94. those files. FIXME: check the modification time. */
  95. if (S_ISREG(st.st_mode) && (st.st_mode & S_IWUSR)) {
  96. printMsg(lvlError, format("skipping suspicious writable file `%1%'") % path);
  97. return;
  98. }
  99. /* This can still happen on top-level files. */
  100. if (st.st_nlink > 1 && inodeHash.count(st.st_ino)) {
  101. printMsg(lvlDebug, format("`%1%' is already linked, with %2% other file(s).") % path % (st.st_nlink - 2));
  102. return;
  103. }
  104. /* Hash the file. Note that hashPath() returns the hash over the
  105. NAR serialisation, which includes the execute bit on the file.
  106. Thus, executable and non-executable files with the same
  107. contents *won't* be linked (which is good because otherwise the
  108. permissions would be screwed up).
  109. Also note that if `path' is a symlink, then we're hashing the
  110. contents of the symlink (i.e. the result of readlink()), not
  111. the contents of the target (which may not even exist). */
  112. Hash hash = hashPath(htSHA256, path).first;
  113. printMsg(lvlDebug, format("`%1%' has hash `%2%'") % path % printHash(hash));
  114. /* Check if this is a known hash. */
  115. Path linkPath = linksDir + "/" + printHash32(hash);
  116. retry:
  117. if (!pathExists(linkPath)) {
  118. /* Nope, create a hard link in the links directory. */
  119. if (link(path.c_str(), linkPath.c_str()) == 0) {
  120. inodeHash.insert(st.st_ino);
  121. return;
  122. }
  123. switch (errno) {
  124. case EEXIST:
  125. /* Fall through if another process created ‘linkPath’ before
  126. we did. */
  127. break;
  128. case ENOSPC:
  129. /* On ext4, that probably means the directory index is full. When
  130. that happens, it's fine to ignore it: we just effectively
  131. disable deduplication of this file. */
  132. printMsg(lvlInfo, format("cannot link `%1%' to `%2%': %3%")
  133. % linkPath % path % strerror(ENOSPC));
  134. return;
  135. default:
  136. throw SysError(format("cannot link `%1%' to `%2%'") % linkPath % path);
  137. }
  138. }
  139. /* Yes! We've seen a file with the same contents. Replace the
  140. current file with a hard link to that file. */
  141. struct stat stLink;
  142. if (lstat(linkPath.c_str(), &stLink))
  143. throw SysError(format("getting attributes of path `%1%'") % linkPath);
  144. if (st.st_ino == stLink.st_ino) {
  145. printMsg(lvlDebug, format("`%1%' is already linked to `%2%'") % path % linkPath);
  146. return;
  147. }
  148. if (st.st_size != stLink.st_size) {
  149. printMsg(lvlError, format("removing corrupted link ‘%1%’") % linkPath);
  150. unlink(linkPath.c_str());
  151. goto retry;
  152. }
  153. printMsg(lvlTalkative, format("linking ‘%1%’ to ‘%2%’") % path % linkPath);
  154. /* Make the containing directory writable, but only if it's not
  155. the store itself (we don't want or need to mess with its
  156. permissions). */
  157. bool mustToggle = !isStorePath(path);
  158. if (mustToggle) makeWritable(dirOf(path));
  159. /* When we're done, make the directory read-only again and reset
  160. its timestamp back to 0. */
  161. MakeReadOnly makeReadOnly(mustToggle ? dirOf(path) : "");
  162. Path tempLink = (format("%1%/.tmp-link-%2%-%3%")
  163. % settings.nixStore % getpid() % rand()).str();
  164. if (link(linkPath.c_str(), tempLink.c_str()) == -1) {
  165. if (errno == EMLINK) {
  166. /* Too many links to the same file (>= 32000 on most file
  167. systems). This is likely to happen with empty files.
  168. Just shrug and ignore. */
  169. if (st.st_size)
  170. printMsg(lvlInfo, format("`%1%' has maximum number of links") % linkPath);
  171. return;
  172. }
  173. throw SysError(format("cannot link `%1%' to `%2%'") % tempLink % linkPath);
  174. }
  175. /* Atomically replace the old file with the new hard link. */
  176. if (rename(tempLink.c_str(), path.c_str()) == -1) {
  177. int renameErrno = errno;
  178. if (unlink(tempLink.c_str()) == -1)
  179. printMsg(lvlError, format("unable to unlink `%1%'") % tempLink);
  180. if (renameErrno == EMLINK) {
  181. /* Some filesystems generate too many links on the rename,
  182. rather than on the original link. (Probably it
  183. temporarily increases the st_nlink field before
  184. decreasing it again.) */
  185. if (st.st_size)
  186. printMsg(lvlInfo, format("`%1%' has maximum number of links") % linkPath);
  187. return;
  188. }
  189. throw SysError(format("cannot rename `%1%' to `%2%'") % tempLink % path);
  190. }
  191. stats.filesLinked++;
  192. stats.bytesFreed += st.st_size;
  193. stats.blocksFreed += st.st_blocks;
  194. }
  195. void LocalStore::optimiseStore(OptimiseStats & stats)
  196. {
  197. PathSet paths = queryAllValidPaths();
  198. InodeHash inodeHash = loadInodeHash();
  199. foreach (PathSet::iterator, i, paths) {
  200. addTempRoot(*i);
  201. if (!isValidPath(*i)) continue; /* path was GC'ed, probably */
  202. startNest(nest, lvlChatty, format("hashing files in `%1%'") % *i);
  203. optimisePath_(stats, *i, inodeHash);
  204. }
  205. }
  206. static string showBytes(unsigned long long bytes)
  207. {
  208. return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str();
  209. }
  210. void LocalStore::optimiseStore()
  211. {
  212. OptimiseStats stats;
  213. optimiseStore(stats);
  214. printMsg(lvlError,
  215. format("%1% freed by hard-linking %2% files")
  216. % showBytes(stats.bytesFreed)
  217. % stats.filesLinked);
  218. }
  219. void LocalStore::optimisePath(const Path & path)
  220. {
  221. OptimiseStats stats;
  222. InodeHash inodeHash;
  223. if (settings.autoOptimiseStore) optimisePath_(stats, path, inodeHash);
  224. }
  225. }