deduplication.scm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2017 Caleb Ristvedt <caleb.ristvedt@cune.org>
  3. ;;; Copyright © 2018-2022 Ludovic Courtès <ludo@gnu.org>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; This houses stuff we do to files when they arrive at the store - resetting
  20. ;;; timestamps, deduplicating, etc.
  21. (define-module (guix store deduplication)
  22. #:use-module (gcrypt hash)
  23. #:use-module (guix build utils)
  24. #:use-module (guix build syscalls)
  25. #:use-module (guix base32)
  26. #:use-module (srfi srfi-11)
  27. #:use-module (srfi srfi-34)
  28. #:use-module (srfi srfi-35)
  29. #:use-module (rnrs io ports)
  30. #:use-module (ice-9 match)
  31. #:use-module (guix serialization)
  32. #:export (nar-sha256
  33. deduplicate
  34. dump-file/deduplicate
  35. copy-file/deduplicate))
  36. (define (nar-sha256 file)
  37. "Gives the sha256 hash of a file and the size of the file in nar form."
  38. (let-values (((port get-hash) (open-sha256-port)))
  39. (write-file file port)
  40. (force-output port)
  41. (let ((hash (get-hash))
  42. (size (port-position port)))
  43. (close-port port)
  44. (values hash size))))
  45. (define (tempname-in directory)
  46. "Gives an unused temporary name under DIRECTORY. Not guaranteed to still be
  47. unused by the time you create anything with that name, but a good shot."
  48. (let ((const-part (string-append directory "/.tmp-link-"
  49. (number->string (getpid)))))
  50. (let try ((guess-part
  51. (number->string (random most-positive-fixnum) 16)))
  52. (if (file-exists? (string-append const-part "-" guess-part))
  53. (try (number->string (random most-positive-fixnum) 16))
  54. (string-append const-part "-" guess-part)))))
  55. (define* (get-temp-link target #:optional (link-prefix (dirname target)))
  56. "Like mkstemp!, but instead of creating a new file and giving you the name,
  57. it creates a new hardlink to TARGET and gives you the name. Since
  58. cross-file-system hardlinks don't work, the temp link must be created on the
  59. same file system - where in that file system it is can be controlled by
  60. LINK-PREFIX."
  61. (let try ((tempname (tempname-in link-prefix)))
  62. (catch 'system-error
  63. (lambda ()
  64. (link target tempname)
  65. tempname)
  66. (lambda args
  67. (if (= (system-error-errno args) EEXIST)
  68. (try (tempname-in link-prefix))
  69. (apply throw args))))))
  70. (define (call-with-writable-file file store thunk)
  71. (if (string=? file store)
  72. (thunk) ;don't meddle with the store's permissions
  73. (let ((stat (lstat file)))
  74. (dynamic-wind
  75. (lambda ()
  76. (make-file-writable file))
  77. thunk
  78. (lambda ()
  79. (set-file-time file stat)
  80. (chmod file (stat:mode stat)))))))
  81. (define-syntax-rule (with-writable-file file store exp ...)
  82. "Make FILE writable for the dynamic extent of EXP..., except if FILE is the
  83. store."
  84. (call-with-writable-file file store (lambda () exp ...)))
  85. ;; There are 3 main kinds of errors we can get from hardlinking: "Too many
  86. ;; things link to this" (EMLINK), "this link already exists" (EEXIST), and
  87. ;; "can't fit more stuff in this directory" (ENOSPC).
  88. (define* (replace-with-link target to-replace
  89. #:key (swap-directory (dirname target))
  90. (store (%store-directory)))
  91. "Atomically replace the file TO-REPLACE with a link to TARGET. Use
  92. SWAP-DIRECTORY as the directory to store temporary hard links. Upon ENOSPC
  93. and EMLINK, TO-REPLACE is left unchanged.
  94. Note: TARGET, TO-REPLACE, and SWAP-DIRECTORY must be on the same file system."
  95. (define temp-link
  96. (catch 'system-error
  97. (lambda ()
  98. (get-temp-link target swap-directory))
  99. (lambda args
  100. ;; We get ENOSPC when we can't fit an additional entry in
  101. ;; SWAP-DIRECTORY. If it's EMLINK, then TARGET has reached its
  102. ;; maximum number of links.
  103. (if (memv (system-error-errno args) `(,ENOSPC ,EMLINK))
  104. #f
  105. (apply throw args)))))
  106. ;; If we couldn't create TEMP-LINK, that's OK: just don't do the
  107. ;; replacement, which means TO-REPLACE won't be deduplicated.
  108. (when temp-link
  109. (with-writable-file (dirname to-replace) store
  110. (catch 'system-error
  111. (lambda ()
  112. (rename-file temp-link to-replace))
  113. (lambda args
  114. (delete-file temp-link)
  115. (unless (= EMLINK (system-error-errno args))
  116. (apply throw args)))))))
  117. (define %deduplication-minimum-size
  118. ;; Size below which files are not deduplicated. This avoids adding too many
  119. ;; entries to '.links', which would slow down 'removeUnusedLinks' while
  120. ;; saving little space. Keep in sync with optimize-store.cc.
  121. 8192)
  122. (define* (deduplicate path hash #:key (store (%store-directory)))
  123. "Check if a store item with sha256 hash HASH already exists. If so,
  124. replace PATH with a hardlink to the already-existing one. If not, register
  125. PATH so that future duplicates can hardlink to it. PATH is assumed to be
  126. under STORE."
  127. ;; Lightweight promises.
  128. (define-syntax-rule (delay exp)
  129. (let ((value #f))
  130. (lambda ()
  131. (unless value
  132. (set! value exp))
  133. value)))
  134. (define-syntax-rule (force promise)
  135. (promise))
  136. (define links-directory
  137. (string-append store "/.links"))
  138. (let loop ((path path)
  139. (type (stat:type (lstat path)))
  140. (hash hash))
  141. (if (eq? 'directory type)
  142. ;; Can't hardlink directories, so hardlink their atoms.
  143. (for-each (match-lambda
  144. ((file . properties)
  145. (unless (member file '("." ".."))
  146. (let* ((file (string-append path "/" file))
  147. (st (delay (lstat file)))
  148. (type (match (assoc-ref properties 'type)
  149. ((or 'unknown #f)
  150. (stat:type (force st)))
  151. (type type))))
  152. (when (or (eq? 'directory type)
  153. (and (eq? 'regular type)
  154. (>= (stat:size (force st))
  155. %deduplication-minimum-size)))
  156. (loop file type
  157. (and (not (eq? 'directory type))
  158. (nar-sha256 file))))))))
  159. (scandir* path))
  160. (let ((link-file (string-append links-directory "/"
  161. (bytevector->nix-base32-string hash))))
  162. (if (file-exists? link-file)
  163. (replace-with-link link-file path
  164. #:swap-directory links-directory
  165. #:store store)
  166. (catch 'system-error
  167. (lambda ()
  168. (link path link-file))
  169. (lambda args
  170. (let ((errno (system-error-errno args)))
  171. (cond ((= errno EEXIST)
  172. ;; Someone else put an entry for PATH in
  173. ;; LINKS-DIRECTORY before we could. Let's use it.
  174. (replace-with-link path link-file
  175. #:swap-directory
  176. links-directory
  177. #:store store))
  178. ((= errno ENOENT)
  179. ;; This most likely means that LINKS-DIRECTORY does
  180. ;; not exist. Attempt to create it and try again.
  181. (mkdir-p links-directory)
  182. (loop path type hash))
  183. ((= errno ENOSPC)
  184. ;; There's not enough room in the directory index for
  185. ;; more entries in .links, but that's fine: we can
  186. ;; just stop.
  187. #f)
  188. ((= errno EMLINK)
  189. ;; PATH has reached the maximum number of links, but
  190. ;; that's OK: we just can't deduplicate it more.
  191. #f)
  192. (else (apply throw args)))))))))))
  193. (define (tee input len output)
  194. "Return a port that reads up to LEN bytes from INPUT and writes them to
  195. OUTPUT as it goes."
  196. (define bytes-read 0)
  197. (define (fail)
  198. ;; Reached EOF before we had read LEN bytes from INPUT.
  199. (raise (condition
  200. (&nar-error (port input)
  201. (file (port-filename output))))))
  202. (define (read! bv start count)
  203. ;; Read at most LEN bytes in total.
  204. (let ((count (min count (- len bytes-read))))
  205. (let loop ((ret (get-bytevector-n! input bv start count)))
  206. (cond ((eof-object? ret)
  207. (if (= bytes-read len)
  208. 0 ; EOF
  209. (fail)))
  210. ((and (zero? ret) (> count 0))
  211. ;; Do not return zero since zero means EOF, so try again.
  212. (loop (get-bytevector-n! input bv start count)))
  213. (else
  214. (put-bytevector output bv start ret)
  215. (set! bytes-read (+ bytes-read ret))
  216. ret)))))
  217. (make-custom-binary-input-port "tee input port" read! #f #f #f))
  218. (define* (dump-file/deduplicate file input size type
  219. #:key (store (%store-directory)))
  220. "Write SIZE bytes read from INPUT to FILE. TYPE is a symbol, either
  221. 'regular or 'executable.
  222. This procedure is suitable as a #:dump-file argument to 'restore-file'. When
  223. used that way, it deduplicates files on the fly as they are restored, thereby
  224. removing the need for a deduplication pass that would re-read all the files
  225. down the road."
  226. (define (dump-and-compute-hash)
  227. (call-with-output-file file
  228. (lambda (output)
  229. (let-values (((hash-port get-hash)
  230. (open-hash-port (hash-algorithm sha256))))
  231. (write-file-tree file hash-port
  232. #:file-type+size (lambda (_) (values type size))
  233. #:file-port
  234. (const (tee input size output)))
  235. (close-port hash-port)
  236. (get-hash)))))
  237. (if (>= size %deduplication-minimum-size)
  238. (deduplicate file (dump-and-compute-hash) #:store store)
  239. (call-with-output-file file
  240. (lambda (output)
  241. (if (file-port? input)
  242. (sendfile output input size 0)
  243. (dump-port input output size
  244. #:buffer-size %deduplication-minimum-size))))))
  245. (define* (copy-file/deduplicate source target
  246. #:key (store (%store-directory)))
  247. "Like 'copy-file', but additionally deduplicate TARGET in STORE."
  248. (call-with-input-file source
  249. (lambda (input)
  250. (let ((stat (stat input)))
  251. (dump-file/deduplicate target input (stat:size stat)
  252. (if (zero? (logand (stat:mode stat)
  253. #o100))
  254. 'regular
  255. 'executable)
  256. #:store store)))))