substitute.scm 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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 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-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
  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]...
  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-values (((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-values (((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* (process-substitution port store-item destination
  400. #:key cache-urls acl
  401. deduplicate? print-build-trace?)
  402. "Substitute STORE-ITEM (a store file name) from CACHE-URLS, and write it to
  403. DESTINATION as a nar file. Verify the substitute against ACL, and verify its
  404. hash against what appears in the narinfo. When DEDUPLICATE? is true, and if
  405. DESTINATION is in the store, deduplicate its files. Print a status line to
  406. PORT."
  407. (define narinfo
  408. (lookup-narinfo cache-urls store-item
  409. (if (%allow-unauthenticated-substitutes?)
  410. (const #t)
  411. (cut valid-narinfo? <> acl))))
  412. (define destination-in-store?
  413. (string-prefix? (string-append (%store-prefix) "/")
  414. destination))
  415. (define (dump-file/deduplicate* . args)
  416. ;; Make sure deduplication looks at the right store (necessary in test
  417. ;; environments).
  418. (apply dump-file/deduplicate
  419. (append args (list #:store (%store-prefix)))))
  420. (define (fetch uri)
  421. (case (uri-scheme uri)
  422. ((file)
  423. (let ((port (open-file (uri-path uri) "r0b")))
  424. (values port (stat:size (stat port)))))
  425. ((http https)
  426. (guard (c ((http-get-error? c)
  427. (leave (G_ "download from '~a' failed: ~a, ~s~%")
  428. (uri->string (http-get-error-uri c))
  429. (http-get-error-code c)
  430. (http-get-error-reason c))))
  431. ;; Test this with:
  432. ;; sudo tc qdisc add dev eth0 root netem delay 1500ms
  433. ;; and then cancel with:
  434. ;; sudo tc qdisc del dev eth0 root
  435. (with-timeout %fetch-timeout
  436. (begin
  437. (warning (G_ "while fetching ~a: server is somewhat slow~%")
  438. (uri->string uri))
  439. (warning (G_ "try `--no-substitutes' if the problem persists~%")))
  440. (with-cached-connection uri port
  441. (http-fetch uri #:text? #f
  442. #:port port
  443. #:keep-alive? #t
  444. #:buffered? #f)))))
  445. (else
  446. (leave (G_ "unsupported substitute URI scheme: ~a~%")
  447. (uri->string uri)))))
  448. (unless narinfo
  449. (leave (G_ "no valid substitute for '~a'~%")
  450. store-item))
  451. (let-values (((uri compression file-size)
  452. (narinfo-best-uri narinfo
  453. #:fast-decompression?
  454. %prefer-fast-decompression?)))
  455. (unless print-build-trace?
  456. (format (current-error-port)
  457. (G_ "Downloading ~a...~%") (uri->string uri)))
  458. (let*-values (((raw download-size)
  459. ;; 'guix publish' without '--cache' doesn't specify a
  460. ;; Content-Length, so DOWNLOAD-SIZE is #f in this case.
  461. (fetch uri))
  462. ((progress)
  463. (let* ((dl-size (or download-size
  464. (and (equal? compression "none")
  465. (narinfo-size narinfo))))
  466. (reporter (if print-build-trace?
  467. (progress-reporter/trace
  468. destination
  469. (uri->string uri) dl-size
  470. (current-error-port))
  471. (progress-reporter/file
  472. (uri->string uri) dl-size
  473. (current-error-port)
  474. #:abbreviation nar-uri-abbreviation))))
  475. ;; Keep RAW open upon completion so we can later reuse
  476. ;; the underlying connection. Pass the download size so
  477. ;; that this procedure won't block reading from RAW.
  478. (progress-report-port reporter raw
  479. #:close? #f
  480. #:download-size dl-size)))
  481. ((input pids)
  482. ;; NOTE: This 'progress' port of current process will be
  483. ;; closed here, while the child process doing the
  484. ;; reporting will close it upon exit.
  485. (decompressed-port (string->symbol compression)
  486. progress))
  487. ;; Compute the actual nar hash as we read it.
  488. ((algorithm expected)
  489. (narinfo-hash-algorithm+value narinfo))
  490. ((hashed get-hash)
  491. (open-hash-input-port algorithm input)))
  492. ;; Unpack the Nar at INPUT into DESTINATION.
  493. (define cpu-usage
  494. (with-cpu-usage-monitoring
  495. (restore-file hashed destination
  496. #:dump-file (if (and destination-in-store?
  497. deduplicate?)
  498. dump-file/deduplicate*
  499. dump-file))))
  500. ;; Create a hysteresis: depending on CPU usage, favor compression
  501. ;; methods with faster decompression (like ztsd) or methods with better
  502. ;; compression ratios (like lzip). This stems from the observation that
  503. ;; substitution can be CPU-bound when high-speed networks are used:
  504. ;; <https://lists.gnu.org/archive/html/guix-devel/2020-12/msg00177.html>.
  505. ;; To simulate "slow" networking or changing conditions, run:
  506. ;; sudo tc qdisc add dev eno1 root tbf rate 512kbit latency 50ms burst 1540
  507. ;; and then cancel with:
  508. ;; sudo tc qdisc del dev eno1 root
  509. (when (> cpu-usage .8)
  510. (set! %prefer-fast-decompression? #t))
  511. (when (< cpu-usage .2)
  512. (set! %prefer-fast-decompression? #f))
  513. (close-port hashed)
  514. (close-port input)
  515. ;; Wait for the reporter to finish.
  516. (every (compose zero? cdr waitpid) pids)
  517. ;; Skip a line after what 'progress-reporter/file' printed, and another
  518. ;; one to visually separate substitutions. When PRINT-BUILD-TRACE? is
  519. ;; true, leave it up to (guix status) to prettify things.
  520. (newline (current-error-port))
  521. (unless print-build-trace?
  522. (newline (current-error-port)))
  523. ;; Check whether we got the data announced in NARINFO.
  524. (let ((actual (get-hash)))
  525. (if (bytevector=? actual expected)
  526. ;; Tell the daemon that we're done.
  527. (format port "success ~a ~a~%"
  528. (narinfo-hash narinfo) (narinfo-size narinfo))
  529. ;; The actual data has a different hash than that in NARINFO.
  530. (format port "hash-mismatch ~a ~a ~a~%"
  531. (hash-algorithm-name algorithm)
  532. (bytevector->nix-base32-string expected)
  533. (bytevector->nix-base32-string actual)))))))
  534. ;;;
  535. ;;; Entry point.
  536. ;;;
  537. (define (check-acl-initialized)
  538. "Warn if the ACL is uninitialized."
  539. (define (singleton? acl)
  540. ;; True if ACL contains just the user's public key.
  541. (and (file-exists? %public-key-file)
  542. (let ((key (call-with-input-file %public-key-file
  543. (compose string->canonical-sexp
  544. read-string))))
  545. (match acl
  546. ((thing)
  547. (equal? (canonical-sexp->string thing)
  548. (canonical-sexp->string key)))
  549. (_
  550. #f)))))
  551. (let ((acl (acl->public-keys (current-acl))))
  552. (when (or (null? acl) (singleton? acl))
  553. (warning (G_ "ACL for archive imports seems to be uninitialized, \
  554. substitutes may be unavailable\n")))))
  555. (define (daemon-options)
  556. "Return a list of name/value pairs denoting build daemon options."
  557. (define %not-newline
  558. (char-set-complement (char-set #\newline)))
  559. (match (getenv "_NIX_OPTIONS")
  560. (#f ;should not happen when called by the daemon
  561. '())
  562. (newline-separated
  563. ;; Here we get something of the form "OPTION1=VALUE1\nOPTION2=VALUE2\n".
  564. (filter-map (lambda (option=value)
  565. (match (string-index option=value #\=)
  566. (#f ;invalid option setting
  567. #f)
  568. (equal-sign
  569. (cons (string-take option=value equal-sign)
  570. (string-drop option=value (+ 1 equal-sign))))))
  571. (string-tokenize newline-separated %not-newline)))))
  572. (define (find-daemon-option option)
  573. "Return the value of build daemon option OPTION, or #f if it could not be
  574. found."
  575. (assoc-ref (daemon-options) option))
  576. (define %default-substitute-urls
  577. (match (and=> (or (find-daemon-option "untrusted-substitute-urls") ;client
  578. (find-daemon-option "substitute-urls")) ;admin
  579. string-tokenize)
  580. ((urls ...)
  581. urls)
  582. (#f
  583. ;; This can only happen when this script is not invoked by the
  584. ;; daemon.
  585. '("http://ci.guix.gnu.org"
  586. "http://bordeaux.guix.gnu.org"))))
  587. ;; In order to prevent using large number of discovered local substitute
  588. ;; servers, limit the local substitute urls list size.
  589. (define %max-substitute-urls 50)
  590. (define* (randomize-substitute-urls urls
  591. #:key
  592. (max %max-substitute-urls))
  593. "Return a list containing MAX urls from URLS, picked randomly. If URLS list
  594. is shorter than MAX elements, then it is directly returned."
  595. (define (random-item list)
  596. (list-ref list (random (length list))))
  597. (if (<= (length urls) max)
  598. urls
  599. (let loop ((res '())
  600. (urls urls))
  601. (if (eq? (length res) max)
  602. res
  603. (let ((url (random-item urls)))
  604. (loop (cons url res) (delete url urls)))))))
  605. (define %local-substitute-urls
  606. ;; If the following option is passed to the daemon, use the substitutes list
  607. ;; provided by "guix discover" process.
  608. (let* ((option (find-daemon-option "discover"))
  609. (discover? (and option (string=? option "true"))))
  610. (if discover?
  611. (randomize-substitute-urls (read-substitute-urls))
  612. '())))
  613. (define substitute-urls
  614. ;; List of substitute URLs.
  615. (make-parameter (append %local-substitute-urls
  616. %default-substitute-urls)))
  617. (define (client-terminal-columns)
  618. "Return the number of columns in the client's terminal, if it is known, or a
  619. default value."
  620. (or (and=> (or (find-daemon-option "untrusted-terminal-columns")
  621. (find-daemon-option "terminal-columns"))
  622. (lambda (str)
  623. (let ((number (string->number str)))
  624. (and number (max 20 (- number 1))))))
  625. 80))
  626. (define (validate-uri uri)
  627. (unless (string->uri uri)
  628. (leave (G_ "~a: invalid URI~%") uri)))
  629. (define %reply-file-descriptor
  630. ;; The file descriptor where replies to the daemon must be sent, or #f to
  631. ;; use the current output port instead.
  632. (make-parameter 4))
  633. (define-command (guix-substitute . args)
  634. (category internal)
  635. (synopsis "implement the build daemon's substituter protocol")
  636. (define print-build-trace?
  637. (match (or (find-daemon-option "untrusted-print-extended-build-trace")
  638. (find-daemon-option "print-extended-build-trace"))
  639. (#f #f)
  640. ((= string->number number) (> number 0))
  641. (_ #f)))
  642. (define deduplicate?
  643. (find-daemon-option "deduplicate"))
  644. (define reply-port
  645. ;; Port used to reply to the daemon.
  646. (if (%reply-file-descriptor)
  647. (fdopen (%reply-file-descriptor) "wl")
  648. (current-output-port)))
  649. (mkdir-p %narinfo-cache-directory)
  650. (maybe-remove-expired-cache-entries %narinfo-cache-directory
  651. cached-narinfo-files
  652. #:entry-expiration
  653. cached-narinfo-expiration-time
  654. #:cleanup-period
  655. %narinfo-expired-cache-entry-removal-delay)
  656. (check-acl-initialized)
  657. ;; Sanity-check SUBSTITUTE-URLS so we can provide a meaningful error
  658. ;; message.
  659. (for-each validate-uri (substitute-urls))
  660. ;; Attempt to install the client's locale so that messages are suitably
  661. ;; translated. LC_CTYPE must be a UTF-8 locale; it's the case by default
  662. ;; so don't change it.
  663. (match (or (find-daemon-option "untrusted-locale")
  664. (find-daemon-option "locale"))
  665. (#f #f)
  666. (locale (false-if-exception (setlocale LC_MESSAGES locale))))
  667. (catch 'system-error
  668. (lambda ()
  669. (set-thread-name "guix substitute"))
  670. (const #t)) ;GNU/Hurd lacks 'prctl'
  671. (with-networking
  672. (with-error-handling ; for signature errors
  673. (match args
  674. (("--query")
  675. (let ((acl (current-acl)))
  676. (let loop ((command (read-line)))
  677. (or (eof-object? command)
  678. (begin
  679. (process-query reply-port command
  680. #:cache-urls (substitute-urls)
  681. #:acl acl)
  682. (loop (read-line)))))))
  683. (("--substitute")
  684. ;; Download STORE-PATH and store it as a Nar in file DESTINATION.
  685. ;; Specify the number of columns of the terminal so the progress
  686. ;; report displays nicely.
  687. (parameterize ((current-terminal-columns (client-terminal-columns)))
  688. (let loop ()
  689. (match (read-line)
  690. ((? eof-object?)
  691. #t)
  692. ((= string-tokenize ("substitute" store-path destination))
  693. (process-substitution reply-port store-path destination
  694. #:cache-urls (substitute-urls)
  695. #:acl (current-acl)
  696. #:deduplicate? deduplicate?
  697. #:print-build-trace?
  698. print-build-trace?)
  699. (loop))))))
  700. ((or ("-V") ("--version"))
  701. (show-version-and-exit "guix substitute"))
  702. ((or ("-h") ("--help"))
  703. (show-help))
  704. (opts
  705. (leave (G_ "~a: unrecognized options~%") opts))))))
  706. ;;; Local Variables:
  707. ;;; eval: (put 'with-timeout 'scheme-indent-function 1)
  708. ;;; eval: (put 'with-redirected-error-port 'scheme-indent-function 0)
  709. ;;; eval: (put 'with-cached-connection 'scheme-indent-function 2)
  710. ;;; eval: (put 'call-with-cached-connection 'scheme-indent-function 1)
  711. ;;; End:
  712. ;;; substitute.scm ends here