substitute.scm 34 KB

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