substitute.scm 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013-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 scripts substitute)
  22. #:use-module (guix ui)
  23. #:use-module (guix scripts)
  24. #:use-module (guix narinfo)
  25. #:use-module (guix store)
  26. #:use-module (guix substitutes)
  27. #:use-module (guix utils)
  28. #:use-module (guix config)
  29. #:use-module (guix records)
  30. #:use-module (guix diagnostics)
  31. #:use-module (guix i18n)
  32. #:use-module ((guix serialization) #:select (restore-file dump-file))
  33. #:autoload (guix store deduplication) (dump-file/deduplicate)
  34. #:autoload (guix scripts discover) (read-substitute-urls)
  35. #:use-module (gcrypt hash)
  36. #:use-module (guix base32)
  37. #:use-module (guix cache)
  38. #:use-module (gcrypt pk-crypto)
  39. #:use-module (guix pki)
  40. #:use-module ((guix build utils) #:select (mkdir-p))
  41. #:use-module ((guix build download)
  42. #:select (uri-abbreviation nar-uri-abbreviation
  43. (open-connection-for-uri
  44. . guix:open-connection-for-uri)))
  45. #:autoload (gnutls) (error/invalid-session error/again error/interrupted)
  46. #:use-module (guix progress)
  47. #:use-module ((guix build syscalls)
  48. #:select (set-thread-name))
  49. #:use-module (ice-9 rdelim)
  50. #:use-module (ice-9 match)
  51. #:use-module (ice-9 format)
  52. #:use-module (ice-9 ftw)
  53. #:use-module (rnrs bytevectors)
  54. #:use-module (srfi srfi-1)
  55. #:use-module (srfi srfi-26)
  56. #:use-module (srfi srfi-34)
  57. #:use-module (srfi srfi-71)
  58. #:use-module (web uri)
  59. #:use-module (guix http-client)
  60. #:export (%allow-unauthenticated-substitutes?
  61. %reply-file-descriptor
  62. substitute-urls
  63. guix-substitute))
  64. ;;; Comment:
  65. ;;;
  66. ;;; This is the "binary substituter". It is invoked by the daemon do check
  67. ;;; for the existence of available "substitutes" (pre-built binaries), and to
  68. ;;; actually use them as a substitute to building things locally.
  69. ;;;
  70. ;;; If possible, substitute a binary for the requested store path, using a Nix
  71. ;;; "binary cache". This program implements the Nix "substituter" protocol.
  72. ;;;
  73. ;;; Code:
  74. (define %narinfo-expired-cache-entry-removal-delay
  75. ;; How often we want to remove files corresponding to expired cache entries.
  76. (* 7 24 3600))
  77. (define (warn-about-missing-authentication)
  78. (warning (G_ "authentication and authorization of substitutes \
  79. disabled!~%"))
  80. #t)
  81. (define %allow-unauthenticated-substitutes?
  82. ;; Whether to allow unchecked substitutes. This is useful for testing
  83. ;; purposes, and should be avoided otherwise.
  84. (make-parameter
  85. (and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES")
  86. (cut string-ci=? <> "yes"))))
  87. (define %fetch-timeout
  88. ;; Number of seconds after which networking is considered "slow".
  89. 5)
  90. (define %random-state
  91. (seed->random-state (+ (ash (cdr (gettimeofday)) 32) (getpid))))
  92. (define-syntax-rule (with-timeout duration handler body ...)
  93. "Run BODY; when DURATION seconds have expired, call HANDLER, and run BODY
  94. again."
  95. (begin
  96. (sigaction SIGALRM
  97. (lambda (signum)
  98. (sigaction SIGALRM SIG_DFL)
  99. handler))
  100. (alarm duration)
  101. (call-with-values
  102. (lambda ()
  103. (let try ()
  104. (catch 'system-error
  105. (lambda ()
  106. body ...)
  107. (lambda args
  108. ;; Before Guile v2.0.9-39-gfe51c7b, the SIGALRM triggers EINTR
  109. ;; because of the bug at
  110. ;; <http://lists.gnu.org/archive/html/guile-devel/2013-06/msg00050.html>.
  111. ;; When that happens, try again. Note: SA_RESTART cannot be
  112. ;; used because of <http://bugs.gnu.org/14640>.
  113. (if (= EINTR (system-error-errno args))
  114. (begin
  115. ;; Wait a little to avoid bursts.
  116. (usleep (random 3000000 %random-state))
  117. (try))
  118. (apply throw args))))))
  119. (lambda result
  120. (alarm 0)
  121. (sigaction SIGALRM SIG_DFL)
  122. (apply values result)))))
  123. (define (at-most max-length lst)
  124. "If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise
  125. return its MAX-LENGTH first elements and its tail."
  126. (let loop ((len 0)
  127. (lst lst)
  128. (result '()))
  129. (match lst
  130. (()
  131. (values (reverse result) '()))
  132. ((head . tail)
  133. (if (>= len max-length)
  134. (values (reverse result) lst)
  135. (loop (+ 1 len) tail (cons head result)))))))
  136. (define (narinfo-from-file file url)
  137. "Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f
  138. if file doesn't exist, and the narinfo otherwise."
  139. (catch 'system-error
  140. (lambda ()
  141. (call-with-input-file file
  142. (cut read-narinfo <> url)))
  143. (lambda args
  144. (if (= ENOENT (system-error-errno args))
  145. #f
  146. (apply throw args)))))
  147. (define (lookup-narinfo caches path authorized?)
  148. "Return the narinfo for PATH in CACHES, or #f when no substitute for PATH
  149. was found."
  150. (match (lookup-narinfos/diverse
  151. caches (list path) authorized?
  152. #:open-connection open-connection-for-uri/cached)
  153. ((answer) answer)
  154. (_ #f)))
  155. (define (cached-narinfo-expiration-time file)
  156. "Return the expiration time for FILE, which is a cached narinfo."
  157. (catch 'system-error
  158. (lambda ()
  159. (call-with-input-file file
  160. (lambda (port)
  161. (match (read port)
  162. (('narinfo ('version 2) ('cache-uri uri)
  163. ('date date) ('ttl ttl) ('value #f))
  164. (+ date ttl))
  165. (('narinfo ('version 2) ('cache-uri uri)
  166. ('date date) ('ttl ttl) ('value value))
  167. (+ date ttl))
  168. (x
  169. 0)))))
  170. (lambda args
  171. ;; FILE may have been deleted.
  172. 0)))
  173. (define (narinfo-cache-directories directory)
  174. "Return the list of narinfo cache directories (one per cache URL.)"
  175. (map (cut string-append directory "/" <>)
  176. (scandir %narinfo-cache-directory
  177. (lambda (item)
  178. (and (not (member item '("." "..")))
  179. (file-is-directory?
  180. (string-append %narinfo-cache-directory
  181. "/" item)))))))
  182. (define* (cached-narinfo-files #:optional
  183. (directory %narinfo-cache-directory))
  184. "Return the list of cached narinfo files under DIRECTORY."
  185. (append-map (lambda (directory)
  186. (map (cut string-append directory "/" <>)
  187. (scandir directory
  188. (lambda (file)
  189. (= (string-length file) 32)))))
  190. (narinfo-cache-directories directory)))
  191. (define-syntax with-networking
  192. (syntax-rules ()
  193. "Catch DNS lookup errors and TLS errors and gracefully exit."
  194. ;; Note: no attempt is made to catch other networking errors, because DNS
  195. ;; lookup errors are typically the first one, and because other errors are
  196. ;; a subset of `system-error', which is harder to filter.
  197. ((_ exp ...)
  198. ;; Use a pre-unwind handler so that re-throwing preserves useful
  199. ;; backtraces. 'with-throw-handler' works for Guile 2.2 and 3.0.
  200. (with-throw-handler #t
  201. (lambda () exp ...)
  202. (match-lambda*
  203. (('getaddrinfo-error error)
  204. (leave (G_ "host name lookup error: ~a~%")
  205. (gai-strerror error)))
  206. (('gnutls-error error proc . rest)
  207. (let ((error->string (module-ref (resolve-interface '(gnutls))
  208. 'error->string)))
  209. (leave (G_ "TLS error in procedure '~a': ~a~%")
  210. proc (error->string error))))
  211. (args
  212. (apply throw args)))))))
  213. ;;;
  214. ;;; Help.
  215. ;;;
  216. (define (show-help)
  217. (display (G_ "Usage: guix substitute OPTION [ARGUMENT]...
  218. Internal tool to substitute a pre-built binary to a local build.\n"))
  219. (display (G_ "
  220. --query report on the availability of substitutes for the
  221. store file names passed on the standard input"))
  222. (display (G_ "
  223. --substitute STORE-FILE DESTINATION
  224. download STORE-FILE and store it as a Nar in file
  225. DESTINATION"))
  226. (newline)
  227. (display (G_ "
  228. -h, --help display this help and exit"))
  229. (display (G_ "
  230. -V, --version display version information and exit"))
  231. (newline)
  232. (show-bug-report-information))
  233. ;;;
  234. ;;; Daemon/substituter protocol.
  235. ;;;
  236. (define %prefer-fast-decompression?
  237. ;; Whether to prefer fast decompression over good compression ratios. This
  238. ;; serves in particular to choose between lzip (high compression ratio but
  239. ;; low decompression throughput) and zstd (lower compression ratio but high
  240. ;; decompression throughput).
  241. #f)
  242. (define (call-with-cpu-usage-monitoring proc)
  243. (let ((before (times)))
  244. (proc)
  245. (let ((after (times)))
  246. (if (= (tms:clock after) (tms:clock before))
  247. 0
  248. (/ (- (tms:utime after) (tms:utime before))
  249. (- (tms:clock after) (tms:clock before))
  250. 1.)))))
  251. (define-syntax-rule (with-cpu-usage-monitoring exp ...)
  252. "Evaluate EXP... Return its CPU usage as a fraction between 0 and 1."
  253. (call-with-cpu-usage-monitoring (lambda () exp ...)))
  254. (define (display-narinfo-data port narinfo)
  255. "Write to PORT the contents of NARINFO in the format expected by the
  256. daemon."
  257. (format port "~a\n~a\n~a\n"
  258. (narinfo-path narinfo)
  259. (or (and=> (narinfo-deriver narinfo)
  260. (cute string-append (%store-prefix) "/" <>))
  261. "")
  262. (length (narinfo-references narinfo)))
  263. (for-each (cute format port "~a/~a~%" (%store-prefix) <>)
  264. (narinfo-references narinfo))
  265. (let ((uri compression file-size
  266. (narinfo-best-uri narinfo
  267. #:fast-decompression?
  268. %prefer-fast-decompression?)))
  269. (format port "~a\n~a\n"
  270. (or file-size 0)
  271. (or (narinfo-size narinfo) 0))))
  272. (define* (process-query port command
  273. #:key cache-urls acl)
  274. "Reply on PORT to COMMAND, a query as written by the daemon to this process's
  275. standard input. Use ACL as the access-control list against which to check
  276. authorized substitutes."
  277. (define valid?
  278. (if (%allow-unauthenticated-substitutes?)
  279. (begin
  280. (warn-about-missing-authentication)
  281. (const #t))
  282. (lambda (obj)
  283. (valid-narinfo? obj acl))))
  284. (define* (make-progress-reporter total #:key url)
  285. (define done 0)
  286. (define (report-progress)
  287. (erase-current-line (current-error-port)) ;erase current line
  288. (force-output (current-error-port))
  289. (format (current-error-port)
  290. (G_ "updating substitutes from '~a'... ~5,1f%")
  291. url (* 100. (/ done total)))
  292. (set! done (+ 1 done)))
  293. (progress-reporter
  294. (start report-progress)
  295. (report report-progress)
  296. (stop (lambda ()
  297. (newline (current-error-port))))))
  298. (match (string-tokenize command)
  299. (("have" paths ..1)
  300. ;; Return the subset of PATHS available in CACHE-URLS.
  301. (let ((substitutable (lookup-narinfos/diverse
  302. cache-urls paths valid?
  303. #:open-connection open-connection-for-uri/cached
  304. #:make-progress-reporter make-progress-reporter)))
  305. (for-each (lambda (narinfo)
  306. (format port "~a~%" (narinfo-path narinfo)))
  307. substitutable)
  308. (newline port)))
  309. (("info" paths ..1)
  310. ;; Reply info about PATHS if it's in CACHE-URLS.
  311. (let ((substitutable (lookup-narinfos/diverse
  312. cache-urls paths valid?
  313. #:open-connection open-connection-for-uri/cached
  314. #:make-progress-reporter make-progress-reporter)))
  315. (for-each (cut display-narinfo-data port <>) substitutable)
  316. (newline port)))
  317. (wtf
  318. (error "unknown `--query' command" wtf))))
  319. (define %max-cached-connections
  320. ;; Maximum number of connections kept in cache by
  321. ;; 'open-connection-for-uri/cached'.
  322. 16)
  323. (define open-connection-for-uri/cached
  324. (let ((cache '()))
  325. (lambda* (uri #:key fresh? (timeout %fetch-timeout) verify-certificate?)
  326. "Return a connection for URI, possibly reusing a cached connection.
  327. When FRESH? is true, delete any cached connections for URI and open a new one.
  328. Return #f if URI's scheme is 'file' or #f.
  329. When true, TIMEOUT is the maximum number of seconds to wait for
  330. connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS
  331. server certificates."
  332. (define host (uri-host uri))
  333. (define scheme (uri-scheme uri))
  334. (define key (list host scheme (uri-port uri)))
  335. (and (not (memq scheme '(file #f)))
  336. (match (assoc-ref cache key)
  337. (#f
  338. ;; Open a new connection to URI and evict old entries from
  339. ;; CACHE, if any.
  340. (let ((socket
  341. (guix:open-connection-for-uri
  342. uri
  343. #:verify-certificate? verify-certificate?
  344. #:timeout timeout))
  345. (new-cache evicted
  346. (at-most (- %max-cached-connections 1) cache)))
  347. (for-each (match-lambda
  348. ((_ . port)
  349. (false-if-exception (close-port port))))
  350. evicted)
  351. (set! cache (alist-cons key socket new-cache))
  352. socket))
  353. (socket
  354. (if (or fresh? (port-closed? socket))
  355. (begin
  356. (false-if-exception (close-port socket))
  357. (set! cache (alist-delete key cache))
  358. (open-connection-for-uri/cached uri #:timeout timeout
  359. #:verify-certificate?
  360. verify-certificate?))
  361. (begin
  362. ;; Drain input left from the previous use.
  363. (drain-input socket)
  364. socket))))))))
  365. (define kind-and-args-exception?
  366. (exception-predicate &exception-with-kind-and-args))
  367. (define (call-with-cached-connection uri proc)
  368. (let ((port (open-connection-for-uri/cached uri
  369. #:verify-certificate? #f)))
  370. (guard (c ((kind-and-args-exception? c)
  371. (let ((key (exception-kind c))
  372. (args (exception-args c)))
  373. ;; If PORT was cached and the server closed the connection in the
  374. ;; meantime, we get EPIPE. In that case, open a fresh connection
  375. ;; and retry. We might also get 'bad-response or a similar
  376. ;; exception from (web response) later on, once we've sent the
  377. ;; request, or a ERROR/INVALID-SESSION from GnuTLS.
  378. (if (or (and (eq? key 'system-error)
  379. (= EPIPE (system-error-errno `(,key ,@args))))
  380. (and (eq? key 'gnutls-error)
  381. (memq (first args)
  382. (list error/invalid-session
  383. ;; XXX: These two are not properly handled in
  384. ;; GnuTLS < 3.7.3, in
  385. ;; 'write_to_session_record_port'; see
  386. ;; <https://bugs.gnu.org/47867>.
  387. error/again error/interrupted)))
  388. (memq key '(bad-response bad-header bad-header-component)))
  389. (proc (open-connection-for-uri/cached uri
  390. #:verify-certificate? #f
  391. #:fresh? #t))
  392. (raise c))))
  393. (#t
  394. ;; An exception that's not handled here, such as
  395. ;; '&http-get-error'. Re-raise it.
  396. (raise c)))
  397. (proc port))))
  398. (define-syntax-rule (with-cached-connection uri port exp ...)
  399. "Bind PORT with EXP... to a socket connected to URI."
  400. (call-with-cached-connection uri (lambda (port) exp ...)))
  401. (define* (download-nar narinfo destination
  402. #:key status-port
  403. deduplicate? print-build-trace?)
  404. "Download the nar prescribed in NARINFO, which is assumed to be authentic
  405. and authorized, and write it to DESTINATION. When DEDUPLICATE? is true, and
  406. if DESTINATION is in the store, deduplicate its files. Print a status line to
  407. STATUS-PORT."
  408. (define destination-in-store?
  409. (string-prefix? (string-append (%store-prefix) "/")
  410. destination))
  411. (define (dump-file/deduplicate* . args)
  412. ;; Make sure deduplication looks at the right store (necessary in test
  413. ;; environments).
  414. (apply dump-file/deduplicate
  415. (append args (list #:store (%store-prefix)))))
  416. (define (fetch uri)
  417. (case (uri-scheme uri)
  418. ((file)
  419. (let ((port (open-file (uri-path uri) "r0b")))
  420. (values port (stat:size (stat port)))))
  421. ((http https)
  422. ;; Test this with:
  423. ;; sudo tc qdisc add dev eth0 root netem delay 1500ms
  424. ;; and then cancel with:
  425. ;; sudo tc qdisc del dev eth0 root
  426. (with-timeout %fetch-timeout
  427. (begin
  428. (warning (G_ "while fetching ~a: server is somewhat slow~%")
  429. (uri->string uri))
  430. (warning (G_ "try `--no-substitutes' if the problem persists~%")))
  431. (with-cached-connection uri port
  432. (http-fetch uri #:text? #f
  433. #:port port
  434. #:keep-alive? #t
  435. #:buffered? #f))))
  436. (else
  437. (leave (G_ "unsupported substitute URI scheme: ~a~%")
  438. (uri->string uri)))))
  439. (define (try-fetch choices)
  440. (match choices
  441. (((uri compression file-size) rest ...)
  442. (guard (c ((and (pair? rest) (http-get-error? c))
  443. (warning (G_ "download from '~a' failed, trying next URL~%")
  444. (uri->string uri))
  445. (try-fetch rest)))
  446. (let ((port download-size (fetch uri)))
  447. (unless print-build-trace?
  448. (format (current-error-port)
  449. (G_ "Downloading ~a...~%") (uri->string uri)))
  450. (values port uri compression download-size))))
  451. (()
  452. (leave (G_ "no valid nar URLs for ~a at ~a~%")
  453. (narinfo-path narinfo)
  454. (narinfo-uri-base narinfo)))))
  455. (let ((choices (narinfo-preferred-uris narinfo
  456. #:fast-decompression?
  457. %prefer-fast-decompression?)))
  458. ;; 'guix publish' without '--cache' doesn't specify a Content-Length, so
  459. ;; DOWNLOAD-SIZE is #f in this case.
  460. (let* ((raw uri compression download-size (try-fetch choices))
  461. (progress
  462. (let* ((dl-size (or download-size
  463. (and (equal? compression "none")
  464. (narinfo-size narinfo))))
  465. (reporter (if print-build-trace?
  466. (progress-reporter/trace
  467. destination
  468. (uri->string uri) dl-size
  469. (current-error-port))
  470. (progress-reporter/file
  471. (uri->string uri) dl-size
  472. (current-error-port)
  473. #:abbreviation nar-uri-abbreviation))))
  474. ;; Keep RAW open upon completion so we can later reuse
  475. ;; the underlying connection. Pass the download size so
  476. ;; that this procedure won't block reading from RAW.
  477. (progress-report-port reporter raw
  478. #:close? #f
  479. #:download-size dl-size)))
  480. (input pids
  481. ;; NOTE: This 'progress' port of current process will be
  482. ;; closed here, while the child process doing the
  483. ;; reporting will close it upon exit.
  484. (decompressed-port (string->symbol compression)
  485. progress))
  486. ;; Compute the actual nar hash as we read it.
  487. (algorithm expected (narinfo-hash-algorithm+value narinfo))
  488. (hashed get-hash (open-hash-input-port algorithm input)))
  489. ;; Unpack the Nar at INPUT into DESTINATION.
  490. (define cpu-usage
  491. (with-cpu-usage-monitoring
  492. (restore-file hashed destination
  493. #:dump-file (if (and destination-in-store?
  494. deduplicate?)
  495. dump-file/deduplicate*
  496. dump-file))))
  497. ;; Create a hysteresis: depending on CPU usage, favor compression
  498. ;; methods with faster decompression (like ztsd) or methods with better
  499. ;; compression ratios (like lzip). This stems from the observation that
  500. ;; substitution can be CPU-bound when high-speed networks are used:
  501. ;; <https://lists.gnu.org/archive/html/guix-devel/2020-12/msg00177.html>.
  502. ;; To simulate "slow" networking or changing conditions, run:
  503. ;; sudo tc qdisc add dev eno1 root tbf rate 512kbit latency 50ms burst 1540
  504. ;; and then cancel with:
  505. ;; sudo tc qdisc del dev eno1 root
  506. (when (> cpu-usage .8)
  507. (set! %prefer-fast-decompression? #t))
  508. (when (< cpu-usage .2)
  509. (set! %prefer-fast-decompression? #f))
  510. (close-port hashed)
  511. (close-port input)
  512. ;; Wait for the reporter to finish.
  513. (every (compose zero? cdr waitpid) pids)
  514. ;; Skip a line after what 'progress-reporter/file' printed, and another
  515. ;; one to visually separate substitutions. When PRINT-BUILD-TRACE? is
  516. ;; true, leave it up to (guix status) to prettify things.
  517. (newline (current-error-port))
  518. (unless print-build-trace?
  519. (newline (current-error-port)))
  520. ;; Check whether we got the data announced in NARINFO.
  521. (let ((actual (get-hash)))
  522. (if (bytevector=? actual expected)
  523. ;; Tell the daemon that we're done.
  524. (format status-port "success ~a ~a~%"
  525. (narinfo-hash narinfo) (narinfo-size narinfo))
  526. ;; The actual data has a different hash than that in NARINFO.
  527. (format status-port "hash-mismatch ~a ~a ~a~%"
  528. (hash-algorithm-name algorithm)
  529. (bytevector->nix-base32-string expected)
  530. (bytevector->nix-base32-string actual)))))))
  531. (define (system-error? exception)
  532. "Return true if EXCEPTION is a Guile 'system-error exception."
  533. (and (kind-and-args-exception? exception)
  534. (eq? 'system-error (exception-kind exception))))
  535. (define network-error?
  536. (let ((kind-and-args? (exception-predicate &exception-with-kind-and-args)))
  537. (lambda (exception)
  538. "Return true if EXCEPTION denotes a networking error."
  539. (or (and (system-error? exception)
  540. (let ((errno (system-error-errno
  541. (cons 'system-error (exception-args exception)))))
  542. (memv errno (list ECONNRESET ECONNABORTED ETIMEDOUT
  543. ECONNREFUSED EHOSTUNREACH
  544. ENOENT)))) ;for "file://"
  545. (and (kind-and-args? exception)
  546. (memq (exception-kind exception)
  547. '(gnutls-error getaddrinfo-error)))
  548. (and (http-get-error? exception)
  549. (begin
  550. (warning (G_ "download from '~a' failed: ~a, ~s~%")
  551. (uri->string (http-get-error-uri exception))
  552. (http-get-error-code exception)
  553. (http-get-error-reason exception))
  554. #t))))))
  555. (define* (process-substitution/fallback port narinfo destination
  556. #:key cache-urls acl
  557. deduplicate? print-build-trace?)
  558. "Attempt to substitute NARINFO, which is assumed to be authorized or
  559. equivalent, by trying to download its nar from each entry in CACHE-URLS.
  560. This can be less efficient than 'lookup-narinfo', which stops at the first
  561. entry that provides a valid narinfo, but it makes sure we eventually find a
  562. way to download the nar."
  563. ;; Note: Keep NARINFO's uri-base in CACHE-URLS: that lets us retry in case
  564. ;; this was a transient issue.
  565. (let loop ((cache-urls cache-urls))
  566. (match cache-urls
  567. (()
  568. (leave (G_ "failed to find alternative substitute for '~a'~%")
  569. (narinfo-path narinfo)))
  570. ((cache-url rest ...)
  571. (match (lookup-narinfos cache-url
  572. (list (narinfo-path narinfo))
  573. #:open-connection
  574. open-connection-for-uri/cached)
  575. ((alternate)
  576. (if (or (equivalent-narinfo? narinfo alternate)
  577. (valid-narinfo? alternate acl)
  578. (%allow-unauthenticated-substitutes?))
  579. (guard (c ((network-error? c) (loop rest)))
  580. (download-nar alternate destination
  581. #:status-port port
  582. #:deduplicate? deduplicate?
  583. #:print-build-trace? print-build-trace?))
  584. (loop rest)))
  585. (()
  586. (loop rest)))))))
  587. (define* (process-substitution port store-item destination
  588. #:key cache-urls acl
  589. deduplicate? print-build-trace?)
  590. "Substitute STORE-ITEM (a store file name) from CACHE-URLS, and write it to
  591. DESTINATION as a nar file. Verify the substitute against ACL, and verify its
  592. hash against what appears in the narinfo. When DEDUPLICATE? is true, and if
  593. DESTINATION is in the store, deduplicate its files. Print a status line to
  594. PORT."
  595. (define narinfo
  596. (lookup-narinfo cache-urls store-item
  597. (if (%allow-unauthenticated-substitutes?)
  598. (const #t)
  599. (cut valid-narinfo? <> acl))))
  600. (unless narinfo
  601. (leave (G_ "no valid substitute for '~a'~%")
  602. store-item))
  603. (guard (c ((network-error? c)
  604. (format (current-error-port)
  605. (G_ "retrying download of '~a' with other substitute URLs...~%")
  606. store-item)
  607. (process-substitution/fallback port narinfo destination
  608. #:cache-urls cache-urls
  609. #:acl acl
  610. #:deduplicate? deduplicate?
  611. #:print-build-trace?
  612. print-build-trace?)))
  613. (download-nar narinfo destination
  614. #:status-port port
  615. #:deduplicate? deduplicate?
  616. #:print-build-trace? print-build-trace?)))
  617. ;;;
  618. ;;; Entry point.
  619. ;;;
  620. (define (check-acl-initialized)
  621. "Warn if the ACL is uninitialized."
  622. (define (singleton? acl)
  623. ;; True if ACL contains just the user's public key.
  624. (and (file-exists? %public-key-file)
  625. (let ((key (call-with-input-file %public-key-file
  626. (compose string->canonical-sexp
  627. read-string))))
  628. (match acl
  629. ((thing)
  630. (equal? (canonical-sexp->string thing)
  631. (canonical-sexp->string key)))
  632. (_
  633. #f)))))
  634. (let ((acl (acl->public-keys (current-acl))))
  635. (when (or (null? acl) (singleton? acl))
  636. (warning (G_ "ACL for archive imports seems to be uninitialized, \
  637. substitutes may be unavailable\n")))))
  638. (define (daemon-options)
  639. "Return a list of name/value pairs denoting build daemon options."
  640. (define %not-newline
  641. (char-set-complement (char-set #\newline)))
  642. (match (getenv "_NIX_OPTIONS")
  643. (#f ;should not happen when called by the daemon
  644. '())
  645. (newline-separated
  646. ;; Here we get something of the form "OPTION1=VALUE1\nOPTION2=VALUE2\n".
  647. (filter-map (lambda (option=value)
  648. (match (string-index option=value #\=)
  649. (#f ;invalid option setting
  650. #f)
  651. (equal-sign
  652. (cons (string-take option=value equal-sign)
  653. (string-drop option=value (+ 1 equal-sign))))))
  654. (string-tokenize newline-separated %not-newline)))))
  655. (define find-daemon-option
  656. (let ((options (delay (daemon-options))))
  657. (lambda (option)
  658. "Return the value of build daemon option OPTION, or #f if it could not be
  659. found."
  660. (assoc-ref (force options) option))))
  661. (define %default-substitute-urls
  662. (match (and=> (or (find-daemon-option "untrusted-substitute-urls") ;client
  663. (find-daemon-option "substitute-urls")) ;admin
  664. string-tokenize)
  665. ((urls ...)
  666. urls)
  667. (#f
  668. ;; This can only happen when this script is not invoked by the
  669. ;; daemon.
  670. '("http://ci.guix.gnu.org"
  671. "http://bordeaux.guix.gnu.org"))))
  672. ;; In order to prevent using large number of discovered local substitute
  673. ;; servers, limit the local substitute urls list size.
  674. (define %max-substitute-urls 50)
  675. (define* (randomize-substitute-urls urls
  676. #:key
  677. (max %max-substitute-urls))
  678. "Return a list containing MAX urls from URLS, picked randomly. If URLS list
  679. is shorter than MAX elements, then it is directly returned."
  680. (define (random-item list)
  681. (list-ref list (random (length list))))
  682. (if (<= (length urls) max)
  683. urls
  684. (let loop ((res '())
  685. (urls urls))
  686. (if (eq? (length res) max)
  687. res
  688. (let ((url (random-item urls)))
  689. (loop (cons url res) (delete url urls)))))))
  690. (define %local-substitute-urls
  691. ;; If the following option is passed to the daemon, use the substitutes list
  692. ;; provided by "guix discover" process.
  693. (let* ((option (find-daemon-option "discover"))
  694. (discover? (and option (string=? option "true"))))
  695. (if discover?
  696. (randomize-substitute-urls (read-substitute-urls))
  697. '())))
  698. (define substitute-urls
  699. ;; List of substitute URLs.
  700. (make-parameter (append %local-substitute-urls
  701. %default-substitute-urls)))
  702. (define (client-terminal-columns)
  703. "Return the number of columns in the client's terminal, if it is known, or a
  704. default value."
  705. (or (and=> (or (find-daemon-option "untrusted-terminal-columns")
  706. (find-daemon-option "terminal-columns"))
  707. (lambda (str)
  708. (let ((number (string->number str)))
  709. (and number (max 20 (- number 1))))))
  710. 80))
  711. (define (validate-uri uri)
  712. (unless (string->uri uri)
  713. (leave (G_ "~a: invalid URI~%") uri)))
  714. (define %reply-file-descriptor
  715. ;; The file descriptor where replies to the daemon must be sent, or #f to
  716. ;; use the current output port instead.
  717. (make-parameter 4))
  718. (define-command (guix-substitute . args)
  719. (category internal)
  720. (synopsis "implement the build daemon's substituter protocol")
  721. (match args
  722. ((or ("-V") ("--version"))
  723. (show-version-and-exit "guix substitute"))
  724. ((or ("-h") ("--help") ())
  725. (show-help)
  726. (exit 0))
  727. (_ #t))
  728. (define print-build-trace?
  729. (match (or (find-daemon-option "untrusted-print-extended-build-trace")
  730. (find-daemon-option "print-extended-build-trace"))
  731. (#f #f)
  732. ((= string->number number) (> number 0))
  733. (_ #f)))
  734. (define deduplicate?
  735. (find-daemon-option "deduplicate"))
  736. (define reply-port
  737. ;; Port used to reply to the daemon.
  738. (if (%reply-file-descriptor)
  739. (fdopen (%reply-file-descriptor) "wl")
  740. (current-output-port)))
  741. (mkdir-p %narinfo-cache-directory)
  742. (maybe-remove-expired-cache-entries %narinfo-cache-directory
  743. cached-narinfo-files
  744. #:entry-expiration
  745. cached-narinfo-expiration-time
  746. #:cleanup-period
  747. %narinfo-expired-cache-entry-removal-delay)
  748. (check-acl-initialized)
  749. ;; Sanity-check SUBSTITUTE-URLS so we can provide a meaningful error
  750. ;; message.
  751. (for-each validate-uri (substitute-urls))
  752. ;; Attempt to install the client's locale so that messages are suitably
  753. ;; translated. LC_CTYPE must be a UTF-8 locale; it's the case by default
  754. ;; so don't change it.
  755. (match (or (find-daemon-option "untrusted-locale")
  756. (find-daemon-option "locale"))
  757. (#f #f)
  758. (locale (false-if-exception (setlocale LC_MESSAGES locale))))
  759. (catch 'system-error
  760. (lambda ()
  761. (set-thread-name "guix substitute"))
  762. (const #t)) ;GNU/Hurd lacks 'prctl'
  763. (with-networking
  764. (with-error-handling ; for signature errors
  765. (match args
  766. (("--query")
  767. (let ((acl (current-acl)))
  768. (let loop ((command (read-line)))
  769. (or (eof-object? command)
  770. (begin
  771. (process-query reply-port command
  772. #:cache-urls (substitute-urls)
  773. #:acl acl)
  774. (loop (read-line)))))))
  775. (("--substitute")
  776. ;; Download STORE-PATH and store it as a Nar in file DESTINATION.
  777. ;; Specify the number of columns of the terminal so the progress
  778. ;; report displays nicely.
  779. (parameterize ((current-terminal-columns (client-terminal-columns)))
  780. (let loop ()
  781. (match (read-line)
  782. ((? eof-object?)
  783. #t)
  784. ((= string-tokenize ("substitute" store-path destination))
  785. (process-substitution reply-port store-path destination
  786. #:cache-urls (substitute-urls)
  787. #:acl (current-acl)
  788. #:deduplicate? deduplicate?
  789. #:print-build-trace?
  790. print-build-trace?)
  791. (loop))))))
  792. (opts
  793. (leave (G_ "~a: unrecognized options~%") opts))))))
  794. ;;; Local Variables:
  795. ;;; eval: (put 'with-timeout 'scheme-indent-function 1)
  796. ;;; eval: (put 'with-redirected-error-port 'scheme-indent-function 0)
  797. ;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)
  798. ;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1)
  799. ;;; End:
  800. ;;; substitute.scm ends here