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