substitute.scm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 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)
  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-11)
  58. #:use-module (srfi srfi-19)
  59. #:use-module (srfi srfi-26)
  60. #:use-module (srfi srfi-34)
  61. #:use-module (srfi srfi-35)
  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 caches (list path) authorized?)
  155. ((answer) answer)
  156. (_ #f)))
  157. (define (cached-narinfo-expiration-time file)
  158. "Return the expiration time for FILE, which is a cached narinfo."
  159. (catch 'system-error
  160. (lambda ()
  161. (call-with-input-file file
  162. (lambda (port)
  163. (match (read port)
  164. (('narinfo ('version 2) ('cache-uri uri)
  165. ('date date) ('ttl ttl) ('value #f))
  166. (+ date ttl))
  167. (('narinfo ('version 2) ('cache-uri uri)
  168. ('date date) ('ttl ttl) ('value value))
  169. (+ date ttl))
  170. (x
  171. 0)))))
  172. (lambda args
  173. ;; FILE may have been deleted.
  174. 0)))
  175. (define (narinfo-cache-directories directory)
  176. "Return the list of narinfo cache directories (one per cache URL.)"
  177. (map (cut string-append directory "/" <>)
  178. (scandir %narinfo-cache-directory
  179. (lambda (item)
  180. (and (not (member item '("." "..")))
  181. (file-is-directory?
  182. (string-append %narinfo-cache-directory
  183. "/" item)))))))
  184. (define* (cached-narinfo-files #:optional
  185. (directory %narinfo-cache-directory))
  186. "Return the list of cached narinfo files under DIRECTORY."
  187. (append-map (lambda (directory)
  188. (map (cut string-append directory "/" <>)
  189. (scandir directory
  190. (lambda (file)
  191. (= (string-length file) 32)))))
  192. (narinfo-cache-directories directory)))
  193. (define-syntax with-networking
  194. (syntax-rules ()
  195. "Catch DNS lookup errors and TLS errors and gracefully exit."
  196. ;; Note: no attempt is made to catch other networking errors, because DNS
  197. ;; lookup errors are typically the first one, and because other errors are
  198. ;; a subset of `system-error', which is harder to filter.
  199. ((_ exp ...)
  200. ;; Use a pre-unwind handler so that re-throwing preserves useful
  201. ;; backtraces. 'with-throw-handler' works for Guile 2.2 and 3.0.
  202. (with-throw-handler #t
  203. (lambda () exp ...)
  204. (match-lambda*
  205. (('getaddrinfo-error error)
  206. (leave (G_ "host name lookup error: ~a~%")
  207. (gai-strerror error)))
  208. (('gnutls-error error proc . rest)
  209. (let ((error->string (module-ref (resolve-interface '(gnutls))
  210. 'error->string)))
  211. (leave (G_ "TLS error in procedure '~a': ~a~%")
  212. proc (error->string error))))
  213. (args
  214. (apply throw args)))))))
  215. ;;;
  216. ;;; Help.
  217. ;;;
  218. (define (show-help)
  219. (display (G_ "Usage: guix substitute [OPTION]...
  220. Internal tool to substitute a pre-built binary to a local build.\n"))
  221. (display (G_ "
  222. --query report on the availability of substitutes for the
  223. store file names passed on the standard input"))
  224. (display (G_ "
  225. --substitute STORE-FILE DESTINATION
  226. download STORE-FILE and store it as a Nar in file
  227. DESTINATION"))
  228. (newline)
  229. (display (G_ "
  230. -h, --help display this help and exit"))
  231. (display (G_ "
  232. -V, --version display version information and exit"))
  233. (newline)
  234. (show-bug-report-information))
  235. ;;;
  236. ;;; Daemon/substituter protocol.
  237. ;;;
  238. (define %prefer-fast-decompression?
  239. ;; Whether to prefer fast decompression over good compression ratios. This
  240. ;; serves in particular to choose between lzip (high compression ratio but
  241. ;; low decompression throughput) and zstd (lower compression ratio but high
  242. ;; decompression throughput).
  243. #f)
  244. (define (call-with-cpu-usage-monitoring proc)
  245. (let ((before (times)))
  246. (proc)
  247. (let ((after (times)))
  248. (if (= (tms:clock after) (tms:clock before))
  249. 0
  250. (/ (- (tms:utime after) (tms:utime before))
  251. (- (tms:clock after) (tms:clock before))
  252. 1.)))))
  253. (define-syntax-rule (with-cpu-usage-monitoring exp ...)
  254. "Evaluate EXP... Return its CPU usage as a fraction between 0 and 1."
  255. (call-with-cpu-usage-monitoring (lambda () exp ...)))
  256. (define (display-narinfo-data port narinfo)
  257. "Write to PORT the contents of NARINFO in the format expected by the
  258. daemon."
  259. (format port "~a\n~a\n~a\n"
  260. (narinfo-path narinfo)
  261. (or (and=> (narinfo-deriver narinfo)
  262. (cute string-append (%store-prefix) "/" <>))
  263. "")
  264. (length (narinfo-references narinfo)))
  265. (for-each (cute format port "~a/~a~%" (%store-prefix) <>)
  266. (narinfo-references narinfo))
  267. (let-values (((uri compression file-size)
  268. (narinfo-best-uri narinfo
  269. #:fast-decompression?
  270. %prefer-fast-decompression?)))
  271. (format port "~a\n~a\n"
  272. (or file-size 0)
  273. (or (narinfo-size narinfo) 0))))
  274. (define* (process-query port command
  275. #:key cache-urls acl)
  276. "Reply on PORT to COMMAND, a query as written by the daemon to this process's
  277. standard input. Use ACL as the access-control list against which to check
  278. authorized substitutes."
  279. (define valid?
  280. (if (%allow-unauthenticated-substitutes?)
  281. (begin
  282. (warn-about-missing-authentication)
  283. (const #t))
  284. (lambda (obj)
  285. (valid-narinfo? obj acl))))
  286. (define* (make-progress-reporter total #:key url)
  287. (define done 0)
  288. (define (report-progress)
  289. (erase-current-line (current-error-port)) ;erase current line
  290. (force-output (current-error-port))
  291. (format (current-error-port)
  292. (G_ "updating substitutes from '~a'... ~5,1f%")
  293. url (* 100. (/ done total)))
  294. (set! done (+ 1 done)))
  295. (progress-reporter
  296. (start report-progress)
  297. (report report-progress)
  298. (stop (lambda ()
  299. (newline (current-error-port))))))
  300. (match (string-tokenize command)
  301. (("have" paths ..1)
  302. ;; Return the subset of PATHS available in CACHE-URLS.
  303. (let ((substitutable (lookup-narinfos/diverse
  304. cache-urls paths valid?
  305. #:open-connection open-connection-for-uri/cached
  306. #:make-progress-reporter make-progress-reporter)))
  307. (for-each (lambda (narinfo)
  308. (format port "~a~%" (narinfo-path narinfo)))
  309. substitutable)
  310. (newline port)))
  311. (("info" paths ..1)
  312. ;; Reply info about PATHS if it's in CACHE-URLS.
  313. (let ((substitutable (lookup-narinfos/diverse
  314. cache-urls paths valid?
  315. #:open-connection open-connection-for-uri/cached
  316. #:make-progress-reporter make-progress-reporter)))
  317. (for-each (cut display-narinfo-data port <>) substitutable)
  318. (newline port)))
  319. (wtf
  320. (error "unknown `--query' command" wtf))))
  321. (define %max-cached-connections
  322. ;; Maximum number of connections kept in cache by
  323. ;; 'open-connection-for-uri/cached'.
  324. 16)
  325. (define open-connection-for-uri/cached
  326. (let ((cache '()))
  327. (lambda* (uri #:key fresh? (timeout %fetch-timeout) verify-certificate?)
  328. "Return a connection for URI, possibly reusing a cached connection.
  329. When FRESH? is true, delete any cached connections for URI and open a new one.
  330. Return #f if URI's scheme is 'file' or #f.
  331. When true, TIMEOUT is the maximum number of milliseconds to wait for
  332. connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS
  333. server certificates."
  334. (define host (uri-host uri))
  335. (define scheme (uri-scheme uri))
  336. (define key (list host scheme (uri-port uri)))
  337. (and (not (memq scheme '(file #f)))
  338. (match (assoc-ref cache key)
  339. (#f
  340. ;; Open a new connection to URI and evict old entries from
  341. ;; CACHE, if any.
  342. (let-values (((socket)
  343. (guix:open-connection-for-uri
  344. uri
  345. #:verify-certificate? verify-certificate?
  346. #:timeout timeout))
  347. ((new-cache evicted)
  348. (at-most (- %max-cached-connections 1) cache)))
  349. (for-each (match-lambda
  350. ((_ . port)
  351. (false-if-exception (close-port port))))
  352. evicted)
  353. (set! cache (alist-cons key socket new-cache))
  354. socket))
  355. (socket
  356. (if (or fresh? (port-closed? socket))
  357. (begin
  358. (false-if-exception (close-port socket))
  359. (set! cache (alist-delete key cache))
  360. (open-connection-for-uri/cached uri #:timeout timeout
  361. #:verify-certificate?
  362. verify-certificate?))
  363. (begin
  364. ;; Drain input left from the previous use.
  365. (drain-input socket)
  366. socket))))))))
  367. (define (call-with-cached-connection uri proc)
  368. (let ((port (open-connection-for-uri/cached uri
  369. #:verify-certificate? #f)))
  370. (catch #t
  371. (lambda ()
  372. (proc port))
  373. (lambda (key . args)
  374. ;; If PORT was cached and the server closed the connection in the
  375. ;; meantime, we get EPIPE. In that case, open a fresh connection
  376. ;; and retry. We might also get 'bad-response or a similar
  377. ;; exception from (web response) later on, once we've sent the
  378. ;; request, or a ERROR/INVALID-SESSION from GnuTLS.
  379. (if (or (and (eq? key 'system-error)
  380. (= EPIPE (system-error-errno `(,key ,@args))))
  381. (and (eq? key 'gnutls-error)
  382. (eq? (first args) error/invalid-session))
  383. (memq key '(bad-response bad-header bad-header-component)))
  384. (proc (open-connection-for-uri/cached uri
  385. #:verify-certificate? #f
  386. #:fresh? #t))
  387. (apply throw key args))))))
  388. (define-syntax-rule (with-cached-connection uri port exp ...)
  389. "Bind PORT with EXP... to a socket connected to URI."
  390. (call-with-cached-connection uri (lambda (port) exp ...)))
  391. (define* (process-substitution port store-item destination
  392. #:key cache-urls acl
  393. deduplicate? print-build-trace?)
  394. "Substitute STORE-ITEM (a store file name) from CACHE-URLS, and write it to
  395. DESTINATION as a nar file. Verify the substitute against ACL, and verify its
  396. hash against what appears in the narinfo. When DEDUPLICATE? is true, and if
  397. DESTINATION is in the store, deduplicate its files. Print a status line to
  398. PORT."
  399. (define narinfo
  400. (lookup-narinfo cache-urls store-item
  401. (if (%allow-unauthenticated-substitutes?)
  402. (const #t)
  403. (cut valid-narinfo? <> acl))))
  404. (define destination-in-store?
  405. (string-prefix? (string-append (%store-prefix) "/")
  406. destination))
  407. (define (dump-file/deduplicate* . args)
  408. ;; Make sure deduplication looks at the right store (necessary in test
  409. ;; environments).
  410. (apply dump-file/deduplicate
  411. (append args (list #:store (%store-prefix)))))
  412. (define (fetch uri)
  413. (case (uri-scheme uri)
  414. ((file)
  415. (let ((port (open-file (uri-path uri) "r0b")))
  416. (values port (stat:size (stat port)))))
  417. ((http https)
  418. (guard (c ((http-get-error? c)
  419. (leave (G_ "download from '~a' failed: ~a, ~s~%")
  420. (uri->string (http-get-error-uri c))
  421. (http-get-error-code c)
  422. (http-get-error-reason c))))
  423. ;; Test this with:
  424. ;; sudo tc qdisc add dev eth0 root netem delay 1500ms
  425. ;; and then cancel with:
  426. ;; sudo tc qdisc del dev eth0 root
  427. (with-timeout %fetch-timeout
  428. (begin
  429. (warning (G_ "while fetching ~a: server is somewhat slow~%")
  430. (uri->string uri))
  431. (warning (G_ "try `--no-substitutes' if the problem persists~%")))
  432. (with-cached-connection uri port
  433. (http-fetch uri #:text? #f
  434. #:port port
  435. #:keep-alive? #t
  436. #:buffered? #f)))))
  437. (else
  438. (leave (G_ "unsupported substitute URI scheme: ~a~%")
  439. (uri->string uri)))))
  440. (unless narinfo
  441. (leave (G_ "no valid substitute for '~a'~%")
  442. store-item))
  443. (let-values (((uri compression file-size)
  444. (narinfo-best-uri narinfo
  445. #:fast-decompression?
  446. %prefer-fast-decompression?)))
  447. (unless print-build-trace?
  448. (format (current-error-port)
  449. (G_ "Downloading ~a...~%") (uri->string uri)))
  450. (let*-values (((raw download-size)
  451. ;; 'guix publish' without '--cache' doesn't specify a
  452. ;; Content-Length, so DOWNLOAD-SIZE is #f in this case.
  453. (fetch uri))
  454. ((progress)
  455. (let* ((dl-size (or download-size
  456. (and (equal? compression "none")
  457. (narinfo-size narinfo))))
  458. (reporter (if print-build-trace?
  459. (progress-reporter/trace
  460. destination
  461. (uri->string uri) dl-size
  462. (current-error-port))
  463. (progress-reporter/file
  464. (uri->string uri) dl-size
  465. (current-error-port)
  466. #:abbreviation nar-uri-abbreviation))))
  467. ;; Keep RAW open upon completion so we can later reuse
  468. ;; the underlying connection.
  469. (progress-report-port reporter raw #:close? #f)))
  470. ((input pids)
  471. ;; NOTE: This 'progress' port of current process will be
  472. ;; closed here, while the child process doing the
  473. ;; reporting will close it upon exit.
  474. (decompressed-port (string->symbol compression)
  475. progress))
  476. ;; Compute the actual nar hash as we read it.
  477. ((algorithm expected)
  478. (narinfo-hash-algorithm+value narinfo))
  479. ((hashed get-hash)
  480. (open-hash-input-port algorithm input)))
  481. ;; Unpack the Nar at INPUT into DESTINATION.
  482. (define cpu-usage
  483. (with-cpu-usage-monitoring
  484. (restore-file hashed destination
  485. #:dump-file (if (and destination-in-store?
  486. deduplicate?)
  487. dump-file/deduplicate*
  488. dump-file))))
  489. ;; Create a hysteresis: depending on CPU usage, favor compression
  490. ;; methods with faster decompression (like ztsd) or methods with better
  491. ;; compression ratios (like lzip). This stems from the observation that
  492. ;; substitution can be CPU-bound when high-speed networks are used:
  493. ;; <https://lists.gnu.org/archive/html/guix-devel/2020-12/msg00177.html>.
  494. ;; To simulate "slow" networking or changing conditions, run:
  495. ;; sudo tc qdisc add dev eno1 root tbf rate 512kbit latency 50ms burst 1540
  496. ;; and then cancel with:
  497. ;; sudo tc qdisc del dev eno1 root
  498. (when (> cpu-usage .8)
  499. (set! %prefer-fast-decompression? #t))
  500. (when (< cpu-usage .2)
  501. (set! %prefer-fast-decompression? #f))
  502. (close-port hashed)
  503. (close-port input)
  504. ;; Wait for the reporter to finish.
  505. (every (compose zero? cdr waitpid) pids)
  506. ;; Skip a line after what 'progress-reporter/file' printed, and another
  507. ;; one to visually separate substitutions. When PRINT-BUILD-TRACE? is
  508. ;; true, leave it up to (guix status) to prettify things.
  509. (newline (current-error-port))
  510. (unless print-build-trace?
  511. (newline (current-error-port)))
  512. ;; Check whether we got the data announced in NARINFO.
  513. (let ((actual (get-hash)))
  514. (if (bytevector=? actual expected)
  515. ;; Tell the daemon that we're done.
  516. (format port "success ~a ~a~%"
  517. (narinfo-hash narinfo) (narinfo-size narinfo))
  518. ;; The actual data has a different hash than that in NARINFO.
  519. (format port "hash-mismatch ~a ~a ~a~%"
  520. (hash-algorithm-name algorithm)
  521. (bytevector->nix-base32-string expected)
  522. (bytevector->nix-base32-string actual)))))))
  523. ;;;
  524. ;;; Entry point.
  525. ;;;
  526. (define (check-acl-initialized)
  527. "Warn if the ACL is uninitialized."
  528. (define (singleton? acl)
  529. ;; True if ACL contains just the user's public key.
  530. (and (file-exists? %public-key-file)
  531. (let ((key (call-with-input-file %public-key-file
  532. (compose string->canonical-sexp
  533. read-string))))
  534. (match acl
  535. ((thing)
  536. (equal? (canonical-sexp->string thing)
  537. (canonical-sexp->string key)))
  538. (_
  539. #f)))))
  540. (let ((acl (acl->public-keys (current-acl))))
  541. (when (or (null? acl) (singleton? acl))
  542. (warning (G_ "ACL for archive imports seems to be uninitialized, \
  543. substitutes may be unavailable\n")))))
  544. (define (daemon-options)
  545. "Return a list of name/value pairs denoting build daemon options."
  546. (define %not-newline
  547. (char-set-complement (char-set #\newline)))
  548. (match (getenv "_NIX_OPTIONS")
  549. (#f ;should not happen when called by the daemon
  550. '())
  551. (newline-separated
  552. ;; Here we get something of the form "OPTION1=VALUE1\nOPTION2=VALUE2\n".
  553. (filter-map (lambda (option=value)
  554. (match (string-index option=value #\=)
  555. (#f ;invalid option setting
  556. #f)
  557. (equal-sign
  558. (cons (string-take option=value equal-sign)
  559. (string-drop option=value (+ 1 equal-sign))))))
  560. (string-tokenize newline-separated %not-newline)))))
  561. (define (find-daemon-option option)
  562. "Return the value of build daemon option OPTION, or #f if it could not be
  563. found."
  564. (assoc-ref (daemon-options) option))
  565. (define %default-substitute-urls
  566. (match (and=> (or (find-daemon-option "untrusted-substitute-urls") ;client
  567. (find-daemon-option "substitute-urls")) ;admin
  568. string-tokenize)
  569. ((urls ...)
  570. urls)
  571. (#f
  572. ;; This can only happen when this script is not invoked by the
  573. ;; daemon.
  574. '("http://ci.guix.gnu.org"))))
  575. ;; In order to prevent using large number of discovered local substitute
  576. ;; servers, limit the local substitute urls list size.
  577. (define %max-substitute-urls 50)
  578. (define* (randomize-substitute-urls urls
  579. #:key
  580. (max %max-substitute-urls))
  581. "Return a list containing MAX urls from URLS, picked randomly. If URLS list
  582. is shorter than MAX elements, then it is directly returned."
  583. (define (random-item list)
  584. (list-ref list (random (length list))))
  585. (if (<= (length urls) max)
  586. urls
  587. (let loop ((res '())
  588. (urls urls))
  589. (if (eq? (length res) max)
  590. res
  591. (let ((url (random-item urls)))
  592. (loop (cons url res) (delete url urls)))))))
  593. (define %local-substitute-urls
  594. ;; If the following option is passed to the daemon, use the substitutes list
  595. ;; provided by "guix discover" process.
  596. (let* ((option (find-daemon-option "discover"))
  597. (discover? (and option (string=? option "true"))))
  598. (if discover?
  599. (randomize-substitute-urls (read-substitute-urls))
  600. '())))
  601. (define substitute-urls
  602. ;; List of substitute URLs.
  603. (make-parameter (append %local-substitute-urls
  604. %default-substitute-urls)))
  605. (define (client-terminal-columns)
  606. "Return the number of columns in the client's terminal, if it is known, or a
  607. default value."
  608. (or (and=> (or (find-daemon-option "untrusted-terminal-columns")
  609. (find-daemon-option "terminal-columns"))
  610. (lambda (str)
  611. (let ((number (string->number str)))
  612. (and number (max 20 (- number 1))))))
  613. 80))
  614. (define (validate-uri uri)
  615. (unless (string->uri uri)
  616. (leave (G_ "~a: invalid URI~%") uri)))
  617. (define %reply-file-descriptor
  618. ;; The file descriptor where replies to the daemon must be sent, or #f to
  619. ;; use the current output port instead.
  620. (make-parameter 4))
  621. (define-command (guix-substitute . args)
  622. (category internal)
  623. (synopsis "implement the build daemon's substituter protocol")
  624. (define print-build-trace?
  625. (match (or (find-daemon-option "untrusted-print-extended-build-trace")
  626. (find-daemon-option "print-extended-build-trace"))
  627. (#f #f)
  628. ((= string->number number) (> number 0))
  629. (_ #f)))
  630. (define deduplicate?
  631. (find-daemon-option "deduplicate"))
  632. (define reply-port
  633. ;; Port used to reply to the daemon.
  634. (if (%reply-file-descriptor)
  635. (fdopen (%reply-file-descriptor) "wl")
  636. (current-output-port)))
  637. (mkdir-p %narinfo-cache-directory)
  638. (maybe-remove-expired-cache-entries %narinfo-cache-directory
  639. cached-narinfo-files
  640. #:entry-expiration
  641. cached-narinfo-expiration-time
  642. #:cleanup-period
  643. %narinfo-expired-cache-entry-removal-delay)
  644. (check-acl-initialized)
  645. ;; Sanity-check SUBSTITUTE-URLS so we can provide a meaningful error
  646. ;; message.
  647. (for-each validate-uri (substitute-urls))
  648. ;; Attempt to install the client's locale so that messages are suitably
  649. ;; translated. LC_CTYPE must be a UTF-8 locale; it's the case by default
  650. ;; so don't change it.
  651. (match (or (find-daemon-option "untrusted-locale")
  652. (find-daemon-option "locale"))
  653. (#f #f)
  654. (locale (false-if-exception (setlocale LC_MESSAGES locale))))
  655. (catch 'system-error
  656. (lambda ()
  657. (set-thread-name "guix substitute"))
  658. (const #t)) ;GNU/Hurd lacks 'prctl'
  659. (with-networking
  660. (with-error-handling ; for signature errors
  661. (match args
  662. (("--query")
  663. (let ((acl (current-acl)))
  664. (let loop ((command (read-line)))
  665. (or (eof-object? command)
  666. (begin
  667. (process-query reply-port command
  668. #:cache-urls (substitute-urls)
  669. #:acl acl)
  670. (loop (read-line)))))))
  671. (("--substitute")
  672. ;; Download STORE-PATH and store it as a Nar in file DESTINATION.
  673. ;; Specify the number of columns of the terminal so the progress
  674. ;; report displays nicely.
  675. (parameterize ((current-terminal-columns (client-terminal-columns)))
  676. (let loop ()
  677. (match (read-line)
  678. ((? eof-object?)
  679. #t)
  680. ((= string-tokenize ("substitute" store-path destination))
  681. (process-substitution reply-port store-path destination
  682. #:cache-urls (substitute-urls)
  683. #:acl (current-acl)
  684. #:deduplicate? deduplicate?
  685. #:print-build-trace?
  686. print-build-trace?)
  687. (loop))))))
  688. ((or ("-V") ("--version"))
  689. (show-version-and-exit "guix substitute"))
  690. (("--help")
  691. (show-help))
  692. (opts
  693. (leave (G_ "~a: unrecognized options~%") opts))))))
  694. ;;; Local Variables:
  695. ;;; eval: (put 'with-timeout 'scheme-indent-function 1)
  696. ;;; eval: (put 'with-redirected-error-port 'scheme-indent-function 0)
  697. ;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)
  698. ;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1)
  699. ;;; End:
  700. ;;; substitute.scm ends here