substitutes.scm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013-2021, 2023 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2014 Nikita Karetnikov <nikita@karetnikov.org>
  4. ;;; Copyright © 2018 Kyle Meyer <kyle@kyleam.com>
  5. ;;; Copyright © 2020 Christopher Baines <mail@cbaines.net>
  6. ;;;
  7. ;;; This file is part of GNU Guix.
  8. ;;;
  9. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  10. ;;; under the terms of the GNU General Public License as published by
  11. ;;; the Free Software Foundation; either version 3 of the License, or (at
  12. ;;; your option) any later version.
  13. ;;;
  14. ;;; GNU Guix is distributed in the hope that it will be useful, but
  15. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;;; GNU General Public License for more details.
  18. ;;;
  19. ;;; You should have received a copy of the GNU General Public License
  20. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  21. (define-module (guix substitutes)
  22. #:use-module (guix narinfo)
  23. #:use-module (guix store)
  24. #:use-module (guix utils)
  25. #:use-module (guix combinators)
  26. #:use-module (guix config)
  27. #:use-module (guix diagnostics)
  28. #:use-module (guix i18n)
  29. #:use-module (gcrypt hash)
  30. #:use-module (guix base32)
  31. #:use-module (guix cache)
  32. #:use-module ((guix build utils) #:select (mkdir-p dump-port))
  33. #:use-module ((guix build download)
  34. #:select ((open-connection-for-uri
  35. . guix:open-connection-for-uri)
  36. resolve-uri-reference))
  37. #:autoload (gnutls) (error->string error/premature-termination)
  38. #:use-module (guix progress)
  39. #:use-module (ice-9 match)
  40. #:use-module (ice-9 format)
  41. #:use-module (ice-9 binary-ports)
  42. #:use-module (ice-9 vlist)
  43. #:use-module (rnrs bytevectors)
  44. #:use-module (srfi srfi-1)
  45. #:use-module (srfi srfi-11)
  46. #:use-module (srfi srfi-19)
  47. #:use-module (srfi srfi-26)
  48. #:use-module (web uri)
  49. #:use-module (web request)
  50. #:use-module (web response)
  51. #:use-module (guix http-client)
  52. #:export (%narinfo-cache-directory
  53. call-with-connection-error-handling
  54. lookup-narinfos
  55. lookup-narinfos/diverse))
  56. (define %narinfo-ttl
  57. ;; Number of seconds during which cached narinfo lookups are considered
  58. ;; valid for substitute servers that do not advertise a TTL via the
  59. ;; 'Cache-Control' response header.
  60. (* 36 3600))
  61. (define %narinfo-negative-ttl
  62. ;; Likewise, but for negative lookups---i.e., cached lookup failures (404).
  63. (* 10 60))
  64. (define %narinfo-transient-error-ttl
  65. ;; Likewise, but for transient errors such as 504 ("Gateway timeout").
  66. (* 5 60))
  67. (define %narinfo-cache-directory
  68. ;; A local cache of narinfos, to avoid going to the network. Most of the
  69. ;; time, 'guix substitute' is called by guix-daemon as root and stores its
  70. ;; cached data in /var/guix/…. However, when invoked from 'guix challenge'
  71. ;; as a user, it stores its cache in ~/.cache.
  72. (if (zero? (getuid))
  73. (or (and=> (getenv "XDG_CACHE_HOME")
  74. (cut string-append <> "/guix/substitute"))
  75. (string-append %state-directory "/substitute/cache"))
  76. (string-append (cache-directory #:ensure? #f) "/substitute")))
  77. (define %debug?
  78. ;; Enable debug mode by setting the GUIX_SUBSTITUTE_DEBUG environmnent
  79. ;; variable.
  80. (make-parameter
  81. (getenv "GUIX_SUBSTITUTE_DEBUG")))
  82. (define-syntax-rule (debug fmt args ...)
  83. (when (%debug?)
  84. (format #t fmt args ...)))
  85. (define (narinfo-cache-file cache-url path)
  86. "Return the name of the local file that contains an entry for PATH. The
  87. entry is stored in a sub-directory specific to CACHE-URL."
  88. ;; The daemon does not sanitize its input, so PATH could be something like
  89. ;; "/gnu/store/foo". Gracefully handle that.
  90. (match (store-path-hash-part path)
  91. (#f
  92. (leave (G_ "'~a' does not name a store item~%") path))
  93. ((? string? hash-part)
  94. (string-append %narinfo-cache-directory "/"
  95. (bytevector->base32-string (sha256 (string->utf8 cache-url)))
  96. "/" hash-part))))
  97. (define (cache-narinfo! cache-url path narinfo ttl)
  98. "Cache locally NARNIFO for PATH, which originates from CACHE-URL, with the
  99. given TTL (a number of seconds or #f). NARINFO may be #f, in which case it
  100. indicates that PATH is unavailable at CACHE-URL."
  101. (define now
  102. (current-time time-monotonic))
  103. (define (cache-entry cache-uri narinfo)
  104. `(narinfo (version 2)
  105. (cache-uri ,cache-uri)
  106. (date ,(time-second now))
  107. (ttl ,(or ttl
  108. (if narinfo %narinfo-ttl %narinfo-negative-ttl)))
  109. (value ,(and=> narinfo narinfo->string))))
  110. (let ((file (narinfo-cache-file cache-url path)))
  111. (mkdir-p (dirname file))
  112. (with-atomic-file-output file
  113. (lambda (out)
  114. (write (cache-entry cache-url narinfo) out))))
  115. narinfo)
  116. (define %unreachable-hosts
  117. ;; Set of names of unreachable hosts.
  118. (make-hash-table))
  119. (define* (call-with-connection-error-handling uri proc)
  120. "Call PROC, and catch if a connection fails, print a warning and return #f."
  121. (define host
  122. (uri-host uri))
  123. (catch #t
  124. proc
  125. (match-lambda*
  126. (('getaddrinfo-error error)
  127. (unless (hash-ref %unreachable-hosts host)
  128. (hash-set! %unreachable-hosts host #t) ;warn only once
  129. (warning (G_ "~a: host not found: ~a~%")
  130. host (gai-strerror error)))
  131. #f)
  132. (('system-error . args)
  133. (unless (hash-ref %unreachable-hosts host)
  134. (hash-set! %unreachable-hosts host #t)
  135. (warning (G_ "~a: connection failed: ~a~%") host
  136. (strerror
  137. (system-error-errno `(system-error ,@args)))))
  138. #f)
  139. (('gnutls-error error proc . rest)
  140. (if (eq? error error/premature-termination)
  141. (begin
  142. (warning (G_ "~a: TLS connection failed: in ~a: ~a~%") host
  143. proc (error->string error))
  144. #f)
  145. (apply throw 'gnutls-error error proc rest)))
  146. (args
  147. (apply throw args)))))
  148. (define (narinfo-request cache-url path)
  149. "Return an HTTP request for the narinfo of PATH at CACHE-URL."
  150. ;; Ensure BASE has a trailing slash so that REF is correct regardless of
  151. ;; whether the user-provided CACHE-URL has a trailing slash.
  152. (let* ((base (string->uri (if (string-suffix? "/" cache-url)
  153. cache-url
  154. (string-append cache-url "/"))))
  155. (ref (build-relative-ref
  156. #:path (string-append (store-path-hash-part path) ".narinfo")))
  157. (url (resolve-uri-reference ref base))
  158. (headers '((User-Agent . "GNU Guile"))))
  159. (build-request url #:method 'GET #:headers headers)))
  160. (define (narinfo-from-file file url)
  161. "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f
  162. if file doesn't exist, and the narinfo otherwise."
  163. (catch 'system-error
  164. (lambda ()
  165. (call-with-input-file file
  166. (cut read-narinfo <> url)))
  167. (lambda args
  168. (if (= ENOENT (system-error-errno args))
  169. #f
  170. (apply throw args)))))
  171. (define* (fetch-narinfos url paths
  172. #:key
  173. (open-connection guix:open-connection-for-uri)
  174. (make-progress-reporter
  175. (const progress-reporter/silent)))
  176. "Retrieve all the narinfos for PATHS from the cache at URL and return them."
  177. (define progress-reporter
  178. (make-progress-reporter (length paths)
  179. #:url url))
  180. (define hash-part->path
  181. (let ((mapping (fold (lambda (path result)
  182. (vhash-cons (store-path-hash-part path) path
  183. result))
  184. vlist-null
  185. paths)))
  186. (lambda (hash)
  187. (match (vhash-assoc hash mapping)
  188. (#f #f)
  189. ((_ . path) path)))))
  190. (define (read-to-eof port)
  191. "Read from PORT until EOF is reached. The data are discarded."
  192. (dump-port port (%make-void-port "w")))
  193. (define (handle-narinfo-response request response port result)
  194. (let* ((code (response-code response))
  195. (len (response-content-length response))
  196. (cache (response-cache-control response))
  197. (ttl (and cache (assoc-ref cache 'max-age))))
  198. (progress-reporter-report! progress-reporter)
  199. ;; Make sure to read no more than LEN bytes since subsequent bytes may
  200. ;; belong to the next response.
  201. (if (= code 200) ; hit
  202. (let ((narinfo (read-narinfo port url #:size len)))
  203. (if (string=? (dirname (narinfo-path narinfo))
  204. (%store-prefix))
  205. (begin
  206. (cache-narinfo! url (narinfo-path narinfo) narinfo ttl)
  207. (cons narinfo result))
  208. result))
  209. (let* ((path (uri-path (request-uri request)))
  210. (hash-part (basename
  211. (string-drop-right path 8)))) ;drop ".narinfo"
  212. ;; Log the failing queries and indicate if it failed because the
  213. ;; narinfo is being baked.
  214. (let ((baking?
  215. (assoc-ref (response-headers response) 'x-baking)))
  216. (debug "could not fetch ~a~a ~a~a~%"
  217. url path code
  218. (if baking? " (baking)" "")))
  219. (if len
  220. (get-bytevector-n port len)
  221. (read-to-eof port))
  222. (cache-narinfo! url (hash-part->path hash-part) #f
  223. (if (or (= 404 code) (= 202 code))
  224. ttl
  225. %narinfo-transient-error-ttl))
  226. result))))
  227. (define (do-fetch uri)
  228. (case (and=> uri uri-scheme)
  229. ((http https)
  230. ;; Note: Do not check HTTPS server certificates to avoid depending
  231. ;; on the X.509 PKI. We can do it because we authenticate
  232. ;; narinfos, which provides a much stronger guarantee.
  233. (let* ((requests (map (cut narinfo-request url <>) paths))
  234. (result (begin
  235. (start-progress-reporter! progress-reporter)
  236. (call-with-connection-error-handling
  237. uri
  238. (lambda ()
  239. (http-multiple-get uri
  240. handle-narinfo-response '()
  241. requests
  242. #:open-connection open-connection
  243. #:verify-certificate? #f))))))
  244. (stop-progress-reporter! progress-reporter)
  245. result))
  246. ((file #f)
  247. (let* ((base (string-append (uri-path uri) "/"))
  248. (files (map (compose (cut string-append base <> ".narinfo")
  249. store-path-hash-part)
  250. paths)))
  251. (filter-map (cut narinfo-from-file <> url) files)))
  252. (else
  253. (leave (G_ "~s: unsupported server URI scheme~%")
  254. (if uri (uri-scheme uri) url)))))
  255. (do-fetch (string->uri url)))
  256. (define (cached-narinfo cache-url path)
  257. "Check locally if we have valid info about PATH coming from CACHE-URL.
  258. Return two values: a Boolean indicating whether we have valid cached info, and
  259. that info, which may be either #f (when PATH is unavailable) or the narinfo
  260. for PATH."
  261. (define now
  262. (current-time time-monotonic))
  263. (define cache-file
  264. (narinfo-cache-file cache-url path))
  265. (catch 'system-error
  266. (lambda ()
  267. (call-with-input-file cache-file
  268. (lambda (p)
  269. (match (read p)
  270. (('narinfo ('version 2)
  271. ('cache-uri cache-uri)
  272. ('date date) ('ttl ttl) ('value #f))
  273. ;; A cached negative lookup.
  274. (if (obsolete? date now ttl)
  275. (values #f #f)
  276. (values #t #f)))
  277. (('narinfo ('version 2)
  278. ('cache-uri cache-uri)
  279. ('date date) ('ttl ttl) ('value value))
  280. ;; A cached positive lookup
  281. (if (obsolete? date now ttl)
  282. (values #f #f)
  283. (values #t (string->narinfo value cache-uri))))
  284. (('narinfo ('version v) _ ...)
  285. (values #f #f))))))
  286. (lambda _
  287. (values #f #f))))
  288. (define* (lookup-narinfos cache paths
  289. #:key (open-connection guix:open-connection-for-uri)
  290. (make-progress-reporter
  291. (const progress-reporter/silent)))
  292. "Return the narinfos for PATHS, invoking the server at CACHE when no
  293. information is available locally."
  294. (let-values (((cached missing)
  295. (fold2 (lambda (path cached missing)
  296. (let-values (((valid? value)
  297. (cached-narinfo cache path)))
  298. (if valid?
  299. (if value
  300. (values (cons value cached) missing)
  301. (values cached missing))
  302. (values cached (cons path missing)))))
  303. '()
  304. '()
  305. paths)))
  306. (values (if (null? missing)
  307. cached
  308. (let ((missing (fetch-narinfos cache missing
  309. #:open-connection open-connection
  310. #:make-progress-reporter
  311. make-progress-reporter)))
  312. (append cached (or missing '()))))
  313. (length missing))))
  314. (define* (lookup-narinfos/diverse caches paths authorized?
  315. #:key (open-connection
  316. guix:open-connection-for-uri)
  317. (make-progress-reporter
  318. (const progress-reporter/silent)))
  319. "Look up narinfos for PATHS on all of CACHES, a list of URLS, in that order.
  320. That is, when a cache lacks an AUTHORIZED? narinfo, look it up in the next
  321. cache, and so on.
  322. Return a list of narinfos for PATHS or a subset thereof. The returned
  323. narinfos are either AUTHORIZED?, or they claim a hash that matches an
  324. AUTHORIZED? narinfo."
  325. (define (select-hit result)
  326. (lambda (path)
  327. (match (vhash-fold* cons '() path result)
  328. ((one)
  329. one)
  330. ((several ..1)
  331. (let ((authorized (find authorized? (reverse several))))
  332. (and authorized
  333. (find (cut equivalent-narinfo? <> authorized)
  334. several)))))))
  335. (let loop ((caches caches)
  336. (paths paths)
  337. (result vlist-null) ;path->narinfo vhash
  338. (hits '())) ;paths
  339. (match paths
  340. (() ;we're done
  341. ;; Now iterate on all the HITS, and return exactly one match for each
  342. ;; hit: the first narinfo that is authorized, or that has the same hash
  343. ;; as an authorized narinfo, in the order of CACHES.
  344. (filter-map (select-hit result) hits))
  345. (_
  346. (match caches
  347. ((cache rest ...)
  348. (let* ((narinfos (lookup-narinfos cache paths
  349. #:open-connection open-connection
  350. #:make-progress-reporter
  351. make-progress-reporter))
  352. (definite (map narinfo-path (filter authorized? narinfos)))
  353. (missing (lset-difference string=? paths definite))) ;XXX: perf
  354. (loop rest missing
  355. (fold vhash-cons result
  356. (map narinfo-path narinfos) narinfos)
  357. (append definite hits))))
  358. (() ;that's it
  359. (filter-map (select-hit result) hits)))))))
  360. ;;; substitutes.scm ends here