deduplication.scm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2017 Caleb Ristvedt <caleb.ristvedt@cune.org>
  3. ;;; Copyright © 2018, 2019, 2020 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 ftw)
  31. #:use-module (ice-9 match)
  32. #:use-module (guix serialization)
  33. #:export (nar-sha256
  34. deduplicate
  35. dump-file/deduplicate
  36. copy-file/deduplicate))
  37. (define (nar-sha256 file)
  38. "Gives the sha256 hash of a file and the size of the file in nar form."
  39. (let-values (((port get-hash) (open-sha256-port)))
  40. (write-file file port)
  41. (force-output port)
  42. (let ((hash (get-hash))
  43. (size (port-position port)))
  44. (close-port port)
  45. (values hash size))))
  46. (define (tempname-in directory)
  47. "Gives an unused temporary name under DIRECTORY. Not guaranteed to still be
  48. unused by the time you create anything with that name, but a good shot."
  49. (let ((const-part (string-append directory "/.tmp-link-"
  50. (number->string (getpid)))))
  51. (let try ((guess-part
  52. (number->string (random most-positive-fixnum) 16)))
  53. (if (file-exists? (string-append const-part "-" guess-part))
  54. (try (number->string (random most-positive-fixnum) 16))
  55. (string-append const-part "-" guess-part)))))
  56. (define* (get-temp-link target #:optional (link-prefix (dirname target)))
  57. "Like mkstemp!, but instead of creating a new file and giving you the name,
  58. it creates a new hardlink to TARGET and gives you the name. Since
  59. cross-file-system hardlinks don't work, the temp link must be created on the
  60. same file system - where in that file system it is can be controlled by
  61. LINK-PREFIX."
  62. (let try ((tempname (tempname-in link-prefix)))
  63. (catch 'system-error
  64. (lambda ()
  65. (link target tempname)
  66. tempname)
  67. (lambda args
  68. (if (= (system-error-errno args) EEXIST)
  69. (try (tempname-in link-prefix))
  70. (apply throw args))))))
  71. (define (call-with-writable-file file store thunk)
  72. (if (string=? file store)
  73. (thunk) ;don't meddle with the store's permissions
  74. (let ((stat (lstat file)))
  75. (dynamic-wind
  76. (lambda ()
  77. (make-file-writable file))
  78. thunk
  79. (lambda ()
  80. (set-file-time file stat)
  81. (chmod file (stat:mode stat)))))))
  82. (define-syntax-rule (with-writable-file file store exp ...)
  83. "Make FILE writable for the dynamic extent of EXP..., except if FILE is the
  84. store."
  85. (call-with-writable-file file store (lambda () exp ...)))
  86. ;; There are 3 main kinds of errors we can get from hardlinking: "Too many
  87. ;; things link to this" (EMLINK), "this link already exists" (EEXIST), and
  88. ;; "can't fit more stuff in this directory" (ENOSPC).
  89. (define* (replace-with-link target to-replace
  90. #:key (swap-directory (dirname target))
  91. (store (%store-directory)))
  92. "Atomically replace the file TO-REPLACE with a link to TARGET. Use
  93. SWAP-DIRECTORY as the directory to store temporary hard links. Upon ENOSPC
  94. and EMLINK, TO-REPLACE is left unchanged.
  95. Note: TARGET, TO-REPLACE, and SWAP-DIRECTORY must be on the same file system."
  96. (define temp-link
  97. (catch 'system-error
  98. (lambda ()
  99. (get-temp-link target swap-directory))
  100. (lambda args
  101. ;; We get ENOSPC when we can't fit an additional entry in
  102. ;; SWAP-DIRECTORY. If it's EMLINK, then TARGET has reached its
  103. ;; maximum number of links.
  104. (if (memv (system-error-errno args) `(,ENOSPC ,EMLINK))
  105. #f
  106. (apply throw args)))))
  107. ;; If we couldn't create TEMP-LINK, that's OK: just don't do the
  108. ;; replacement, which means TO-REPLACE won't be deduplicated.
  109. (when temp-link
  110. (with-writable-file (dirname to-replace) store
  111. (catch 'system-error
  112. (lambda ()
  113. (rename-file temp-link to-replace))
  114. (lambda args
  115. (delete-file temp-link)
  116. (unless (= EMLINK (system-error-errno args))
  117. (apply throw args)))))))
  118. (define* (deduplicate path hash #:key (store (%store-directory)))
  119. "Check if a store item with sha256 hash HASH already exists. If so,
  120. replace PATH with a hardlink to the already-existing one. If not, register
  121. PATH so that future duplicates can hardlink to it. PATH is assumed to be
  122. under STORE."
  123. (define links-directory
  124. (string-append store "/.links"))
  125. (let loop ((path path)
  126. (type (stat:type (lstat path)))
  127. (hash hash))
  128. (if (eq? 'directory type)
  129. ;; Can't hardlink directories, so hardlink their atoms.
  130. (for-each (match-lambda
  131. ((file . properties)
  132. (unless (member file '("." ".."))
  133. (let* ((file (string-append path "/" file))
  134. (type (match (assoc-ref properties 'type)
  135. ((or 'unknown #f)
  136. (stat:type (lstat file)))
  137. (type type))))
  138. (loop file type
  139. (and (not (eq? 'directory type))
  140. (nar-sha256 file)))))))
  141. (scandir* path))
  142. (let ((link-file (string-append links-directory "/"
  143. (bytevector->nix-base32-string hash))))
  144. (if (file-exists? link-file)
  145. (replace-with-link link-file path
  146. #:swap-directory links-directory
  147. #:store store)
  148. (catch 'system-error
  149. (lambda ()
  150. (link path link-file))
  151. (lambda args
  152. (let ((errno (system-error-errno args)))
  153. (cond ((= errno EEXIST)
  154. ;; Someone else put an entry for PATH in
  155. ;; LINKS-DIRECTORY before we could. Let's use it.
  156. (replace-with-link path link-file
  157. #:swap-directory
  158. links-directory
  159. #:store store))
  160. ((= errno ENOENT)
  161. ;; This most likely means that LINKS-DIRECTORY does
  162. ;; not exist. Attempt to create it and try again.
  163. (mkdir-p links-directory)
  164. (loop path type hash))
  165. ((= errno ENOSPC)
  166. ;; There's not enough room in the directory index for
  167. ;; more entries in .links, but that's fine: we can
  168. ;; just stop.
  169. #f)
  170. ((= errno EMLINK)
  171. ;; PATH has reached the maximum number of links, but
  172. ;; that's OK: we just can't deduplicate it more.
  173. #f)
  174. (else (apply throw args)))))))))))
  175. (define (tee input len output)
  176. "Return a port that reads up to LEN bytes from INPUT and writes them to
  177. OUTPUT as it goes."
  178. (define bytes-read 0)
  179. (define (fail)
  180. ;; Reached EOF before we had read LEN bytes from INPUT.
  181. (raise (condition
  182. (&nar-error (port input)
  183. (file (port-filename output))))))
  184. (define (read! bv start count)
  185. ;; Read at most LEN bytes in total.
  186. (let ((count (min count (- len bytes-read))))
  187. (let loop ((ret (get-bytevector-n! input bv start count)))
  188. (cond ((eof-object? ret)
  189. (if (= bytes-read len)
  190. 0 ; EOF
  191. (fail)))
  192. ((and (zero? ret) (> count 0))
  193. ;; Do not return zero since zero means EOF, so try again.
  194. (loop (get-bytevector-n! input bv start count)))
  195. (else
  196. (put-bytevector output bv start ret)
  197. (set! bytes-read (+ bytes-read ret))
  198. ret)))))
  199. (make-custom-binary-input-port "tee input port" read! #f #f #f))
  200. (define* (dump-file/deduplicate file input size type
  201. #:key (store (%store-directory)))
  202. "Write SIZE bytes read from INPUT to FILE. TYPE is a symbol, either
  203. 'regular or 'executable.
  204. This procedure is suitable as a #:dump-file argument to 'restore-file'. When
  205. used that way, it deduplicates files on the fly as they are restored, thereby
  206. removing the need to a deduplication pass that would re-read all the files
  207. down the road."
  208. (define hash
  209. (call-with-output-file file
  210. (lambda (output)
  211. (let-values (((hash-port get-hash)
  212. (open-hash-port (hash-algorithm sha256))))
  213. (write-file-tree file hash-port
  214. #:file-type+size (lambda (_) (values type size))
  215. #:file-port
  216. (const (tee input size output)))
  217. (close-port hash-port)
  218. (get-hash)))))
  219. (deduplicate file hash #:store store))
  220. (define* (copy-file/deduplicate source target
  221. #:key (store (%store-directory)))
  222. "Like 'copy-file', but additionally deduplicate TARGET in STORE."
  223. (call-with-input-file source
  224. (lambda (input)
  225. (let ((stat (stat input)))
  226. (dump-file/deduplicate target input (stat:size stat)
  227. (if (zero? (logand (stat:mode stat)
  228. #o100))
  229. 'regular
  230. 'executable)
  231. #:store store)))))