2c3675dca64d77d50f94e14f035b1ea8530eeb5e
[jackhill/guix/guix.git] / guix / store.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
3 ;;; Copyright © 2018 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;; Copyright © 2019, 2020 Mathieu Othacehe <m.othacehe@gmail.com>
5 ;;; Copyright © 2020 Florian Pelz <pelzflorian@pelzflorian.de>
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
22 (define-module (guix store)
23 #:use-module (guix utils)
24 #:use-module (guix config)
25 #:use-module (guix deprecation)
26 #:use-module (guix memoization)
27 #:use-module (guix serialization)
28 #:use-module (guix monads)
29 #:use-module (guix records)
30 #:use-module (guix base16)
31 #:use-module (guix base32)
32 #:use-module (gcrypt hash)
33 #:use-module (guix profiling)
34 #:autoload (guix build syscalls) (terminal-columns)
35 #:use-module (rnrs bytevectors)
36 #:use-module (ice-9 binary-ports)
37 #:use-module ((ice-9 control) #:select (let/ec))
38 #:use-module (srfi srfi-1)
39 #:use-module (srfi srfi-9)
40 #:use-module (srfi srfi-9 gnu)
41 #:use-module (srfi srfi-11)
42 #:use-module (srfi srfi-26)
43 #:use-module (srfi srfi-34)
44 #:use-module (srfi srfi-35)
45 #:use-module (srfi srfi-39)
46 #:use-module (ice-9 match)
47 #:use-module (ice-9 vlist)
48 #:use-module (ice-9 popen)
49 #:use-module (ice-9 threads)
50 #:use-module (ice-9 format)
51 #:use-module (web uri)
52 #:export (%daemon-socket-uri
53 %gc-roots-directory
54 %default-substitute-urls
55
56 store-connection?
57 store-connection-version
58 store-connection-major-version
59 store-connection-minor-version
60 store-connection-socket
61
62 ;; Deprecated forms for 'store-connection'.
63 nix-server?
64 nix-server-version
65 nix-server-major-version
66 nix-server-minor-version
67 nix-server-socket
68
69 current-store-protocol-version ;for internal use
70 mcached
71
72 &store-error store-error?
73 &store-connection-error store-connection-error?
74 store-connection-error-file
75 store-connection-error-code
76 &store-protocol-error store-protocol-error?
77 store-protocol-error-message
78 store-protocol-error-status
79
80 ;; Deprecated forms for '&store-error' et al.
81 &nix-error nix-error?
82 &nix-connection-error nix-connection-error?
83 nix-connection-error-file
84 nix-connection-error-code
85 &nix-protocol-error nix-protocol-error?
86 nix-protocol-error-message
87 nix-protocol-error-status
88
89 hash-algo
90 build-mode
91
92 open-connection
93 port->connection
94 close-connection
95 with-store
96 set-build-options
97 set-build-options*
98 valid-path?
99 query-path-hash
100 hash-part->path
101 query-path-info
102 add-data-to-store
103 add-text-to-store
104 add-to-store
105 add-file-tree-to-store
106 binary-file
107 build-things
108 build
109 query-failed-paths
110 clear-failed-paths
111 add-temp-root
112 add-indirect-root
113 add-permanent-root
114 remove-permanent-root
115
116 substitutable?
117 substitutable-path
118 substitutable-deriver
119 substitutable-references
120 substitutable-download-size
121 substitutable-nar-size
122 has-substitutes?
123 substitutable-paths
124 substitutable-path-info
125
126 path-info?
127 path-info-deriver
128 path-info-hash
129 path-info-references
130 path-info-registration-time
131 path-info-nar-size
132
133 built-in-builders
134 references
135 references/substitutes
136 references*
137 query-path-info*
138 requisites
139 referrers
140 optimize-store
141 verify-store
142 topologically-sorted
143 valid-derivers
144 query-derivation-outputs
145 live-paths
146 dead-paths
147 collect-garbage
148 delete-paths
149 import-paths
150 export-paths
151
152 current-build-output-port
153
154 %store-monad
155 store-bind
156 store-return
157 store-lift
158 store-lower
159 run-with-store
160 %guile-for-build
161 current-system
162 set-current-system
163 current-target-system
164 set-current-target
165 text-file
166 interned-file
167 interned-file-tree
168
169 %store-prefix
170 store-path
171 output-path
172 fixed-output-path
173 store-path?
174 direct-store-path?
175 derivation-path?
176 store-path-base
177 store-path-package-name
178 store-path-hash-part
179 direct-store-path
180 derivation-log-file
181 log-file))
182
183 (define %protocol-version #x163)
184
185 (define %worker-magic-1 #x6e697863) ; "nixc"
186 (define %worker-magic-2 #x6478696f) ; "dxio"
187
188 (define (protocol-major magic)
189 (logand magic #xff00))
190 (define (protocol-minor magic)
191 (logand magic #x00ff))
192 (define (protocol-version major minor)
193 (logior major minor))
194
195 (define-syntax define-enumerate-type
196 (syntax-rules ()
197 ((_ name->int (name id) ...)
198 (define-syntax name->int
199 (syntax-rules (name ...)
200 ((_ name) id) ...)))))
201
202 (define-enumerate-type operation-id
203 ;; operation numbers from worker-protocol.hh
204 (quit 0)
205 (valid-path? 1)
206 (has-substitutes? 3)
207 (query-path-hash 4)
208 (query-references 5)
209 (query-referrers 6)
210 (add-to-store 7)
211 (add-text-to-store 8)
212 (build-things 9)
213 (ensure-path 10)
214 (add-temp-root 11)
215 (add-indirect-root 12)
216 (sync-with-gc 13)
217 (find-roots 14)
218 (export-path 16)
219 (query-deriver 18)
220 (set-options 19)
221 (collect-garbage 20)
222 ;;(query-substitutable-path-info 21) ; obsolete as of #x10c
223 (query-derivation-outputs 22)
224 (query-all-valid-paths 23)
225 (query-failed-paths 24)
226 (clear-failed-paths 25)
227 (query-path-info 26)
228 (import-paths 27)
229 (query-derivation-output-names 28)
230 (query-path-from-hash-part 29)
231 (query-substitutable-path-infos 30)
232 (query-valid-paths 31)
233 (query-substitutable-paths 32)
234 (query-valid-derivers 33)
235 (optimize-store 34)
236 (verify-store 35)
237 (built-in-builders 80))
238
239 (define-enumerate-type hash-algo
240 ;; hash.hh
241 (md5 1)
242 (sha1 2)
243 (sha256 3))
244
245 (define-enumerate-type build-mode
246 ;; store-api.hh
247 (normal 0)
248 (repair 1)
249 (check 2))
250
251 (define-enumerate-type gc-action
252 ;; store-api.hh
253 (return-live 0)
254 (return-dead 1)
255 (delete-dead 2)
256 (delete-specific 3))
257
258 (define %default-socket-path
259 (string-append %state-directory "/daemon-socket/socket"))
260
261 (define %daemon-socket-uri
262 ;; URI or file name of the socket the daemon listens too.
263 (make-parameter (or (getenv "GUIX_DAEMON_SOCKET")
264 %default-socket-path)))
265
266
267 \f
268 ;; Information about a substitutable store path.
269 (define-record-type <substitutable>
270 (substitutable path deriver refs dl-size nar-size)
271 substitutable?
272 (path substitutable-path)
273 (deriver substitutable-deriver)
274 (refs substitutable-references)
275 (dl-size substitutable-download-size)
276 (nar-size substitutable-nar-size))
277
278 (define (read-substitutable-path-list p)
279 (let loop ((len (read-int p))
280 (result '()))
281 (if (zero? len)
282 (reverse result)
283 (let ((path (read-store-path p))
284 (deriver (read-store-path p))
285 (refs (read-store-path-list p))
286 (dl-size (read-long-long p))
287 (nar-size (read-long-long p)))
288 (loop (- len 1)
289 (cons (substitutable path deriver refs dl-size nar-size)
290 result))))))
291
292 ;; Information about a store path.
293 (define-record-type <path-info>
294 (path-info deriver hash references registration-time nar-size)
295 path-info?
296 (deriver path-info-deriver) ;string | #f
297 (hash path-info-hash)
298 (references path-info-references)
299 (registration-time path-info-registration-time)
300 (nar-size path-info-nar-size))
301
302 (define (read-path-info p)
303 (let ((deriver (match (read-store-path p)
304 ("" #f)
305 (x x)))
306 (hash (base16-string->bytevector (read-string p)))
307 (refs (read-store-path-list p))
308 (registration-time (read-int p))
309 (nar-size (read-long-long p)))
310 (path-info deriver hash refs registration-time nar-size)))
311
312 (define-syntax write-arg
313 (syntax-rules (integer boolean bytevector
314 string string-list string-pairs
315 store-path store-path-list base16)
316 ((_ integer arg p)
317 (write-int arg p))
318 ((_ boolean arg p)
319 (write-int (if arg 1 0) p))
320 ((_ bytevector arg p)
321 (write-bytevector arg p))
322 ((_ string arg p)
323 (write-string arg p))
324 ((_ string-list arg p)
325 (write-string-list arg p))
326 ((_ string-pairs arg p)
327 (write-string-pairs arg p))
328 ((_ store-path arg p)
329 (write-store-path arg p))
330 ((_ store-path-list arg p)
331 (write-store-path-list arg p))
332 ((_ base16 arg p)
333 (write-string (bytevector->base16-string arg) p))))
334
335 (define-syntax read-arg
336 (syntax-rules (integer boolean string store-path store-path-list string-list
337 substitutable-path-list path-info base16)
338 ((_ integer p)
339 (read-int p))
340 ((_ boolean p)
341 (not (zero? (read-int p))))
342 ((_ string p)
343 (read-string p))
344 ((_ store-path p)
345 (read-store-path p))
346 ((_ store-path-list p)
347 (read-store-path-list p))
348 ((_ string-list p)
349 (read-string-list p))
350 ((_ substitutable-path-list p)
351 (read-substitutable-path-list p))
352 ((_ path-info p)
353 (read-path-info p))
354 ((_ base16 p)
355 (base16-string->bytevector (read-string p)))))
356
357 \f
358 ;; remote-store.cc
359
360 (define-record-type* <store-connection> store-connection %make-store-connection
361 store-connection?
362 (socket store-connection-socket)
363 (major store-connection-major-version)
364 (minor store-connection-minor-version)
365
366 (buffer store-connection-output-port) ;output port
367 (flush store-connection-flush-output) ;thunk
368
369 ;; Caches. We keep them per-connection, because store paths build
370 ;; during the session are temporary GC roots kept for the duration of
371 ;; the session.
372 (ats-cache store-connection-add-to-store-cache)
373 (atts-cache store-connection-add-text-to-store-cache)
374 (object-cache store-connection-object-cache
375 (default vlist-null)) ;vhash
376 (built-in-builders store-connection-built-in-builders
377 (default (delay '())))) ;promise
378
379 (set-record-type-printer! <store-connection>
380 (lambda (obj port)
381 (format port "#<store-connection ~a.~a ~a>"
382 (store-connection-major-version obj)
383 (store-connection-minor-version obj)
384 (number->string (object-address obj)
385 16))))
386
387 (define-deprecated/alias nix-server? store-connection?)
388 (define-deprecated/alias nix-server-major-version
389 store-connection-major-version)
390 (define-deprecated/alias nix-server-minor-version
391 store-connection-minor-version)
392 (define-deprecated/alias nix-server-socket store-connection-socket)
393
394
395 (define-condition-type &store-error &error
396 store-error?)
397
398 (define-condition-type &store-connection-error &store-error
399 store-connection-error?
400 (file store-connection-error-file)
401 (errno store-connection-error-code))
402
403 (define-condition-type &store-protocol-error &store-error
404 store-protocol-error?
405 (message store-protocol-error-message)
406 (status store-protocol-error-status))
407
408 (define-deprecated/alias &nix-error &store-error)
409 (define-deprecated/alias nix-error? store-error?)
410 (define-deprecated/alias &nix-connection-error &store-connection-error)
411 (define-deprecated/alias nix-connection-error? store-connection-error?)
412 (define-deprecated/alias nix-connection-error-file
413 store-connection-error-file)
414 (define-deprecated/alias nix-connection-error-code
415 store-connection-error-code)
416 (define-deprecated/alias &nix-protocol-error &store-protocol-error)
417 (define-deprecated/alias nix-protocol-error? store-protocol-error?)
418 (define-deprecated/alias nix-protocol-error-message
419 store-protocol-error-message)
420 (define-deprecated/alias nix-protocol-error-status
421 store-protocol-error-status)
422
423
424 (define-syntax-rule (system-error-to-connection-error file exp ...)
425 "Catch 'system-error' exceptions and translate them to
426 '&store-connection-error'."
427 (catch 'system-error
428 (lambda ()
429 exp ...)
430 (lambda args
431 (let ((errno (system-error-errno args)))
432 (raise (condition (&store-connection-error
433 (file file)
434 (errno errno))))))))
435
436 (define (open-unix-domain-socket file)
437 "Connect to the Unix-domain socket at FILE and return it. Raise a
438 '&store-connection-error' upon error."
439 (let ((s (with-fluids ((%default-port-encoding #f))
440 ;; This trick allows use of the `scm_c_read' optimization.
441 (socket PF_UNIX SOCK_STREAM 0)))
442 (a (make-socket-address PF_UNIX file)))
443
444 (system-error-to-connection-error file
445 (connect s a)
446 s)))
447
448 (define %default-guix-port
449 ;; Default port when connecting to a daemon over TCP/IP.
450 44146)
451
452 (define (open-inet-socket host port)
453 "Connect to the Unix-domain socket at HOST:PORT and return it. Raise a
454 '&store-connection-error' upon error."
455 (let ((sock (with-fluids ((%default-port-encoding #f))
456 ;; This trick allows use of the `scm_c_read' optimization.
457 (socket PF_UNIX SOCK_STREAM 0))))
458 (define addresses
459 (getaddrinfo host
460 (if (number? port) (number->string port) port)
461 (if (number? port)
462 (logior AI_ADDRCONFIG AI_NUMERICSERV)
463 AI_ADDRCONFIG)
464 0 ;any address family
465 SOCK_STREAM)) ;TCP only
466
467 (let loop ((addresses addresses))
468 (match addresses
469 ((ai rest ...)
470 (let ((s (socket (addrinfo:fam ai)
471 ;; TCP/IP only
472 SOCK_STREAM IPPROTO_IP)))
473
474 (catch 'system-error
475 (lambda ()
476 (connect s (addrinfo:addr ai))
477
478 ;; Setting this option makes a dramatic difference because it
479 ;; avoids the "ACK delay" on our RPC messages.
480 (setsockopt s IPPROTO_TCP TCP_NODELAY 1)
481 s)
482 (lambda args
483 ;; Connection failed, so try one of the other addresses.
484 (close s)
485 (if (null? rest)
486 (raise (condition (&store-connection-error
487 (file host)
488 (errno (system-error-errno args)))))
489 (loop rest))))))))))
490
491 (define (connect-to-daemon uri)
492 "Connect to the daemon at URI, a string that may be an actual URI or a file
493 name."
494 (define (not-supported)
495 (raise (condition (&store-connection-error
496 (file uri)
497 (errno ENOTSUP)))))
498
499 (define connect
500 (match (string->uri uri)
501 (#f ;URI is a file name
502 open-unix-domain-socket)
503 ((? uri? uri)
504 (match (uri-scheme uri)
505 ((or #f 'file 'unix)
506 (lambda (_)
507 (open-unix-domain-socket (uri-path uri))))
508 ('guix
509 (lambda (_)
510 (open-inet-socket (uri-host uri)
511 (or (uri-port uri) %default-guix-port))))
512 ((? symbol? scheme)
513 ;; Try to dynamically load a module for SCHEME.
514 ;; XXX: Errors are swallowed.
515 (match (false-if-exception
516 (resolve-interface `(guix store ,scheme)))
517 ((? module? module)
518 (match (false-if-exception
519 (module-ref module 'connect-to-daemon))
520 ((? procedure? connect)
521 (lambda (_)
522 (connect uri)))
523 (x (not-supported))))
524 (#f (not-supported))))
525 (x
526 (not-supported))))))
527
528 (connect uri))
529
530 (define* (open-connection #:optional (uri (%daemon-socket-uri))
531 #:key port (reserve-space? #t) cpu-affinity)
532 "Connect to the daemon at URI (a string), or, if PORT is not #f, use it as
533 the I/O port over which to communicate to a build daemon.
534
535 When RESERVE-SPACE? is true, instruct it to reserve a little bit of extra
536 space on the file system so that the garbage collector can still operate,
537 should the disk become full. When CPU-AFFINITY is true, it must be an integer
538 corresponding to an OS-level CPU number to which the daemon's worker process
539 for this connection will be pinned. Return a server object."
540 (guard (c ((nar-error? c)
541 ;; One of the 'write-' or 'read-' calls below failed, but this is
542 ;; really a connection error.
543 (raise (condition
544 (&store-connection-error (file (or port uri))
545 (errno EPROTO))
546 (&message (message "build daemon handshake failed"))))))
547 (let*-values (((port)
548 (or port (connect-to-daemon uri)))
549 ((output flush)
550 (buffering-output-port port
551 (make-bytevector 8192))))
552 (write-int %worker-magic-1 port)
553 (let ((r (read-int port)))
554 (and (eqv? r %worker-magic-2)
555 (let ((v (read-int port)))
556 (and (eqv? (protocol-major %protocol-version)
557 (protocol-major v))
558 (begin
559 (write-int %protocol-version port)
560 (when (>= (protocol-minor v) 14)
561 (write-int (if cpu-affinity 1 0) port)
562 (when cpu-affinity
563 (write-int cpu-affinity port)))
564 (when (>= (protocol-minor v) 11)
565 (write-int (if reserve-space? 1 0) port))
566 (letrec* ((built-in-builders
567 (delay (%built-in-builders conn)))
568 (conn
569 (%make-store-connection port
570 (protocol-major v)
571 (protocol-minor v)
572 output flush
573 (make-hash-table 100)
574 (make-hash-table 100)
575 vlist-null
576 built-in-builders)))
577 (let loop ((done? (process-stderr conn)))
578 (or done? (process-stderr conn)))
579 conn)))))))))
580
581 (define* (port->connection port
582 #:key (version %protocol-version))
583 "Assimilate PORT, an input/output port, and return a connection to the
584 daemon, assuming the given protocol VERSION.
585
586 Warning: this procedure assumes that the initial handshake with the daemon has
587 already taken place on PORT and that we're just continuing on this established
588 connection. Use with care."
589 (let-values (((output flush)
590 (buffering-output-port port (make-bytevector 8192))))
591 (define connection
592 (%make-store-connection port
593 (protocol-major version)
594 (protocol-minor version)
595 output flush
596 (make-hash-table 100)
597 (make-hash-table 100)
598 vlist-null
599 (delay (%built-in-builders connection))))
600
601 connection))
602
603 (define (store-connection-version store)
604 "Return the protocol version of STORE as an integer."
605 (protocol-version (store-connection-major-version store)
606 (store-connection-minor-version store)))
607
608 (define-deprecated/alias nix-server-version store-connection-version)
609
610 (define (write-buffered-output server)
611 "Flush SERVER's output port."
612 (force-output (store-connection-output-port server))
613 ((store-connection-flush-output server)))
614
615 (define (close-connection server)
616 "Close the connection to SERVER."
617 (close (store-connection-socket server)))
618
619 (define (call-with-store proc)
620 "Call PROC with an open store connection."
621 (let ((store (open-connection)))
622 (dynamic-wind
623 (const #f)
624 (lambda ()
625 (parameterize ((current-store-protocol-version
626 (store-connection-version store)))
627 (proc store)))
628 (lambda ()
629 (false-if-exception (close-connection store))))))
630
631 (define-syntax-rule (with-store store exp ...)
632 "Bind STORE to an open connection to the store and evaluate EXPs;
633 automatically close the store when the dynamic extent of EXP is left."
634 (call-with-store (lambda (store) exp ...)))
635
636 (define current-store-protocol-version
637 ;; Protocol version of the store currently used. XXX: This is a hack to
638 ;; communicate the protocol version to the build output port. It's a hack
639 ;; because it could be inaccurrate, for instance if there's code that
640 ;; manipulates several store connections at once; it works well for the
641 ;; purposes of (guix status) though.
642 (make-parameter #f))
643
644 (define current-build-output-port
645 ;; The port where build output is sent.
646 (make-parameter (current-error-port)))
647
648 (define* (dump-port in out
649 #:optional len
650 #:key (buffer-size 16384))
651 "Read LEN bytes from IN (or as much as possible if LEN is #f) and write it
652 to OUT, using chunks of BUFFER-SIZE bytes."
653 (define buffer
654 (make-bytevector buffer-size))
655
656 (let loop ((total 0)
657 (bytes (get-bytevector-n! in buffer 0
658 (if len
659 (min len buffer-size)
660 buffer-size))))
661 (or (eof-object? bytes)
662 (and len (= total len))
663 (let ((total (+ total bytes)))
664 (put-bytevector out buffer 0 bytes)
665 (loop total
666 (get-bytevector-n! in buffer 0
667 (if len
668 (min (- len total) buffer-size)
669 buffer-size)))))))
670
671 (define %newlines
672 ;; Newline characters triggering a flush of 'current-build-output-port'.
673 ;; Unlike Guile's 'line, we flush upon #\return so that progress reports
674 ;; that use that trick are correctly displayed.
675 (char-set #\newline #\return))
676
677 (define* (process-stderr server #:optional user-port)
678 "Read standard output and standard error from SERVER, writing it to
679 CURRENT-BUILD-OUTPUT-PORT. Return #t when SERVER is done sending data, and
680 #f otherwise; in the latter case, the caller should call `process-stderr'
681 again until #t is returned or an error is raised.
682
683 Since the build process's output cannot be assumed to be UTF-8, we
684 conservatively consider it to be Latin-1, thereby avoiding possible
685 encoding conversion errors."
686 (define p
687 (store-connection-socket server))
688
689 ;; magic cookies from worker-protocol.hh
690 (define %stderr-next #x6f6c6d67) ; "olmg", build log
691 (define %stderr-read #x64617461) ; "data", data needed from source
692 (define %stderr-write #x64617416) ; "dat\x16", data for sink
693 (define %stderr-last #x616c7473) ; "alts", we're done
694 (define %stderr-error #x63787470) ; "cxtp", error reporting
695
696 (let ((k (read-int p)))
697 (cond ((= k %stderr-write)
698 ;; Write a byte stream to USER-PORT.
699 (let* ((len (read-int p))
700 (m (modulo len 8)))
701 (dump-port p user-port len
702 #:buffer-size (if (<= len 16384) 16384 65536))
703 (unless (zero? m)
704 ;; Consume padding, as for strings.
705 (get-bytevector-n p (- 8 m))))
706 #f)
707 ((= k %stderr-read)
708 ;; Read a byte stream from USER-PORT.
709 ;; Note: Avoid 'get-bytevector-n' to work around
710 ;; <http://bugs.gnu.org/17591> in Guile up to 2.0.11.
711 (let* ((max-len (read-int p))
712 (data (make-bytevector max-len))
713 (len (get-bytevector-n! user-port data 0 max-len)))
714 (write-bytevector data p len)
715 #f))
716 ((= k %stderr-next)
717 ;; Log a string. Build logs are usually UTF-8-encoded, but they
718 ;; may also contain arbitrary byte sequences that should not cause
719 ;; this to fail. Thus, use the permissive
720 ;; 'read-maybe-utf8-string'.
721 (let ((s (read-maybe-utf8-string p)))
722 (display s (current-build-output-port))
723 (when (string-any %newlines s)
724 (force-output (current-build-output-port)))
725 #f))
726 ((= k %stderr-error)
727 ;; Report an error.
728 (let ((error (read-maybe-utf8-string p))
729 ;; Currently the daemon fails to send a status code for early
730 ;; errors like DB schema version mismatches, so check for EOF.
731 (status (if (and (>= (store-connection-minor-version server) 8)
732 (not (eof-object? (lookahead-u8 p))))
733 (read-int p)
734 1)))
735 (raise (condition (&store-protocol-error
736 (message error)
737 (status status))))))
738 ((= k %stderr-last)
739 ;; The daemon is done (see `stopWork' in `nix-worker.cc'.)
740 #t)
741 (else
742 (raise (condition (&store-protocol-error
743 (message "invalid error code")
744 (status k))))))))
745
746 (define %default-substitute-urls
747 ;; Default list of substituters. This is *not* the list baked in
748 ;; 'guix-daemon', but it is used by 'guix-service-type' and and a couple of
749 ;; clients ('guix build --log-file' uses it.)
750 (map (if (false-if-exception (resolve-interface '(gnutls)))
751 (cut string-append "https://" <>)
752 (cut string-append "http://" <>))
753 '("ci.guix.gnu.org")))
754
755 (define (current-user-name)
756 "Return the name of the calling user."
757 (catch #t
758 (lambda ()
759 (passwd:name (getpwuid (getuid))))
760 (lambda _
761 (getenv "USER"))))
762
763 (define* (set-build-options server
764 #:key keep-failed? keep-going? fallback?
765 (verbosity 0)
766 rounds ;number of build rounds
767 max-build-jobs
768 timeout
769 max-silent-time
770 (offload? #t)
771 (use-build-hook? *unspecified*) ;deprecated
772 (build-verbosity 0)
773 (log-type 0)
774 (print-build-trace #t)
775 (user-name (current-user-name))
776
777 ;; When true, provide machine-readable "build
778 ;; traces" for use by (guix status). Old clients
779 ;; are unable to make sense, which is why it's
780 ;; disabled by default.
781 print-extended-build-trace?
782
783 ;; When true, the daemon prefixes builder output
784 ;; with "@ build-log" traces so we can
785 ;; distinguish it from daemon output, and we can
786 ;; distinguish each builder's output
787 ;; (PRINT-BUILD-TRACE must be true as well.) The
788 ;; latter is particularly useful when
789 ;; MAX-BUILD-JOBS > 1.
790 multiplexed-build-output?
791
792 build-cores
793 (use-substitutes? #t)
794
795 ;; Client-provided substitute URLs. If it is #f,
796 ;; the daemon's settings are used. Otherwise, it
797 ;; overrides the daemons settings; see 'guix
798 ;; substitute'.
799 (substitute-urls #f)
800
801 ;; Number of columns in the client's terminal.
802 (terminal-columns (terminal-columns))
803
804 ;; Locale of the client.
805 (locale (false-if-exception (setlocale LC_ALL))))
806 ;; Must be called after `open-connection'.
807
808 (define socket
809 (store-connection-socket server))
810
811 (unless (unspecified? use-build-hook?)
812 (warn-about-deprecation #:use-build-hook? #f
813 #:replacement #:offload?))
814
815 (let-syntax ((send (syntax-rules ()
816 ((_ (type option) ...)
817 (begin
818 (write-arg type option socket)
819 ...)))))
820 (write-int (operation-id set-options) socket)
821 (send (boolean keep-failed?) (boolean keep-going?)
822 (boolean fallback?) (integer verbosity))
823 (when (< (store-connection-minor-version server) #x61)
824 (let ((max-build-jobs (or max-build-jobs 1))
825 (max-silent-time (or max-silent-time 3600)))
826 (send (integer max-build-jobs) (integer max-silent-time))))
827 (when (>= (store-connection-minor-version server) 2)
828 (send (boolean (if (unspecified? use-build-hook?)
829 offload?
830 use-build-hook?))))
831 (when (>= (store-connection-minor-version server) 4)
832 (send (integer build-verbosity) (integer log-type)
833 (boolean print-build-trace)))
834 (when (and (>= (store-connection-minor-version server) 6)
835 (< (store-connection-minor-version server) #x61))
836 (let ((build-cores (or build-cores (current-processor-count))))
837 (send (integer build-cores))))
838 (when (>= (store-connection-minor-version server) 10)
839 (send (boolean use-substitutes?)))
840 (when (>= (store-connection-minor-version server) 12)
841 (let ((pairs `(;; This option is honored by 'guix substitute' et al.
842 ,@(if print-build-trace
843 `(("print-extended-build-trace"
844 . ,(if print-extended-build-trace? "1" "0")))
845 '())
846 ,@(if multiplexed-build-output?
847 `(("multiplexed-build-output"
848 . ,(if multiplexed-build-output? "true" "false")))
849 '())
850 ,@(if timeout
851 `(("build-timeout" . ,(number->string timeout)))
852 '())
853 ,@(if max-silent-time
854 `(("build-max-silent-time"
855 . ,(number->string max-silent-time)))
856 '())
857 ,@(if max-build-jobs
858 `(("build-max-jobs"
859 . ,(number->string max-build-jobs)))
860 '())
861 ,@(if build-cores
862 `(("build-cores" . ,(number->string build-cores)))
863 '())
864 ,@(if substitute-urls
865 `(("substitute-urls"
866 . ,(string-join substitute-urls)))
867 '())
868 ,@(if rounds
869 `(("build-repeat"
870 . ,(number->string (max 0 (1- rounds)))))
871 '())
872 ,@(if user-name
873 `(("user-name" . ,user-name))
874 '())
875 ,@(if terminal-columns
876 `(("terminal-columns"
877 . ,(number->string terminal-columns)))
878 '())
879 ,@(if locale
880 `(("locale" . ,locale))
881 '()))))
882 (send (string-pairs pairs))))
883 (let loop ((done? (process-stderr server)))
884 (or done? (process-stderr server)))))
885
886 (define (buffering-output-port port buffer)
887 "Return two value: an output port wrapped around PORT that uses BUFFER (a
888 bytevector) as its internal buffer, and a thunk to flush this output port."
889 ;; Note: In Guile 2.2.2, custom binary output ports already have their own
890 ;; 4K internal buffer.
891 (define size
892 (bytevector-length buffer))
893
894 (define total 0)
895
896 (define (flush)
897 (put-bytevector port buffer 0 total)
898 (force-output port)
899 (set! total 0))
900
901 (define (write bv offset count)
902 (if (zero? count) ;end of file
903 (flush)
904 (let loop ((offset offset)
905 (count count)
906 (written 0))
907 (cond ((= total size)
908 (flush)
909 (loop offset count written))
910 ((zero? count)
911 written)
912 (else
913 (let ((to-copy (min count (- size total))))
914 (bytevector-copy! bv offset buffer total to-copy)
915 (set! total (+ total to-copy))
916 (loop (+ offset to-copy) (- count to-copy)
917 (+ written to-copy))))))))
918
919 ;; Note: We need to return FLUSH because the custom binary port has no way
920 ;; to be notified of a 'force-output' call on itself.
921 (values (make-custom-binary-output-port "buffering-output-port"
922 write #f #f flush)
923 flush))
924
925 (define profiled?
926 (let ((profiled
927 (or (and=> (getenv "GUIX_PROFILING") string-tokenize)
928 '())))
929 (lambda (component)
930 "Return true if COMPONENT profiling is active."
931 (member component profiled))))
932
933 (define %rpc-calls
934 ;; Mapping from RPC names (symbols) to invocation counts.
935 (make-hash-table))
936
937 (define* (show-rpc-profile #:optional (port (current-error-port)))
938 "Write to PORT a summary of the RPCs that have been made."
939 (let ((profile (sort (hash-fold alist-cons '() %rpc-calls)
940 (lambda (rpc1 rpc2)
941 (< (cdr rpc1) (cdr rpc2))))))
942 (format port "Remote procedure call summary: ~a RPCs~%"
943 (match profile
944 (((names . counts) ...)
945 (reduce + 0 counts))))
946 (for-each (match-lambda
947 ((rpc . count)
948 (format port " ~30a ... ~5@a~%" rpc count)))
949 profile)))
950
951 (define record-operation
952 ;; Optionally, increment the number of calls of the given RPC.
953 (if (profiled? "rpc")
954 (begin
955 (register-profiling-hook! "rpc" show-rpc-profile)
956 (lambda (name)
957 (let ((count (or (hashq-ref %rpc-calls name) 0)))
958 (hashq-set! %rpc-calls name (+ count 1)))))
959 (lambda (_)
960 #t)))
961
962 (define-syntax operation
963 (syntax-rules ()
964 "Define a client-side RPC stub for the given operation."
965 ((_ (name (type arg) ...) docstring return ...)
966 (lambda (server arg ...)
967 docstring
968 (let* ((s (store-connection-socket server))
969 (buffered (store-connection-output-port server)))
970 (record-operation 'name)
971 (write-int (operation-id name) buffered)
972 (write-arg type arg buffered)
973 ...
974 (write-buffered-output server)
975
976 ;; Loop until the server is done sending error output.
977 (let loop ((done? (process-stderr server)))
978 (or done? (loop (process-stderr server))))
979 (values (read-arg return s) ...))))))
980
981 (define-syntax-rule (define-operation (name args ...)
982 docstring return ...)
983 (define name
984 (operation (name args ...) docstring return ...)))
985
986 (define-operation (valid-path? (string path))
987 "Return #t when PATH designates a valid store item and #f otherwise (an
988 invalid item may exist on disk but still be invalid, for instance because it
989 is the result of an aborted or failed build.)
990
991 A '&store-protocol-error' condition is raised if PATH is not prefixed by the
992 store directory (/gnu/store)."
993 boolean)
994
995 (define-operation (query-path-hash (store-path path))
996 "Return the SHA256 hash of the nar serialization of PATH as a bytevector."
997 base16)
998
999 (define hash-part->path
1000 (let ((query-path-from-hash-part
1001 (operation (query-path-from-hash-part (string hash))
1002 #f
1003 store-path)))
1004 (lambda (server hash-part)
1005 "Return the store path whose hash part is HASH-PART (a nix-base32
1006 string). Return the empty string if no such path exists."
1007 ;; This RPC is primarily used by Hydra to reply to HTTP GETs of
1008 ;; /HASH.narinfo.
1009 (query-path-from-hash-part server hash-part))))
1010
1011 (define-operation (query-path-info (store-path path))
1012 "Return the info (hash, references, etc.) for PATH."
1013 path-info)
1014
1015 (define add-data-to-store
1016 ;; A memoizing version of `add-to-store', to avoid repeated RPCs with
1017 ;; the very same arguments during a given session.
1018 (let ((add-text-to-store
1019 (operation (add-text-to-store (string name) (bytevector text)
1020 (string-list references))
1021 #f
1022 store-path))
1023 (lookup (if (profiled? "add-data-to-store-cache")
1024 (let ((lookups 0)
1025 (hits 0)
1026 (drv 0)
1027 (scheme 0))
1028 (define (show-stats)
1029 (define (% n)
1030 (if (zero? lookups)
1031 100.
1032 (* 100. (/ n lookups))))
1033
1034 (format (current-error-port) "
1035 'add-data-to-store' cache:
1036 lookups: ~5@a
1037 hits: ~5@a (~,1f%)
1038 .drv files: ~5@a (~,1f%)
1039 Scheme files: ~5@a (~,1f%)~%"
1040 lookups hits (% hits)
1041 drv (% drv)
1042 scheme (% scheme)))
1043
1044 (register-profiling-hook! "add-data-to-store-cache"
1045 show-stats)
1046 (lambda (cache args)
1047 (let ((result (hash-ref cache args)))
1048 (set! lookups (+ 1 lookups))
1049 (when result
1050 (set! hits (+ 1 hits)))
1051 (match args
1052 ((_ name _)
1053 (cond ((string-suffix? ".drv" name)
1054 (set! drv (+ drv 1)))
1055 ((string-suffix? "-builder" name)
1056 (set! scheme (+ scheme 1)))
1057 ((string-suffix? ".scm" name)
1058 (set! scheme (+ scheme 1))))))
1059 result)))
1060 hash-ref)))
1061 (lambda* (server name bytes #:optional (references '()))
1062 "Add BYTES under file NAME in the store, and return its store path.
1063 REFERENCES is the list of store paths referred to by the resulting store
1064 path."
1065 (let* ((args `(,bytes ,name ,references))
1066 (cache (store-connection-add-text-to-store-cache server)))
1067 (or (lookup cache args)
1068 (let ((path (add-text-to-store server name bytes references)))
1069 (hash-set! cache args path)
1070 path))))))
1071
1072 (define* (add-text-to-store store name text #:optional (references '()))
1073 "Add TEXT under file NAME in the store, and return its store path.
1074 REFERENCES is the list of store paths referred to by the resulting store
1075 path."
1076 (add-data-to-store store name (string->utf8 text) references))
1077
1078 (define true
1079 ;; Define it once and for all since we use it as a default value for
1080 ;; 'add-to-store' and want to make sure two default values are 'eq?' for the
1081 ;; purposes or memoization.
1082 (lambda (file stat)
1083 #t))
1084
1085 (define add-to-store
1086 ;; A memoizing version of `add-to-store'. This is important because
1087 ;; `add-to-store' leads to huge data transfers to the server, and
1088 ;; because it's often called many times with the very same argument.
1089 (let ((add-to-store
1090 (lambda* (server basename recursive? hash-algo file-name
1091 #:key (select? true))
1092 ;; We don't use the 'operation' macro so we can pass SELECT? to
1093 ;; 'write-file'.
1094 (record-operation 'add-to-store)
1095 (let ((port (store-connection-socket server)))
1096 (write-int (operation-id add-to-store) port)
1097 (write-string basename port)
1098 (write-int 1 port) ;obsolete, must be #t
1099 (write-int (if recursive? 1 0) port)
1100 (write-string hash-algo port)
1101 (write-file file-name port #:select? select?)
1102 (write-buffered-output server)
1103 (let loop ((done? (process-stderr server)))
1104 (or done? (loop (process-stderr server))))
1105 (read-store-path port)))))
1106 (lambda* (server basename recursive? hash-algo file-name
1107 #:key (select? true))
1108 "Add the contents of FILE-NAME under BASENAME to the store. When
1109 RECURSIVE? is false, FILE-NAME must designate a regular file--not a directory
1110 nor a symlink. When RECURSIVE? is true and FILE-NAME designates a directory,
1111 the contents of FILE-NAME are added recursively; if FILE-NAME designates a
1112 flat file and RECURSIVE? is true, its contents are added, and its permission
1113 bits are kept. HASH-ALGO must be a string such as \"sha256\".
1114
1115 When RECURSIVE? is true, call (SELECT? FILE STAT) for each directory entry,
1116 where FILE is the entry's absolute file name and STAT is the result of
1117 'lstat'; exclude entries for which SELECT? does not return true."
1118 ;; Note: We don't stat FILE-NAME at each call, and thus we assume that
1119 ;; the file remains unchanged for the lifetime of SERVER.
1120 (let* ((args `(,file-name ,basename ,recursive? ,hash-algo ,select?))
1121 (cache (store-connection-add-to-store-cache server)))
1122 (or (hash-ref cache args)
1123 (let ((path (add-to-store server basename recursive?
1124 hash-algo file-name
1125 #:select? select?)))
1126 (hash-set! cache args path)
1127 path))))))
1128
1129 (define %not-slash
1130 (char-set-complement (char-set #\/)))
1131
1132 (define* (add-file-tree-to-store server tree
1133 #:key
1134 (hash-algo "sha256")
1135 (recursive? #t))
1136 "Add the given TREE to the store on SERVER. TREE must be an entry such as:
1137
1138 (\"my-tree\" directory
1139 (\"a\" regular (data \"hello\"))
1140 (\"b\" symlink \"a\")
1141 (\"c\" directory
1142 (\"d\" executable (file \"/bin/sh\"))))
1143
1144 This is a generalized version of 'add-to-store'. It allows you to reproduce
1145 an arbitrary directory layout in the store without creating a derivation."
1146
1147 ;; Note: The format of TREE was chosen to allow trees to be compared with
1148 ;; 'equal?', which in turn allows us to memoize things.
1149
1150 (define root
1151 ;; TREE is a single entry.
1152 (list tree))
1153
1154 (define basename
1155 (match tree
1156 ((name . _) name)))
1157
1158 (define (lookup file)
1159 (let loop ((components (string-tokenize file %not-slash))
1160 (tree root))
1161 (match components
1162 ((basename)
1163 (assoc basename tree))
1164 ((head . rest)
1165 (loop rest
1166 (match (assoc-ref tree head)
1167 (('directory . entries) entries)))))))
1168
1169 (define (file-type+size file)
1170 (match (lookup file)
1171 ((_ (and type (or 'directory 'symlink)) . _)
1172 (values type 0))
1173 ((_ type ('file file))
1174 (values type (stat:size (stat file))))
1175 ((_ type ('data (? string? data)))
1176 (values type (string-length data)))
1177 ((_ type ('data (? bytevector? data)))
1178 (values type (bytevector-length data)))))
1179
1180 (define (file-port file)
1181 (match (lookup file)
1182 ((_ (or 'regular 'executable) content)
1183 (match content
1184 (('file (? string? file))
1185 (open-file file "r0b"))
1186 (('data (? string? str))
1187 (open-input-string str))
1188 (('data (? bytevector? bv))
1189 (open-bytevector-input-port bv))))))
1190
1191 (define (symlink-target file)
1192 (match (lookup file)
1193 ((_ 'symlink target) target)))
1194
1195 (define (directory-entries directory)
1196 (match (lookup directory)
1197 ((_ 'directory (names . _) ...) names)))
1198
1199 (define cache
1200 (store-connection-add-to-store-cache server))
1201
1202 (or (hash-ref cache tree)
1203 (begin
1204 ;; We don't use the 'operation' macro so we can use 'write-file-tree'
1205 ;; instead of 'write-file'.
1206 (record-operation 'add-to-store/tree)
1207 (let ((port (store-connection-socket server)))
1208 (write-int (operation-id add-to-store) port)
1209 (write-string basename port)
1210 (write-int 1 port) ;obsolete, must be #t
1211 (write-int (if recursive? 1 0) port)
1212 (write-string hash-algo port)
1213 (write-file-tree basename port
1214 #:file-type+size file-type+size
1215 #:file-port file-port
1216 #:symlink-target symlink-target
1217 #:directory-entries directory-entries)
1218 (write-buffered-output server)
1219 (let loop ((done? (process-stderr server)))
1220 (or done? (loop (process-stderr server))))
1221 (let ((result (read-store-path port)))
1222 (hash-set! cache tree result)
1223 result)))))
1224
1225 (define build-things
1226 (let ((build (operation (build-things (string-list things)
1227 (integer mode))
1228 "Do it!"
1229 boolean))
1230 (build/old (operation (build-things (string-list things))
1231 "Do it!"
1232 boolean)))
1233 (lambda* (store things #:optional (mode (build-mode normal)))
1234 "Build THINGS, a list of store items which may be either '.drv' files or
1235 outputs, and return when the worker is done building them. Elements of THINGS
1236 that are not derivations can only be substituted and not built locally.
1237 Alternately, an element of THING can be a derivation/output name pair, in
1238 which case the daemon will attempt to substitute just the requested output of
1239 the derivation. Return #t on success."
1240 (let ((things (map (match-lambda
1241 ((drv . output) (string-append drv "!" output))
1242 (thing thing))
1243 things)))
1244 (parameterize ((current-store-protocol-version
1245 (store-connection-version store)))
1246 (if (>= (store-connection-minor-version store) 15)
1247 (build store things mode)
1248 (if (= mode (build-mode normal))
1249 (build/old store things)
1250 (raise (condition (&store-protocol-error
1251 (message "unsupported build mode")
1252 (status 1)))))))))))
1253
1254 (define-operation (add-temp-root (store-path path))
1255 "Make PATH a temporary root for the duration of the current session.
1256 Return #t."
1257 boolean)
1258
1259 (define-operation (add-indirect-root (string file-name))
1260 "Make the symlink FILE-NAME an indirect root for the garbage collector:
1261 whatever store item FILE-NAME points to will not be collected. Return #t on
1262 success.
1263
1264 FILE-NAME can be anywhere on the file system, but it must be an absolute file
1265 name--it is the caller's responsibility to ensure that it is an absolute file
1266 name."
1267 boolean)
1268
1269 (define %gc-roots-directory
1270 ;; The place where garbage collector roots (symlinks) are kept.
1271 (string-append %state-directory "/gcroots"))
1272
1273 (define (add-permanent-root target)
1274 "Add a garbage collector root pointing to TARGET, an element of the store,
1275 preventing TARGET from even being collected. This can also be used if TARGET
1276 does not exist yet.
1277
1278 Raise an error if the caller does not have write access to the GC root
1279 directory."
1280 (let* ((root (string-append %gc-roots-directory "/" (basename target))))
1281 (catch 'system-error
1282 (lambda ()
1283 (symlink target root))
1284 (lambda args
1285 ;; If ROOT already exists, this is fine; otherwise, re-throw.
1286 (unless (= EEXIST (system-error-errno args))
1287 (apply throw args))))))
1288
1289 (define (remove-permanent-root target)
1290 "Remove the permanent garbage collector root pointing to TARGET. Raise an
1291 error if there is no such root."
1292 (delete-file (string-append %gc-roots-directory "/" (basename target))))
1293
1294 (define references
1295 (operation (query-references (store-path path))
1296 "Return the list of references of PATH."
1297 store-path-list))
1298
1299 (define %reference-cache
1300 ;; Brute-force cache mapping store items to their list of references.
1301 ;; Caching matters because when building a profile in the presence of
1302 ;; grafts, we keep calling 'graft-derivation', which in turn calls
1303 ;; 'references/substitutes' many times with the same arguments. Ideally we
1304 ;; would use a cache associated with the daemon connection instead (XXX).
1305 (make-hash-table 100))
1306
1307 (define (references/substitutes store items)
1308 "Return the list of list of references of ITEMS; the result has the same
1309 length as ITEMS. Query substitute information for any item missing from the
1310 store at once. Raise a '&store-protocol-error' exception if reference
1311 information for one of ITEMS is missing."
1312 (let* ((requested items)
1313 (local-refs (map (lambda (item)
1314 (or (hash-ref %reference-cache item)
1315 (guard (c ((store-protocol-error? c) #f))
1316 (references store item))))
1317 items))
1318 (missing (fold-right (lambda (item local-ref result)
1319 (if local-ref
1320 result
1321 (cons item result)))
1322 '()
1323 items local-refs))
1324
1325 ;; Query all the substitutes at once to minimize the cost of
1326 ;; launching 'guix substitute' and making HTTP requests.
1327 (substs (if (null? missing)
1328 '()
1329 (substitutable-path-info store missing))))
1330 (when (< (length substs) (length missing))
1331 (raise (condition (&store-protocol-error
1332 (message "cannot determine \
1333 the list of references")
1334 (status 1)))))
1335
1336 ;; Intersperse SUBSTS and LOCAL-REFS.
1337 (let loop ((items items)
1338 (local-refs local-refs)
1339 (result '()))
1340 (match items
1341 (()
1342 (let ((result (reverse result)))
1343 (for-each (cut hash-set! %reference-cache <> <>)
1344 requested result)
1345 result))
1346 ((item items ...)
1347 (match local-refs
1348 ((#f tail ...)
1349 (loop items tail
1350 (cons (any (lambda (subst)
1351 (and (string=? (substitutable-path subst) item)
1352 (substitutable-references subst)))
1353 substs)
1354 result)))
1355 ((head tail ...)
1356 (loop items tail
1357 (cons head result)))))))))
1358
1359 (define* (fold-path store proc seed paths
1360 #:optional (relatives (cut references store <>)))
1361 "Call PROC for each of the RELATIVES of PATHS, exactly once, and return the
1362 result formed from the successive calls to PROC, the first of which is passed
1363 SEED."
1364 (let loop ((paths paths)
1365 (result seed)
1366 (seen vlist-null))
1367 (match paths
1368 ((path rest ...)
1369 (if (vhash-assoc path seen)
1370 (loop rest result seen)
1371 (let ((seen (vhash-cons path #t seen))
1372 (rest (append rest (relatives path)))
1373 (result (proc path result)))
1374 (loop rest result seen))))
1375 (()
1376 result))))
1377
1378 (define (requisites store paths)
1379 "Return the requisites of PATHS, including PATHS---i.e., their closures (all
1380 its references, recursively)."
1381 (fold-path store cons '() paths))
1382
1383 (define (topologically-sorted store paths)
1384 "Return a list containing PATHS and all their references sorted in
1385 topological order."
1386 (define (traverse)
1387 ;; Do a simple depth-first traversal of all of PATHS.
1388 (let loop ((paths paths)
1389 (visited vlist-null)
1390 (result '()))
1391 (define (visit n)
1392 (vhash-cons n #t visited))
1393
1394 (define (visited? n)
1395 (vhash-assoc n visited))
1396
1397 (match paths
1398 ((head tail ...)
1399 (if (visited? head)
1400 (loop tail visited result)
1401 (call-with-values
1402 (lambda ()
1403 (loop (references store head)
1404 (visit head)
1405 result))
1406 (lambda (visited result)
1407 (loop tail
1408 visited
1409 (cons head result))))))
1410 (()
1411 (values visited result)))))
1412
1413 (call-with-values traverse
1414 (lambda (_ result)
1415 (reverse result))))
1416
1417 (define referrers
1418 (operation (query-referrers (store-path path))
1419 "Return the list of path that refer to PATH."
1420 store-path-list))
1421
1422 (define valid-derivers
1423 (operation (query-valid-derivers (store-path path))
1424 "Return the list of valid \"derivers\" of PATH---i.e., all the
1425 .drv present in the store that have PATH among their outputs."
1426 store-path-list))
1427
1428 (define query-derivation-outputs ; avoid name clash with `derivation-outputs'
1429 (operation (query-derivation-outputs (store-path path))
1430 "Return the list of outputs of PATH, a .drv file."
1431 store-path-list))
1432
1433 (define-operation (has-substitutes? (store-path path))
1434 "Return #t if binary substitutes are available for PATH, and #f otherwise."
1435 boolean)
1436
1437 (define substitutable-paths
1438 (operation (query-substitutable-paths (store-path-list paths))
1439 "Return the subset of PATHS that is substitutable."
1440 store-path-list))
1441
1442 (define substitutable-path-info
1443 (operation (query-substitutable-path-infos (store-path-list paths))
1444 "Return information about the subset of PATHS that is
1445 substitutable. For each substitutable path, a `substitutable?' object is
1446 returned; thus, the resulting list can be shorter than PATHS. Furthermore,
1447 that there is no guarantee that the order of the resulting list matches the
1448 order of PATHS."
1449 substitutable-path-list))
1450
1451 (define %built-in-builders
1452 (let ((builders (operation (built-in-builders)
1453 "Return the built-in builders."
1454 string-list)))
1455 (lambda (store)
1456 "Return the names of the supported built-in derivation builders
1457 supported by STORE. The result is memoized for STORE."
1458 ;; Check whether STORE's version supports this RPC and built-in
1459 ;; derivation builders in general, which appeared in Guix > 0.11.0.
1460 ;; Return the empty list if it doesn't. Note that this RPC does not
1461 ;; exist in 'nix-daemon'.
1462 (if (or (> (store-connection-major-version store) #x100)
1463 (and (= (store-connection-major-version store) #x100)
1464 (>= (store-connection-minor-version store) #x60)))
1465 (builders store)
1466 '()))))
1467
1468 (define (built-in-builders store)
1469 "Return the names of the supported built-in derivation builders
1470 supported by STORE."
1471 (force (store-connection-built-in-builders store)))
1472
1473 (define-operation (optimize-store)
1474 "Optimize the store by hard-linking identical files (\"deduplication\".)
1475 Return #t on success."
1476 ;; Note: the daemon in Guix <= 0.8.2 does not implement this RPC.
1477 boolean)
1478
1479 (define verify-store
1480 (let ((verify (operation (verify-store (boolean check-contents?)
1481 (boolean repair?))
1482 "Verify the store."
1483 boolean)))
1484 (lambda* (store #:key check-contents? repair?)
1485 "Verify the integrity of the store and return false if errors remain,
1486 and true otherwise. When REPAIR? is true, repair any missing or altered store
1487 items by substituting them (this typically requires root privileges because it
1488 is not an atomic operation.) When CHECK-CONTENTS? is true, check the contents
1489 of store items; this can take a lot of time."
1490 (not (verify store check-contents? repair?)))))
1491
1492 (define (run-gc server action to-delete min-freed)
1493 "Perform the garbage-collector operation ACTION, one of the
1494 `gc-action' values. When ACTION is `delete-specific', the TO-DELETE is
1495 the list of store paths to delete. IGNORE-LIVENESS? should always be
1496 #f. MIN-FREED is the minimum amount of disk space to be freed, in
1497 bytes, before the GC can stop. Return the list of store paths delete,
1498 and the number of bytes freed."
1499 (let ((s (store-connection-socket server)))
1500 (write-int (operation-id collect-garbage) s)
1501 (write-int action s)
1502 (write-store-path-list to-delete s)
1503 (write-arg boolean #f s) ; ignore-liveness?
1504 (write-long-long min-freed s)
1505 (write-int 0 s) ; obsolete
1506 (when (>= (store-connection-minor-version server) 5)
1507 ;; Obsolete `use-atime' and `max-atime' parameters.
1508 (write-int 0 s)
1509 (write-int 0 s))
1510
1511 ;; Loop until the server is done sending error output.
1512 (let loop ((done? (process-stderr server)))
1513 (or done? (loop (process-stderr server))))
1514
1515 (let ((paths (read-store-path-list s))
1516 (freed (read-long-long s))
1517 (obsolete (read-long-long s)))
1518 (unless (null? paths)
1519 ;; To be on the safe side, completely invalidate both caches.
1520 ;; Otherwise we could end up returning store paths that are no longer
1521 ;; valid.
1522 (hash-clear! (store-connection-add-to-store-cache server))
1523 (hash-clear! (store-connection-add-text-to-store-cache server)))
1524
1525 (values paths freed))))
1526
1527 (define-syntax-rule (%long-long-max)
1528 ;; Maximum unsigned 64-bit integer.
1529 (- (expt 2 64) 1))
1530
1531 (define (live-paths server)
1532 "Return the list of live store paths---i.e., store paths still
1533 referenced, and thus not subject to being garbage-collected."
1534 (run-gc server (gc-action return-live) '() (%long-long-max)))
1535
1536 (define (dead-paths server)
1537 "Return the list of dead store paths---i.e., store paths no longer
1538 referenced, and thus subject to being garbage-collected."
1539 (run-gc server (gc-action return-dead) '() (%long-long-max)))
1540
1541 (define* (collect-garbage server #:optional (min-freed (%long-long-max)))
1542 "Collect garbage from the store at SERVER. If MIN-FREED is non-zero,
1543 then collect at least MIN-FREED bytes. Return the paths that were
1544 collected, and the number of bytes freed."
1545 (run-gc server (gc-action delete-dead) '() min-freed))
1546
1547 (define* (delete-paths server paths #:optional (min-freed (%long-long-max)))
1548 "Delete PATHS from the store at SERVER, if they are no longer
1549 referenced. If MIN-FREED is non-zero, then stop after at least
1550 MIN-FREED bytes have been collected. Return the paths that were
1551 collected, and the number of bytes freed."
1552 (run-gc server (gc-action delete-specific) paths min-freed))
1553
1554 (define (import-paths server port)
1555 "Import the set of store paths read from PORT into SERVER's store. An error
1556 is raised if the set of paths read from PORT is not signed (as per
1557 'export-path #:sign? #t'.) Return the list of store paths imported."
1558 (let ((s (store-connection-socket server)))
1559 (write-int (operation-id import-paths) s)
1560 (let loop ((done? (process-stderr server port)))
1561 (or done? (loop (process-stderr server port))))
1562 (read-store-path-list s)))
1563
1564 (define* (export-path server path port #:key (sign? #t))
1565 "Export PATH to PORT. When SIGN? is true, sign it."
1566 (let ((s (store-connection-socket server)))
1567 (write-int (operation-id export-path) s)
1568 (write-store-path path s)
1569 (write-arg boolean sign? s)
1570 (let loop ((done? (process-stderr server port)))
1571 (or done? (loop (process-stderr server port))))
1572 (= 1 (read-int s))))
1573
1574 (define* (export-paths server paths port #:key (sign? #t) recursive?)
1575 "Export the store paths listed in PATHS to PORT, in topological order,
1576 signing them if SIGN? is true. When RECURSIVE? is true, export the closure of
1577 PATHS---i.e., PATHS and all their dependencies."
1578 (define ordered
1579 (let ((sorted (topologically-sorted server paths)))
1580 ;; When RECURSIVE? is #f, filter out the references of PATHS.
1581 (if recursive?
1582 sorted
1583 (filter (cut member <> paths) sorted))))
1584
1585 (let loop ((paths ordered))
1586 (match paths
1587 (()
1588 (write-int 0 port))
1589 ((head tail ...)
1590 (write-int 1 port)
1591 (and (export-path server head port #:sign? sign?)
1592 (loop tail))))))
1593
1594 (define-operation (query-failed-paths)
1595 "Return the list of store items for which a build failure is cached.
1596
1597 The result is always the empty list unless the daemon was started with
1598 '--cache-failures'."
1599 store-path-list)
1600
1601 (define-operation (clear-failed-paths (store-path-list items))
1602 "Remove ITEMS from the list of cached build failures.
1603
1604 This makes sense only when the daemon was started with '--cache-failures'."
1605 boolean)
1606
1607 \f
1608 ;;;
1609 ;;; Store monad.
1610 ;;;
1611
1612 (define-syntax-rule (define-alias new old)
1613 (define-syntax new (identifier-syntax old)))
1614
1615 ;; The store monad allows us to (1) build sequences of operations in the
1616 ;; store, and (2) make the store an implicit part of the execution context,
1617 ;; rather than a parameter of every single function.
1618 (define-alias %store-monad %state-monad)
1619 (define-alias store-return state-return)
1620 (define-alias store-bind state-bind)
1621
1622 ;; Instantiate templates for %STORE-MONAD since it's syntactically different
1623 ;; from %STATE-MONAD.
1624 (template-directory instantiations %store-monad)
1625
1626 (define* (cache-object-mapping object keys result
1627 #:key (vhash-cons vhash-consq))
1628 "Augment the store's object cache with a mapping from OBJECT/KEYS to RESULT.
1629 KEYS is a list of additional keys to match against, for instance a (SYSTEM
1630 TARGET) tuple. Use VHASH-CONS to insert OBJECT into the cache.
1631
1632 OBJECT is typically a high-level object such as a <package> or an <origin>,
1633 and RESULT is typically its derivation."
1634 (lambda (store)
1635 (values result
1636 (store-connection
1637 (inherit store)
1638 (object-cache (vhash-cons object (cons result keys)
1639 (store-connection-object-cache store)))))))
1640
1641 (define record-cache-lookup!
1642 (if (profiled? "object-cache")
1643 (let ((fresh 0)
1644 (lookups 0)
1645 (hits 0))
1646 (register-profiling-hook!
1647 "object-cache"
1648 (lambda ()
1649 (format (current-error-port) "Store object cache:
1650 fresh caches: ~5@a
1651 lookups: ~5@a
1652 hits: ~5@a (~,1f%)~%"
1653 fresh lookups hits
1654 (if (zero? lookups)
1655 100.
1656 (* 100. (/ hits lookups))))))
1657
1658 (lambda (hit? cache)
1659 (set! fresh
1660 (if (eq? cache vlist-null)
1661 (+ 1 fresh)
1662 fresh))
1663 (set! lookups (+ 1 lookups))
1664 (set! hits (if hit? (+ hits 1) hits))))
1665 (lambda (x y)
1666 #t)))
1667
1668 (define* (lookup-cached-object object #:optional (keys '())
1669 #:key (vhash-fold* vhash-foldq*))
1670 "Return the cached object in the store connection corresponding to OBJECT
1671 and KEYS; use VHASH-FOLD* to look for OBJECT in the cache. KEYS is a list of
1672 additional keys to match against, and which are compared with 'equal?'.
1673 Return #f on failure and the cached result otherwise."
1674 (lambda (store)
1675 (let* ((cache (store-connection-object-cache store))
1676
1677 ;; Escape as soon as we find the result. This avoids traversing
1678 ;; the whole vlist chain and significantly reduces the number of
1679 ;; 'hashq' calls.
1680 (value (let/ec return
1681 (vhash-fold* (lambda (item result)
1682 (match item
1683 ((value . keys*)
1684 (if (equal? keys keys*)
1685 (return value)
1686 result))))
1687 #f object
1688 cache))))
1689 (record-cache-lookup! value cache)
1690 (values value store))))
1691
1692 (define* (%mcached mthunk object #:optional (keys '())
1693 #:key
1694 (vhash-cons vhash-consq)
1695 (vhash-fold* vhash-foldq*))
1696 "Bind the monadic value returned by MTHUNK, which supposedly corresponds to
1697 OBJECT/KEYS, or return its cached value. Use VHASH-CONS to insert OBJECT into
1698 the cache, and VHASH-FOLD* to look it up."
1699 (mlet %store-monad ((cached (lookup-cached-object object keys
1700 #:vhash-fold* vhash-fold*)))
1701 (if cached
1702 (return cached)
1703 (>>= (mthunk)
1704 (lambda (result)
1705 (cache-object-mapping object keys result
1706 #:vhash-cons vhash-cons))))))
1707
1708 (define-syntax mcached
1709 (syntax-rules (eq? equal?)
1710 "Run MVALUE, which corresponds to OBJECT/KEYS, and cache it; or return the
1711 value associated with OBJECT/KEYS in the store's object cache if there is
1712 one."
1713 ((_ eq? mvalue object keys ...)
1714 (%mcached (lambda () mvalue)
1715 object (list keys ...)
1716 #:vhash-cons vhash-consq
1717 #:vhash-fold* vhash-foldq*))
1718 ((_ equal? mvalue object keys ...)
1719 (%mcached (lambda () mvalue)
1720 object (list keys ...)
1721 #:vhash-cons vhash-cons
1722 #:vhash-fold* vhash-fold*))
1723 ((_ mvalue object keys ...)
1724 (mcached eq? mvalue object keys ...))))
1725
1726 (define (preserve-documentation original proc)
1727 "Return PROC with documentation taken from ORIGINAL."
1728 (set-object-property! proc 'documentation
1729 (procedure-property original 'documentation))
1730 proc)
1731
1732 (define (store-lift proc)
1733 "Lift PROC, a procedure whose first argument is a connection to the store,
1734 in the store monad."
1735 (preserve-documentation proc
1736 (lambda args
1737 (lambda (store)
1738 (values (apply proc store args) store)))))
1739
1740 (define (store-lower proc)
1741 "Lower PROC, a monadic procedure in %STORE-MONAD, to a \"normal\" procedure
1742 taking the store as its first argument."
1743 (preserve-documentation proc
1744 (lambda (store . args)
1745 (run-with-store store (apply proc args)))))
1746
1747 ;;
1748 ;; Store monad operators.
1749 ;;
1750
1751 (define* (binary-file name
1752 data ;bytevector
1753 #:optional (references '()))
1754 "Return as a monadic value the absolute file name in the store of the file
1755 containing DATA, a bytevector. REFERENCES is a list of store items that the
1756 resulting text file refers to; it defaults to the empty list."
1757 (lambda (store)
1758 (values (add-data-to-store store name data references)
1759 store)))
1760
1761 (define* (text-file name
1762 text ;string
1763 #:optional (references '()))
1764 "Return as a monadic value the absolute file name in the store of the file
1765 containing TEXT, a string. REFERENCES is a list of store items that the
1766 resulting text file refers to; it defaults to the empty list."
1767 (lambda (store)
1768 (values (add-text-to-store store name text references)
1769 store)))
1770
1771 (define* (interned-file file #:optional name
1772 #:key (recursive? #t) (select? true))
1773 "Return the name of FILE once interned in the store. Use NAME as its store
1774 name, or the basename of FILE if NAME is omitted.
1775
1776 When RECURSIVE? is true, the contents of FILE are added recursively; if FILE
1777 designates a flat file and RECURSIVE? is true, its contents are added, and its
1778 permission bits are kept.
1779
1780 When RECURSIVE? is true, call (SELECT? FILE STAT) for each directory entry,
1781 where FILE is the entry's absolute file name and STAT is the result of
1782 'lstat'; exclude entries for which SELECT? does not return true."
1783 (lambda (store)
1784 (values (add-to-store store (or name (basename file))
1785 recursive? "sha256" file
1786 #:select? select?)
1787 store)))
1788
1789 (define interned-file-tree
1790 (store-lift add-file-tree-to-store))
1791
1792 (define build
1793 ;; Monadic variant of 'build-things'.
1794 (store-lift build-things))
1795
1796 (define set-build-options*
1797 (store-lift set-build-options))
1798
1799 (define references*
1800 (store-lift references))
1801
1802 (define (query-path-info* item)
1803 "Monadic version of 'query-path-info' that returns #f when ITEM is not in
1804 the store."
1805 (lambda (store)
1806 (guard (c ((store-protocol-error? c)
1807 ;; ITEM is not in the store; return #f.
1808 (values #f store)))
1809 (values (query-path-info store item) store))))
1810
1811 (define-inlinable (current-system)
1812 ;; Consult the %CURRENT-SYSTEM fluid at bind time. This is equivalent to
1813 ;; (lift0 %current-system %store-monad), but inlinable, thus avoiding
1814 ;; closure allocation in some cases.
1815 (lambda (state)
1816 (values (%current-system) state)))
1817
1818 (define-inlinable (set-current-system system)
1819 ;; Set the %CURRENT-SYSTEM fluid at bind time.
1820 (lambda (state)
1821 (values (%current-system system) state)))
1822
1823 (define-inlinable (current-target-system)
1824 ;; Consult the %CURRENT-TARGET-SYSTEM fluid at bind time.
1825 (lambda (state)
1826 (values (%current-target-system) state)))
1827
1828 (define-inlinable (set-current-target target)
1829 ;; Set the %CURRENT-TARGET-SYSTEM fluid at bind time.
1830 (lambda (state)
1831 (values (%current-target-system target) state)))
1832
1833 (define %guile-for-build
1834 ;; The derivation of the Guile to be used within the build environment,
1835 ;; when using 'gexp->derivation' and co.
1836 (make-parameter #f))
1837
1838 (define set-store-connection-object-cache!
1839 (record-modifier <store-connection> 'object-cache))
1840
1841 (define* (run-with-store store mval
1842 #:key
1843 (guile-for-build (%guile-for-build))
1844 (system (%current-system))
1845 (target #f))
1846 "Run MVAL, a monadic value in the store monad, in STORE, an open store
1847 connection, and return the result."
1848 ;; Initialize the dynamic bindings here to avoid bad surprises. The
1849 ;; difficulty lies in the fact that dynamic bindings are resolved at
1850 ;; bind-time and not at call time, which can be disconcerting.
1851 (parameterize ((%guile-for-build guile-for-build)
1852 (%current-system system)
1853 (%current-target-system target))
1854 (call-with-values (lambda ()
1855 (run-with-state mval store))
1856 (lambda (result new-store)
1857 (when (and store new-store)
1858 ;; Copy the object cache from NEW-STORE so we don't fully discard
1859 ;; the state.
1860 (let ((cache (store-connection-object-cache new-store)))
1861 (set-store-connection-object-cache! store cache)))
1862 result))))
1863
1864 \f
1865 ;;;
1866 ;;; Store paths.
1867 ;;;
1868
1869 (define %store-prefix
1870 ;; Absolute path to the Nix store.
1871 (make-parameter %store-directory))
1872
1873 (define (compressed-hash bv size) ; `compressHash'
1874 "Given the hash stored in BV, return a compressed version thereof that fits
1875 in SIZE bytes."
1876 (define new (make-bytevector size 0))
1877 (define old-size (bytevector-length bv))
1878 (let loop ((i 0))
1879 (if (= i old-size)
1880 new
1881 (let* ((j (modulo i size))
1882 (o (bytevector-u8-ref new j)))
1883 (bytevector-u8-set! new j
1884 (logxor o (bytevector-u8-ref bv i)))
1885 (loop (+ 1 i))))))
1886
1887 (define (store-path type hash name) ; makeStorePath
1888 "Return the store path for NAME/HASH/TYPE."
1889 (let* ((s (string-append type ":sha256:"
1890 (bytevector->base16-string hash) ":"
1891 (%store-prefix) ":" name))
1892 (h (sha256 (string->utf8 s)))
1893 (c (compressed-hash h 20)))
1894 (string-append (%store-prefix) "/"
1895 (bytevector->nix-base32-string c) "-"
1896 name)))
1897
1898 (define (output-path output hash name) ; makeOutputPath
1899 "Return an output path for OUTPUT (the name of the output as a string) of
1900 the derivation called NAME with hash HASH."
1901 (store-path (string-append "output:" output) hash
1902 (if (string=? output "out")
1903 name
1904 (string-append name "-" output))))
1905
1906 (define* (fixed-output-path name hash
1907 #:key
1908 (output "out")
1909 (hash-algo 'sha256)
1910 (recursive? #t))
1911 "Return an output path for the fixed output OUTPUT defined by HASH of type
1912 HASH-ALGO, of the derivation NAME. RECURSIVE? has the same meaning as for
1913 'add-to-store'."
1914 (if (and recursive? (eq? hash-algo 'sha256))
1915 (store-path "source" hash name)
1916 (let ((tag (string-append "fixed:" output ":"
1917 (if recursive? "r:" "")
1918 (symbol->string hash-algo) ":"
1919 (bytevector->base16-string hash) ":")))
1920 (store-path (string-append "output:" output)
1921 (sha256 (string->utf8 tag))
1922 name))))
1923
1924 (define (store-path? path)
1925 "Return #t if PATH is a store path."
1926 ;; This is a lightweight check, compared to using a regexp, but this has to
1927 ;; be fast as it's called often in `derivation', for instance.
1928 ;; `isStorePath' in Nix does something similar.
1929 (string-prefix? (%store-prefix) path))
1930
1931 (define (direct-store-path? path)
1932 "Return #t if PATH is a store path, and not a sub-directory of a store path.
1933 This predicate is sometimes needed because files *under* a store path are not
1934 valid inputs."
1935 (and (store-path? path)
1936 (not (string=? path (%store-prefix)))
1937 (let ((len (+ 1 (string-length (%store-prefix)))))
1938 (not (string-index (substring path len) #\/)))))
1939
1940 (define (direct-store-path path)
1941 "Return the direct store path part of PATH, stripping components after
1942 '/gnu/store/xxxx-foo'."
1943 (let ((prefix-length (+ (string-length (%store-prefix)) 35)))
1944 (if (> (string-length path) prefix-length)
1945 (let ((slash (string-index path #\/ prefix-length)))
1946 (if slash (string-take path slash) path))
1947 path)))
1948
1949 (define (derivation-path? path)
1950 "Return #t if PATH is a derivation path."
1951 (and (store-path? path) (string-suffix? ".drv" path)))
1952
1953 (define (store-path-base path)
1954 "Return the base path of a path in the store."
1955 (and (string-prefix? (%store-prefix) path)
1956 (let ((base (string-drop path (+ 1 (string-length (%store-prefix))))))
1957 (and (> (string-length base) 33)
1958 (not (string-index base #\/))
1959 base))))
1960
1961 (define (store-path-package-name path)
1962 "Return the package name part of PATH, a file name in the store."
1963 (let ((base (store-path-base path)))
1964 (string-drop base (+ 32 1)))) ;32 hash part + 1 hyphen
1965
1966 (define (store-path-hash-part path)
1967 "Return the hash part of PATH as a base32 string, or #f if PATH is not a
1968 syntactically valid store path."
1969 (let* ((base (store-path-base path))
1970 (hash (string-take base 32)))
1971 (and (string-every %nix-base32-charset hash)
1972 hash)))
1973
1974 (define (derivation-log-file drv)
1975 "Return the build log file for DRV, a derivation file name, or #f if it
1976 could not be found."
1977 (let* ((base (basename drv))
1978 (log (string-append (or (getenv "GUIX_LOG_DIRECTORY")
1979 (string-append %localstatedir "/log/guix"))
1980 "/drvs/"
1981 (string-take base 2) "/"
1982 (string-drop base 2)))
1983 (log.gz (string-append log ".gz"))
1984 (log.bz2 (string-append log ".bz2")))
1985 (cond ((file-exists? log.gz) log.gz)
1986 ((file-exists? log.bz2) log.bz2)
1987 ((file-exists? log) log)
1988 (else #f))))
1989
1990 (define (log-file store file)
1991 "Return the build log file for FILE, or #f if none could be found. FILE
1992 must be an absolute store file name, or a derivation file name."
1993 (cond ((derivation-path? file)
1994 (derivation-log-file file))
1995 (else
1996 (match (valid-derivers store file)
1997 ((derivers ...)
1998 ;; Return the first that works.
1999 (any (cut log-file store <>) derivers))
2000 (_ #f)))))
2001
2002 ;;; Local Variables:
2003 ;;; eval: (put 'system-error-to-connection-error 'scheme-indent-function 1)
2004 ;;; End: